File: | tools/clang/lib/Sema/SemaType.cpp |
Warning: | line 4929, column 9 Value stored to 'ExpectNoDerefChunk' is never read |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// |
2 | // |
3 | // The LLVM Compiler Infrastructure |
4 | // |
5 | // This file is distributed under the University of Illinois Open Source |
6 | // License. See LICENSE.TXT for details. |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | // |
10 | // This file implements type-related semantic analysis. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #include "TypeLocBuilder.h" |
15 | #include "clang/AST/ASTConsumer.h" |
16 | #include "clang/AST/ASTContext.h" |
17 | #include "clang/AST/ASTMutationListener.h" |
18 | #include "clang/AST/ASTStructuralEquivalence.h" |
19 | #include "clang/AST/CXXInheritance.h" |
20 | #include "clang/AST/DeclObjC.h" |
21 | #include "clang/AST/DeclTemplate.h" |
22 | #include "clang/AST/Expr.h" |
23 | #include "clang/AST/TypeLoc.h" |
24 | #include "clang/AST/TypeLocVisitor.h" |
25 | #include "clang/Basic/PartialDiagnostic.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/ScopeInfo.h" |
32 | #include "clang/Sema/SemaInternal.h" |
33 | #include "clang/Sema/Template.h" |
34 | #include "clang/Sema/TemplateInstCallback.h" |
35 | #include "llvm/ADT/SmallPtrSet.h" |
36 | #include "llvm/ADT/SmallString.h" |
37 | #include "llvm/ADT/StringSwitch.h" |
38 | #include "llvm/Support/ErrorHandling.h" |
39 | |
40 | using namespace clang; |
41 | |
42 | enum TypeDiagSelector { |
43 | TDS_Function, |
44 | TDS_Pointer, |
45 | TDS_ObjCObjOrBlock |
46 | }; |
47 | |
48 | /// isOmittedBlockReturnType - Return true if this declarator is missing a |
49 | /// return type because this is a omitted return type on a block literal. |
50 | static bool isOmittedBlockReturnType(const Declarator &D) { |
51 | if (D.getContext() != DeclaratorContext::BlockLiteralContext || |
52 | D.getDeclSpec().hasTypeSpecifier()) |
53 | return false; |
54 | |
55 | if (D.getNumTypeObjects() == 0) |
56 | return true; // ^{ ... } |
57 | |
58 | if (D.getNumTypeObjects() == 1 && |
59 | D.getTypeObject(0).Kind == DeclaratorChunk::Function) |
60 | return true; // ^(int X, float Y) { ... } |
61 | |
62 | return false; |
63 | } |
64 | |
65 | /// diagnoseBadTypeAttribute - Diagnoses a type attribute which |
66 | /// doesn't apply to the given type. |
67 | static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, |
68 | QualType type) { |
69 | TypeDiagSelector WhichType; |
70 | bool useExpansionLoc = true; |
71 | switch (attr.getKind()) { |
72 | case ParsedAttr::AT_ObjCGC: |
73 | WhichType = TDS_Pointer; |
74 | break; |
75 | case ParsedAttr::AT_ObjCOwnership: |
76 | WhichType = TDS_ObjCObjOrBlock; |
77 | break; |
78 | default: |
79 | // Assume everything else was a function attribute. |
80 | WhichType = TDS_Function; |
81 | useExpansionLoc = false; |
82 | break; |
83 | } |
84 | |
85 | SourceLocation loc = attr.getLoc(); |
86 | StringRef name = attr.getName()->getName(); |
87 | |
88 | // The GC attributes are usually written with macros; special-case them. |
89 | IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident |
90 | : nullptr; |
91 | if (useExpansionLoc && loc.isMacroID() && II) { |
92 | if (II->isStr("strong")) { |
93 | if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; |
94 | } else if (II->isStr("weak")) { |
95 | if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; |
96 | } |
97 | } |
98 | |
99 | S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType |
100 | << type; |
101 | } |
102 | |
103 | // objc_gc applies to Objective-C pointers or, otherwise, to the |
104 | // smallest available pointer type (i.e. 'void*' in 'void**'). |
105 | #define OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership \ |
106 | case ParsedAttr::AT_ObjCGC: \ |
107 | case ParsedAttr::AT_ObjCOwnership |
108 | |
109 | // Calling convention attributes. |
110 | #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_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 \ |
111 | case ParsedAttr::AT_CDecl: \ |
112 | case ParsedAttr::AT_FastCall: \ |
113 | case ParsedAttr::AT_StdCall: \ |
114 | case ParsedAttr::AT_ThisCall: \ |
115 | case ParsedAttr::AT_RegCall: \ |
116 | case ParsedAttr::AT_Pascal: \ |
117 | case ParsedAttr::AT_SwiftCall: \ |
118 | case ParsedAttr::AT_VectorCall: \ |
119 | case ParsedAttr::AT_AArch64VectorPcs: \ |
120 | case ParsedAttr::AT_MSABI: \ |
121 | case ParsedAttr::AT_SysVABI: \ |
122 | case ParsedAttr::AT_Pcs: \ |
123 | case ParsedAttr::AT_IntelOclBicc: \ |
124 | case ParsedAttr::AT_PreserveMost: \ |
125 | case ParsedAttr::AT_PreserveAll |
126 | |
127 | // Function type attributes. |
128 | #define FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: 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_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 \ |
129 | case ParsedAttr::AT_NSReturnsRetained: \ |
130 | case ParsedAttr::AT_NoReturn: \ |
131 | case ParsedAttr::AT_Regparm: \ |
132 | case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ |
133 | case ParsedAttr::AT_AnyX86NoCfCheck: \ |
134 | 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_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 |
135 | |
136 | // Microsoft-specific type qualifiers. |
137 | #define MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr \ |
138 | case ParsedAttr::AT_Ptr32: \ |
139 | case ParsedAttr::AT_Ptr64: \ |
140 | case ParsedAttr::AT_SPtr: \ |
141 | case ParsedAttr::AT_UPtr |
142 | |
143 | // Nullability qualifiers. |
144 | #define NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullUnspecified \ |
145 | case ParsedAttr::AT_TypeNonNull: \ |
146 | case ParsedAttr::AT_TypeNullable: \ |
147 | case ParsedAttr::AT_TypeNullUnspecified |
148 | |
149 | namespace { |
150 | /// An object which stores processing state for the entire |
151 | /// GetTypeForDeclarator process. |
152 | class TypeProcessingState { |
153 | Sema &sema; |
154 | |
155 | /// The declarator being processed. |
156 | Declarator &declarator; |
157 | |
158 | /// The index of the declarator chunk we're currently processing. |
159 | /// May be the total number of valid chunks, indicating the |
160 | /// DeclSpec. |
161 | unsigned chunkIndex; |
162 | |
163 | /// Whether there are non-trivial modifications to the decl spec. |
164 | bool trivial; |
165 | |
166 | /// Whether we saved the attributes in the decl spec. |
167 | bool hasSavedAttrs; |
168 | |
169 | /// The original set of attributes on the DeclSpec. |
170 | SmallVector<ParsedAttr *, 2> savedAttrs; |
171 | |
172 | /// A list of attributes to diagnose the uselessness of when the |
173 | /// processing is complete. |
174 | SmallVector<ParsedAttr *, 2> ignoredTypeAttrs; |
175 | |
176 | /// Attributes corresponding to AttributedTypeLocs that we have not yet |
177 | /// populated. |
178 | // FIXME: The two-phase mechanism by which we construct Types and fill |
179 | // their TypeLocs makes it hard to correctly assign these. We keep the |
180 | // attributes in creation order as an attempt to make them line up |
181 | // properly. |
182 | using TypeAttrPair = std::pair<const AttributedType*, const Attr*>; |
183 | SmallVector<TypeAttrPair, 8> AttrsForTypes; |
184 | bool AttrsForTypesSorted = true; |
185 | |
186 | /// Flag to indicate we parsed a noderef attribute. This is used for |
187 | /// validating that noderef was used on a pointer or array. |
188 | bool parsedNoDeref; |
189 | |
190 | public: |
191 | TypeProcessingState(Sema &sema, Declarator &declarator) |
192 | : sema(sema), declarator(declarator), |
193 | chunkIndex(declarator.getNumTypeObjects()), trivial(true), |
194 | hasSavedAttrs(false), parsedNoDeref(false) {} |
195 | |
196 | Sema &getSema() const { |
197 | return sema; |
198 | } |
199 | |
200 | Declarator &getDeclarator() const { |
201 | return declarator; |
202 | } |
203 | |
204 | bool isProcessingDeclSpec() const { |
205 | return chunkIndex == declarator.getNumTypeObjects(); |
206 | } |
207 | |
208 | unsigned getCurrentChunkIndex() const { |
209 | return chunkIndex; |
210 | } |
211 | |
212 | void setCurrentChunkIndex(unsigned idx) { |
213 | assert(idx <= declarator.getNumTypeObjects())((idx <= declarator.getNumTypeObjects()) ? static_cast< void> (0) : __assert_fail ("idx <= declarator.getNumTypeObjects()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 213, __PRETTY_FUNCTION__)); |
214 | chunkIndex = idx; |
215 | } |
216 | |
217 | ParsedAttributesView &getCurrentAttributes() const { |
218 | if (isProcessingDeclSpec()) |
219 | return getMutableDeclSpec().getAttributes(); |
220 | return declarator.getTypeObject(chunkIndex).getAttrs(); |
221 | } |
222 | |
223 | /// Save the current set of attributes on the DeclSpec. |
224 | void saveDeclSpecAttrs() { |
225 | // Don't try to save them multiple times. |
226 | if (hasSavedAttrs) return; |
227 | |
228 | DeclSpec &spec = getMutableDeclSpec(); |
229 | for (ParsedAttr &AL : spec.getAttributes()) |
230 | savedAttrs.push_back(&AL); |
231 | trivial &= savedAttrs.empty(); |
232 | hasSavedAttrs = true; |
233 | } |
234 | |
235 | /// Record that we had nowhere to put the given type attribute. |
236 | /// We will diagnose such attributes later. |
237 | void addIgnoredTypeAttr(ParsedAttr &attr) { |
238 | ignoredTypeAttrs.push_back(&attr); |
239 | } |
240 | |
241 | /// Diagnose all the ignored type attributes, given that the |
242 | /// declarator worked out to the given type. |
243 | void diagnoseIgnoredTypeAttrs(QualType type) const { |
244 | for (auto *Attr : ignoredTypeAttrs) |
245 | diagnoseBadTypeAttribute(getSema(), *Attr, type); |
246 | } |
247 | |
248 | /// Get an attributed type for the given attribute, and remember the Attr |
249 | /// object so that we can attach it to the AttributedTypeLoc. |
250 | QualType getAttributedType(Attr *A, QualType ModifiedType, |
251 | QualType EquivType) { |
252 | QualType T = |
253 | sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType); |
254 | AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A}); |
255 | AttrsForTypesSorted = false; |
256 | return T; |
257 | } |
258 | |
259 | /// Extract and remove the Attr* for a given attributed type. |
260 | const Attr *takeAttrForAttributedType(const AttributedType *AT) { |
261 | if (!AttrsForTypesSorted) { |
262 | std::stable_sort(AttrsForTypes.begin(), AttrsForTypes.end(), |
263 | [](const TypeAttrPair &A, const TypeAttrPair &B) { |
264 | return A.first < B.first; |
265 | }); |
266 | AttrsForTypesSorted = true; |
267 | } |
268 | |
269 | // FIXME: This is quadratic if we have lots of reuses of the same |
270 | // attributed type. |
271 | for (auto It = std::partition_point( |
272 | AttrsForTypes.begin(), AttrsForTypes.end(), |
273 | [=](const TypeAttrPair &A) { return A.first < AT; }); |
274 | It != AttrsForTypes.end() && It->first == AT; ++It) { |
275 | if (It->second) { |
276 | const Attr *Result = It->second; |
277 | It->second = nullptr; |
278 | return Result; |
279 | } |
280 | } |
281 | |
282 | llvm_unreachable("no Attr* for AttributedType*")::llvm::llvm_unreachable_internal("no Attr* for AttributedType*" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 282); |
283 | } |
284 | |
285 | void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } |
286 | |
287 | bool didParseNoDeref() const { return parsedNoDeref; } |
288 | |
289 | ~TypeProcessingState() { |
290 | if (trivial) return; |
291 | |
292 | restoreDeclSpecAttrs(); |
293 | } |
294 | |
295 | private: |
296 | DeclSpec &getMutableDeclSpec() const { |
297 | return const_cast<DeclSpec&>(declarator.getDeclSpec()); |
298 | } |
299 | |
300 | void restoreDeclSpecAttrs() { |
301 | assert(hasSavedAttrs)((hasSavedAttrs) ? static_cast<void> (0) : __assert_fail ("hasSavedAttrs", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 301, __PRETTY_FUNCTION__)); |
302 | |
303 | getMutableDeclSpec().getAttributes().clearListOnly(); |
304 | for (ParsedAttr *AL : savedAttrs) |
305 | getMutableDeclSpec().getAttributes().addAtEnd(AL); |
306 | } |
307 | }; |
308 | } // end anonymous namespace |
309 | |
310 | static void moveAttrFromListToList(ParsedAttr &attr, |
311 | ParsedAttributesView &fromList, |
312 | ParsedAttributesView &toList) { |
313 | fromList.remove(&attr); |
314 | toList.addAtEnd(&attr); |
315 | } |
316 | |
317 | /// The location of a type attribute. |
318 | enum TypeAttrLocation { |
319 | /// The attribute is in the decl-specifier-seq. |
320 | TAL_DeclSpec, |
321 | /// The attribute is part of a DeclaratorChunk. |
322 | TAL_DeclChunk, |
323 | /// The attribute is immediately after the declaration's name. |
324 | TAL_DeclName |
325 | }; |
326 | |
327 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, |
328 | TypeAttrLocation TAL, ParsedAttributesView &attrs); |
329 | |
330 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, |
331 | QualType &type); |
332 | |
333 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, |
334 | ParsedAttr &attr, QualType &type); |
335 | |
336 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, |
337 | QualType &type); |
338 | |
339 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, |
340 | ParsedAttr &attr, QualType &type); |
341 | |
342 | static bool handleObjCPointerTypeAttr(TypeProcessingState &state, |
343 | ParsedAttr &attr, QualType &type) { |
344 | if (attr.getKind() == ParsedAttr::AT_ObjCGC) |
345 | return handleObjCGCTypeAttr(state, attr, type); |
346 | assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership)((attr.getKind() == ParsedAttr::AT_ObjCOwnership) ? static_cast <void> (0) : __assert_fail ("attr.getKind() == ParsedAttr::AT_ObjCOwnership" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 346, __PRETTY_FUNCTION__)); |
347 | return handleObjCOwnershipTypeAttr(state, attr, type); |
348 | } |
349 | |
350 | /// Given the index of a declarator chunk, check whether that chunk |
351 | /// directly specifies the return type of a function and, if so, find |
352 | /// an appropriate place for it. |
353 | /// |
354 | /// \param i - a notional index which the search will start |
355 | /// immediately inside |
356 | /// |
357 | /// \param onlyBlockPointers Whether we should only look into block |
358 | /// pointer types (vs. all pointer types). |
359 | static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, |
360 | unsigned i, |
361 | bool onlyBlockPointers) { |
362 | assert(i <= declarator.getNumTypeObjects())((i <= declarator.getNumTypeObjects()) ? static_cast<void > (0) : __assert_fail ("i <= declarator.getNumTypeObjects()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 362, __PRETTY_FUNCTION__)); |
363 | |
364 | DeclaratorChunk *result = nullptr; |
365 | |
366 | // First, look inwards past parens for a function declarator. |
367 | for (; i != 0; --i) { |
368 | DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); |
369 | switch (fnChunk.Kind) { |
370 | case DeclaratorChunk::Paren: |
371 | continue; |
372 | |
373 | // If we find anything except a function, bail out. |
374 | case DeclaratorChunk::Pointer: |
375 | case DeclaratorChunk::BlockPointer: |
376 | case DeclaratorChunk::Array: |
377 | case DeclaratorChunk::Reference: |
378 | case DeclaratorChunk::MemberPointer: |
379 | case DeclaratorChunk::Pipe: |
380 | return result; |
381 | |
382 | // If we do find a function declarator, scan inwards from that, |
383 | // looking for a (block-)pointer declarator. |
384 | case DeclaratorChunk::Function: |
385 | for (--i; i != 0; --i) { |
386 | DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); |
387 | switch (ptrChunk.Kind) { |
388 | case DeclaratorChunk::Paren: |
389 | case DeclaratorChunk::Array: |
390 | case DeclaratorChunk::Function: |
391 | case DeclaratorChunk::Reference: |
392 | case DeclaratorChunk::Pipe: |
393 | continue; |
394 | |
395 | case DeclaratorChunk::MemberPointer: |
396 | case DeclaratorChunk::Pointer: |
397 | if (onlyBlockPointers) |
398 | continue; |
399 | |
400 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
401 | |
402 | case DeclaratorChunk::BlockPointer: |
403 | result = &ptrChunk; |
404 | goto continue_outer; |
405 | } |
406 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 406); |
407 | } |
408 | |
409 | // If we run out of declarators doing that, we're done. |
410 | return result; |
411 | } |
412 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 412); |
413 | |
414 | // Okay, reconsider from our new point. |
415 | continue_outer: ; |
416 | } |
417 | |
418 | // Ran out of chunks, bail out. |
419 | return result; |
420 | } |
421 | |
422 | /// Given that an objc_gc attribute was written somewhere on a |
423 | /// declaration *other* than on the declarator itself (for which, use |
424 | /// distributeObjCPointerTypeAttrFromDeclarator), and given that it |
425 | /// didn't apply in whatever position it was written in, try to move |
426 | /// it to a more appropriate position. |
427 | static void distributeObjCPointerTypeAttr(TypeProcessingState &state, |
428 | ParsedAttr &attr, QualType type) { |
429 | Declarator &declarator = state.getDeclarator(); |
430 | |
431 | // Move it to the outermost normal or block pointer declarator. |
432 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { |
433 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); |
434 | switch (chunk.Kind) { |
435 | case DeclaratorChunk::Pointer: |
436 | case DeclaratorChunk::BlockPointer: { |
437 | // But don't move an ARC ownership attribute to the return type |
438 | // of a block. |
439 | DeclaratorChunk *destChunk = nullptr; |
440 | if (state.isProcessingDeclSpec() && |
441 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) |
442 | destChunk = maybeMovePastReturnType(declarator, i - 1, |
443 | /*onlyBlockPointers=*/true); |
444 | if (!destChunk) destChunk = &chunk; |
445 | |
446 | moveAttrFromListToList(attr, state.getCurrentAttributes(), |
447 | destChunk->getAttrs()); |
448 | return; |
449 | } |
450 | |
451 | case DeclaratorChunk::Paren: |
452 | case DeclaratorChunk::Array: |
453 | continue; |
454 | |
455 | // We may be starting at the return type of a block. |
456 | case DeclaratorChunk::Function: |
457 | if (state.isProcessingDeclSpec() && |
458 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) { |
459 | if (DeclaratorChunk *dest = maybeMovePastReturnType( |
460 | declarator, i, |
461 | /*onlyBlockPointers=*/true)) { |
462 | moveAttrFromListToList(attr, state.getCurrentAttributes(), |
463 | dest->getAttrs()); |
464 | return; |
465 | } |
466 | } |
467 | goto error; |
468 | |
469 | // Don't walk through these. |
470 | case DeclaratorChunk::Reference: |
471 | case DeclaratorChunk::MemberPointer: |
472 | case DeclaratorChunk::Pipe: |
473 | goto error; |
474 | } |
475 | } |
476 | error: |
477 | |
478 | diagnoseBadTypeAttribute(state.getSema(), attr, type); |
479 | } |
480 | |
481 | /// Distribute an objc_gc type attribute that was written on the |
482 | /// declarator. |
483 | static void distributeObjCPointerTypeAttrFromDeclarator( |
484 | TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { |
485 | Declarator &declarator = state.getDeclarator(); |
486 | |
487 | // objc_gc goes on the innermost pointer to something that's not a |
488 | // pointer. |
489 | unsigned innermost = -1U; |
490 | bool considerDeclSpec = true; |
491 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { |
492 | DeclaratorChunk &chunk = declarator.getTypeObject(i); |
493 | switch (chunk.Kind) { |
494 | case DeclaratorChunk::Pointer: |
495 | case DeclaratorChunk::BlockPointer: |
496 | innermost = i; |
497 | continue; |
498 | |
499 | case DeclaratorChunk::Reference: |
500 | case DeclaratorChunk::MemberPointer: |
501 | case DeclaratorChunk::Paren: |
502 | case DeclaratorChunk::Array: |
503 | case DeclaratorChunk::Pipe: |
504 | continue; |
505 | |
506 | case DeclaratorChunk::Function: |
507 | considerDeclSpec = false; |
508 | goto done; |
509 | } |
510 | } |
511 | done: |
512 | |
513 | // That might actually be the decl spec if we weren't blocked by |
514 | // anything in the declarator. |
515 | if (considerDeclSpec) { |
516 | if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { |
517 | // Splice the attribute into the decl spec. Prevents the |
518 | // attribute from being applied multiple times and gives |
519 | // the source-location-filler something to work with. |
520 | state.saveDeclSpecAttrs(); |
521 | moveAttrFromListToList(attr, declarator.getAttributes(), |
522 | declarator.getMutableDeclSpec().getAttributes()); |
523 | return; |
524 | } |
525 | } |
526 | |
527 | // Otherwise, if we found an appropriate chunk, splice the attribute |
528 | // into it. |
529 | if (innermost != -1U) { |
530 | moveAttrFromListToList(attr, declarator.getAttributes(), |
531 | declarator.getTypeObject(innermost).getAttrs()); |
532 | return; |
533 | } |
534 | |
535 | // Otherwise, diagnose when we're done building the type. |
536 | declarator.getAttributes().remove(&attr); |
537 | state.addIgnoredTypeAttr(attr); |
538 | } |
539 | |
540 | /// A function type attribute was written somewhere in a declaration |
541 | /// *other* than on the declarator itself or in the decl spec. Given |
542 | /// that it didn't apply in whatever position it was written in, try |
543 | /// to move it to a more appropriate position. |
544 | static void distributeFunctionTypeAttr(TypeProcessingState &state, |
545 | ParsedAttr &attr, QualType type) { |
546 | Declarator &declarator = state.getDeclarator(); |
547 | |
548 | // Try to push the attribute from the return type of a function to |
549 | // the function itself. |
550 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { |
551 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); |
552 | switch (chunk.Kind) { |
553 | case DeclaratorChunk::Function: |
554 | moveAttrFromListToList(attr, state.getCurrentAttributes(), |
555 | chunk.getAttrs()); |
556 | return; |
557 | |
558 | case DeclaratorChunk::Paren: |
559 | case DeclaratorChunk::Pointer: |
560 | case DeclaratorChunk::BlockPointer: |
561 | case DeclaratorChunk::Array: |
562 | case DeclaratorChunk::Reference: |
563 | case DeclaratorChunk::MemberPointer: |
564 | case DeclaratorChunk::Pipe: |
565 | continue; |
566 | } |
567 | } |
568 | |
569 | diagnoseBadTypeAttribute(state.getSema(), attr, type); |
570 | } |
571 | |
572 | /// Try to distribute a function type attribute to the innermost |
573 | /// function chunk or type. Returns true if the attribute was |
574 | /// distributed, false if no location was found. |
575 | static bool distributeFunctionTypeAttrToInnermost( |
576 | TypeProcessingState &state, ParsedAttr &attr, |
577 | ParsedAttributesView &attrList, QualType &declSpecType) { |
578 | Declarator &declarator = state.getDeclarator(); |
579 | |
580 | // Put it on the innermost function chunk, if there is one. |
581 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { |
582 | DeclaratorChunk &chunk = declarator.getTypeObject(i); |
583 | if (chunk.Kind != DeclaratorChunk::Function) continue; |
584 | |
585 | moveAttrFromListToList(attr, attrList, chunk.getAttrs()); |
586 | return true; |
587 | } |
588 | |
589 | return handleFunctionTypeAttr(state, attr, declSpecType); |
590 | } |
591 | |
592 | /// A function type attribute was written in the decl spec. Try to |
593 | /// apply it somewhere. |
594 | static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, |
595 | ParsedAttr &attr, |
596 | QualType &declSpecType) { |
597 | state.saveDeclSpecAttrs(); |
598 | |
599 | // C++11 attributes before the decl specifiers actually appertain to |
600 | // the declarators. Move them straight there. We don't support the |
601 | // 'put them wherever you like' semantics we allow for GNU attributes. |
602 | if (attr.isCXX11Attribute()) { |
603 | moveAttrFromListToList(attr, state.getCurrentAttributes(), |
604 | state.getDeclarator().getAttributes()); |
605 | return; |
606 | } |
607 | |
608 | // Try to distribute to the innermost. |
609 | if (distributeFunctionTypeAttrToInnermost( |
610 | state, attr, state.getCurrentAttributes(), declSpecType)) |
611 | return; |
612 | |
613 | // If that failed, diagnose the bad attribute when the declarator is |
614 | // fully built. |
615 | state.addIgnoredTypeAttr(attr); |
616 | } |
617 | |
618 | /// A function type attribute was written on the declarator. Try to |
619 | /// apply it somewhere. |
620 | static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, |
621 | ParsedAttr &attr, |
622 | QualType &declSpecType) { |
623 | Declarator &declarator = state.getDeclarator(); |
624 | |
625 | // Try to distribute to the innermost. |
626 | if (distributeFunctionTypeAttrToInnermost( |
627 | state, attr, declarator.getAttributes(), declSpecType)) |
628 | return; |
629 | |
630 | // If that failed, diagnose the bad attribute when the declarator is |
631 | // fully built. |
632 | declarator.getAttributes().remove(&attr); |
633 | state.addIgnoredTypeAttr(attr); |
634 | } |
635 | |
636 | /// Given that there are attributes written on the declarator |
637 | /// itself, try to distribute any type attributes to the appropriate |
638 | /// declarator chunk. |
639 | /// |
640 | /// These are attributes like the following: |
641 | /// int f ATTR; |
642 | /// int (f ATTR)(); |
643 | /// but not necessarily this: |
644 | /// int f() ATTR; |
645 | static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, |
646 | QualType &declSpecType) { |
647 | // Collect all the type attributes from the declarator itself. |
648 | assert(!state.getDeclarator().getAttributes().empty() &&((!state.getDeclarator().getAttributes().empty() && "declarator has no attrs!" ) ? static_cast<void> (0) : __assert_fail ("!state.getDeclarator().getAttributes().empty() && \"declarator has no attrs!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 649, __PRETTY_FUNCTION__)) |
649 | "declarator has no attrs!")((!state.getDeclarator().getAttributes().empty() && "declarator has no attrs!" ) ? static_cast<void> (0) : __assert_fail ("!state.getDeclarator().getAttributes().empty() && \"declarator has no attrs!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 649, __PRETTY_FUNCTION__)); |
650 | // The called functions in this loop actually remove things from the current |
651 | // list, so iterating over the existing list isn't possible. Instead, make a |
652 | // non-owning copy and iterate over that. |
653 | ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; |
654 | for (ParsedAttr &attr : AttrsCopy) { |
655 | // Do not distribute C++11 attributes. They have strict rules for what |
656 | // they appertain to. |
657 | if (attr.isCXX11Attribute()) |
658 | continue; |
659 | |
660 | switch (attr.getKind()) { |
661 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: |
662 | distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); |
663 | break; |
664 | |
665 | FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: 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_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: |
666 | distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType); |
667 | break; |
668 | |
669 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: |
670 | // Microsoft type attributes cannot go after the declarator-id. |
671 | continue; |
672 | |
673 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullUnspecified: |
674 | // Nullability specifiers cannot go after the declarator-id. |
675 | |
676 | // Objective-C __kindof does not get distributed. |
677 | case ParsedAttr::AT_ObjCKindOf: |
678 | continue; |
679 | |
680 | default: |
681 | break; |
682 | } |
683 | } |
684 | } |
685 | |
686 | /// Add a synthetic '()' to a block-literal declarator if it is |
687 | /// required, given the return type. |
688 | static void maybeSynthesizeBlockSignature(TypeProcessingState &state, |
689 | QualType declSpecType) { |
690 | Declarator &declarator = state.getDeclarator(); |
691 | |
692 | // First, check whether the declarator would produce a function, |
693 | // i.e. whether the innermost semantic chunk is a function. |
694 | if (declarator.isFunctionDeclarator()) { |
695 | // If so, make that declarator a prototyped declarator. |
696 | declarator.getFunctionTypeInfo().hasPrototype = true; |
697 | return; |
698 | } |
699 | |
700 | // If there are any type objects, the type as written won't name a |
701 | // function, regardless of the decl spec type. This is because a |
702 | // block signature declarator is always an abstract-declarator, and |
703 | // abstract-declarators can't just be parentheses chunks. Therefore |
704 | // we need to build a function chunk unless there are no type |
705 | // objects and the decl spec type is a function. |
706 | if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) |
707 | return; |
708 | |
709 | // Note that there *are* cases with invalid declarators where |
710 | // declarators consist solely of parentheses. In general, these |
711 | // occur only in failed efforts to make function declarators, so |
712 | // faking up the function chunk is still the right thing to do. |
713 | |
714 | // Otherwise, we need to fake up a function declarator. |
715 | SourceLocation loc = declarator.getBeginLoc(); |
716 | |
717 | // ...and *prepend* it to the declarator. |
718 | SourceLocation NoLoc; |
719 | declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( |
720 | /*HasProto=*/true, |
721 | /*IsAmbiguous=*/false, |
722 | /*LParenLoc=*/NoLoc, |
723 | /*ArgInfo=*/nullptr, |
724 | /*NumArgs=*/0, |
725 | /*EllipsisLoc=*/NoLoc, |
726 | /*RParenLoc=*/NoLoc, |
727 | /*TypeQuals=*/0, |
728 | /*RefQualifierIsLvalueRef=*/true, |
729 | /*RefQualifierLoc=*/NoLoc, |
730 | /*ConstQualifierLoc=*/NoLoc, |
731 | /*VolatileQualifierLoc=*/NoLoc, |
732 | /*RestrictQualifierLoc=*/NoLoc, |
733 | /*MutableLoc=*/NoLoc, EST_None, |
734 | /*ESpecRange=*/SourceRange(), |
735 | /*Exceptions=*/nullptr, |
736 | /*ExceptionRanges=*/nullptr, |
737 | /*NumExceptions=*/0, |
738 | /*NoexceptExpr=*/nullptr, |
739 | /*ExceptionSpecTokens=*/nullptr, |
740 | /*DeclsInPrototype=*/None, |
741 | loc, loc, declarator)); |
742 | |
743 | // For consistency, make sure the state still has us as processing |
744 | // the decl spec. |
745 | assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1)((state.getCurrentChunkIndex() == declarator.getNumTypeObjects () - 1) ? static_cast<void> (0) : __assert_fail ("state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 745, __PRETTY_FUNCTION__)); |
746 | state.setCurrentChunkIndex(declarator.getNumTypeObjects()); |
747 | } |
748 | |
749 | static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, |
750 | unsigned &TypeQuals, |
751 | QualType TypeSoFar, |
752 | unsigned RemoveTQs, |
753 | unsigned DiagID) { |
754 | // If this occurs outside a template instantiation, warn the user about |
755 | // it; they probably didn't mean to specify a redundant qualifier. |
756 | typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; |
757 | for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), |
758 | QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), |
759 | QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), |
760 | QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { |
761 | if (!(RemoveTQs & Qual.first)) |
762 | continue; |
763 | |
764 | if (!S.inTemplateInstantiation()) { |
765 | if (TypeQuals & Qual.first) |
766 | S.Diag(Qual.second, DiagID) |
767 | << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar |
768 | << FixItHint::CreateRemoval(Qual.second); |
769 | } |
770 | |
771 | TypeQuals &= ~Qual.first; |
772 | } |
773 | } |
774 | |
775 | /// Return true if this is omitted block return type. Also check type |
776 | /// attributes and type qualifiers when returning true. |
777 | static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, |
778 | QualType Result) { |
779 | if (!isOmittedBlockReturnType(declarator)) |
780 | return false; |
781 | |
782 | // Warn if we see type attributes for omitted return type on a block literal. |
783 | SmallVector<ParsedAttr *, 2> ToBeRemoved; |
784 | for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { |
785 | if (AL.isInvalid() || !AL.isTypeAttr()) |
786 | continue; |
787 | S.Diag(AL.getLoc(), |
788 | diag::warn_block_literal_attributes_on_omitted_return_type) |
789 | << AL.getName(); |
790 | ToBeRemoved.push_back(&AL); |
791 | } |
792 | // Remove bad attributes from the list. |
793 | for (ParsedAttr *AL : ToBeRemoved) |
794 | declarator.getMutableDeclSpec().getAttributes().remove(AL); |
795 | |
796 | // Warn if we see type qualifiers for omitted return type on a block literal. |
797 | const DeclSpec &DS = declarator.getDeclSpec(); |
798 | unsigned TypeQuals = DS.getTypeQualifiers(); |
799 | diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, |
800 | diag::warn_block_literal_qualifiers_on_omitted_return_type); |
801 | declarator.getMutableDeclSpec().ClearTypeQualifiers(); |
802 | |
803 | return true; |
804 | } |
805 | |
806 | /// Apply Objective-C type arguments to the given type. |
807 | static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, |
808 | ArrayRef<TypeSourceInfo *> typeArgs, |
809 | SourceRange typeArgsRange, |
810 | bool failOnError = false) { |
811 | // We can only apply type arguments to an Objective-C class type. |
812 | const auto *objcObjectType = type->getAs<ObjCObjectType>(); |
813 | if (!objcObjectType || !objcObjectType->getInterface()) { |
814 | S.Diag(loc, diag::err_objc_type_args_non_class) |
815 | << type |
816 | << typeArgsRange; |
817 | |
818 | if (failOnError) |
819 | return QualType(); |
820 | return type; |
821 | } |
822 | |
823 | // The class type must be parameterized. |
824 | ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); |
825 | ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); |
826 | if (!typeParams) { |
827 | S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) |
828 | << objcClass->getDeclName() |
829 | << FixItHint::CreateRemoval(typeArgsRange); |
830 | |
831 | if (failOnError) |
832 | return QualType(); |
833 | |
834 | return type; |
835 | } |
836 | |
837 | // The type must not already be specialized. |
838 | if (objcObjectType->isSpecialized()) { |
839 | S.Diag(loc, diag::err_objc_type_args_specialized_class) |
840 | << type |
841 | << FixItHint::CreateRemoval(typeArgsRange); |
842 | |
843 | if (failOnError) |
844 | return QualType(); |
845 | |
846 | return type; |
847 | } |
848 | |
849 | // Check the type arguments. |
850 | SmallVector<QualType, 4> finalTypeArgs; |
851 | unsigned numTypeParams = typeParams->size(); |
852 | bool anyPackExpansions = false; |
853 | for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { |
854 | TypeSourceInfo *typeArgInfo = typeArgs[i]; |
855 | QualType typeArg = typeArgInfo->getType(); |
856 | |
857 | // Type arguments cannot have explicit qualifiers or nullability. |
858 | // We ignore indirect sources of these, e.g. behind typedefs or |
859 | // template arguments. |
860 | if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { |
861 | bool diagnosed = false; |
862 | SourceRange rangeToRemove; |
863 | if (auto attr = qual.getAs<AttributedTypeLoc>()) { |
864 | rangeToRemove = attr.getLocalSourceRange(); |
865 | if (attr.getTypePtr()->getImmediateNullability()) { |
866 | typeArg = attr.getTypePtr()->getModifiedType(); |
867 | S.Diag(attr.getBeginLoc(), |
868 | diag::err_objc_type_arg_explicit_nullability) |
869 | << typeArg << FixItHint::CreateRemoval(rangeToRemove); |
870 | diagnosed = true; |
871 | } |
872 | } |
873 | |
874 | if (!diagnosed) { |
875 | S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified) |
876 | << typeArg << typeArg.getQualifiers().getAsString() |
877 | << FixItHint::CreateRemoval(rangeToRemove); |
878 | } |
879 | } |
880 | |
881 | // Remove qualifiers even if they're non-local. |
882 | typeArg = typeArg.getUnqualifiedType(); |
883 | |
884 | finalTypeArgs.push_back(typeArg); |
885 | |
886 | if (typeArg->getAs<PackExpansionType>()) |
887 | anyPackExpansions = true; |
888 | |
889 | // Find the corresponding type parameter, if there is one. |
890 | ObjCTypeParamDecl *typeParam = nullptr; |
891 | if (!anyPackExpansions) { |
892 | if (i < numTypeParams) { |
893 | typeParam = typeParams->begin()[i]; |
894 | } else { |
895 | // Too many arguments. |
896 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) |
897 | << false |
898 | << objcClass->getDeclName() |
899 | << (unsigned)typeArgs.size() |
900 | << numTypeParams; |
901 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) |
902 | << objcClass; |
903 | |
904 | if (failOnError) |
905 | return QualType(); |
906 | |
907 | return type; |
908 | } |
909 | } |
910 | |
911 | // Objective-C object pointer types must be substitutable for the bounds. |
912 | if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { |
913 | // If we don't have a type parameter to match against, assume |
914 | // everything is fine. There was a prior pack expansion that |
915 | // means we won't be able to match anything. |
916 | if (!typeParam) { |
917 | assert(anyPackExpansions && "Too many arguments?")((anyPackExpansions && "Too many arguments?") ? static_cast <void> (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 917, __PRETTY_FUNCTION__)); |
918 | continue; |
919 | } |
920 | |
921 | // Retrieve the bound. |
922 | QualType bound = typeParam->getUnderlyingType(); |
923 | const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); |
924 | |
925 | // Determine whether the type argument is substitutable for the bound. |
926 | if (typeArgObjC->isObjCIdType()) { |
927 | // When the type argument is 'id', the only acceptable type |
928 | // parameter bound is 'id'. |
929 | if (boundObjC->isObjCIdType()) |
930 | continue; |
931 | } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { |
932 | // Otherwise, we follow the assignability rules. |
933 | continue; |
934 | } |
935 | |
936 | // Diagnose the mismatch. |
937 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), |
938 | diag::err_objc_type_arg_does_not_match_bound) |
939 | << typeArg << bound << typeParam->getDeclName(); |
940 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) |
941 | << typeParam->getDeclName(); |
942 | |
943 | if (failOnError) |
944 | return QualType(); |
945 | |
946 | return type; |
947 | } |
948 | |
949 | // Block pointer types are permitted for unqualified 'id' bounds. |
950 | if (typeArg->isBlockPointerType()) { |
951 | // If we don't have a type parameter to match against, assume |
952 | // everything is fine. There was a prior pack expansion that |
953 | // means we won't be able to match anything. |
954 | if (!typeParam) { |
955 | assert(anyPackExpansions && "Too many arguments?")((anyPackExpansions && "Too many arguments?") ? static_cast <void> (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 955, __PRETTY_FUNCTION__)); |
956 | continue; |
957 | } |
958 | |
959 | // Retrieve the bound. |
960 | QualType bound = typeParam->getUnderlyingType(); |
961 | if (bound->isBlockCompatibleObjCPointerType(S.Context)) |
962 | continue; |
963 | |
964 | // Diagnose the mismatch. |
965 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), |
966 | diag::err_objc_type_arg_does_not_match_bound) |
967 | << typeArg << bound << typeParam->getDeclName(); |
968 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) |
969 | << typeParam->getDeclName(); |
970 | |
971 | if (failOnError) |
972 | return QualType(); |
973 | |
974 | return type; |
975 | } |
976 | |
977 | // Dependent types will be checked at instantiation time. |
978 | if (typeArg->isDependentType()) { |
979 | continue; |
980 | } |
981 | |
982 | // Diagnose non-id-compatible type arguments. |
983 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), |
984 | diag::err_objc_type_arg_not_id_compatible) |
985 | << typeArg << typeArgInfo->getTypeLoc().getSourceRange(); |
986 | |
987 | if (failOnError) |
988 | return QualType(); |
989 | |
990 | return type; |
991 | } |
992 | |
993 | // Make sure we didn't have the wrong number of arguments. |
994 | if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { |
995 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) |
996 | << (typeArgs.size() < typeParams->size()) |
997 | << objcClass->getDeclName() |
998 | << (unsigned)finalTypeArgs.size() |
999 | << (unsigned)numTypeParams; |
1000 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) |
1001 | << objcClass; |
1002 | |
1003 | if (failOnError) |
1004 | return QualType(); |
1005 | |
1006 | return type; |
1007 | } |
1008 | |
1009 | // Success. Form the specialized type. |
1010 | return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); |
1011 | } |
1012 | |
1013 | QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, |
1014 | SourceLocation ProtocolLAngleLoc, |
1015 | ArrayRef<ObjCProtocolDecl *> Protocols, |
1016 | ArrayRef<SourceLocation> ProtocolLocs, |
1017 | SourceLocation ProtocolRAngleLoc, |
1018 | bool FailOnError) { |
1019 | QualType Result = QualType(Decl->getTypeForDecl(), 0); |
1020 | if (!Protocols.empty()) { |
1021 | bool HasError; |
1022 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, |
1023 | HasError); |
1024 | if (HasError) { |
1025 | Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) |
1026 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); |
1027 | if (FailOnError) Result = QualType(); |
1028 | } |
1029 | if (FailOnError && Result.isNull()) |
1030 | return QualType(); |
1031 | } |
1032 | |
1033 | return Result; |
1034 | } |
1035 | |
1036 | QualType Sema::BuildObjCObjectType(QualType BaseType, |
1037 | SourceLocation Loc, |
1038 | SourceLocation TypeArgsLAngleLoc, |
1039 | ArrayRef<TypeSourceInfo *> TypeArgs, |
1040 | SourceLocation TypeArgsRAngleLoc, |
1041 | SourceLocation ProtocolLAngleLoc, |
1042 | ArrayRef<ObjCProtocolDecl *> Protocols, |
1043 | ArrayRef<SourceLocation> ProtocolLocs, |
1044 | SourceLocation ProtocolRAngleLoc, |
1045 | bool FailOnError) { |
1046 | QualType Result = BaseType; |
1047 | if (!TypeArgs.empty()) { |
1048 | Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, |
1049 | SourceRange(TypeArgsLAngleLoc, |
1050 | TypeArgsRAngleLoc), |
1051 | FailOnError); |
1052 | if (FailOnError && Result.isNull()) |
1053 | return QualType(); |
1054 | } |
1055 | |
1056 | if (!Protocols.empty()) { |
1057 | bool HasError; |
1058 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, |
1059 | HasError); |
1060 | if (HasError) { |
1061 | Diag(Loc, diag::err_invalid_protocol_qualifiers) |
1062 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); |
1063 | if (FailOnError) Result = QualType(); |
1064 | } |
1065 | if (FailOnError && Result.isNull()) |
1066 | return QualType(); |
1067 | } |
1068 | |
1069 | return Result; |
1070 | } |
1071 | |
1072 | TypeResult Sema::actOnObjCProtocolQualifierType( |
1073 | SourceLocation lAngleLoc, |
1074 | ArrayRef<Decl *> protocols, |
1075 | ArrayRef<SourceLocation> protocolLocs, |
1076 | SourceLocation rAngleLoc) { |
1077 | // Form id<protocol-list>. |
1078 | QualType Result = Context.getObjCObjectType( |
1079 | Context.ObjCBuiltinIdTy, { }, |
1080 | llvm::makeArrayRef( |
1081 | (ObjCProtocolDecl * const *)protocols.data(), |
1082 | protocols.size()), |
1083 | false); |
1084 | Result = Context.getObjCObjectPointerType(Result); |
1085 | |
1086 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); |
1087 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); |
1088 | |
1089 | auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); |
1090 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit |
1091 | |
1092 | auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() |
1093 | .castAs<ObjCObjectTypeLoc>(); |
1094 | ObjCObjectTL.setHasBaseTypeAsWritten(false); |
1095 | ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); |
1096 | |
1097 | // No type arguments. |
1098 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); |
1099 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); |
1100 | |
1101 | // Fill in protocol qualifiers. |
1102 | ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); |
1103 | ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); |
1104 | for (unsigned i = 0, n = protocols.size(); i != n; ++i) |
1105 | ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); |
1106 | |
1107 | // We're done. Return the completed type to the parser. |
1108 | return CreateParsedType(Result, ResultTInfo); |
1109 | } |
1110 | |
1111 | TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( |
1112 | Scope *S, |
1113 | SourceLocation Loc, |
1114 | ParsedType BaseType, |
1115 | SourceLocation TypeArgsLAngleLoc, |
1116 | ArrayRef<ParsedType> TypeArgs, |
1117 | SourceLocation TypeArgsRAngleLoc, |
1118 | SourceLocation ProtocolLAngleLoc, |
1119 | ArrayRef<Decl *> Protocols, |
1120 | ArrayRef<SourceLocation> ProtocolLocs, |
1121 | SourceLocation ProtocolRAngleLoc) { |
1122 | TypeSourceInfo *BaseTypeInfo = nullptr; |
1123 | QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); |
1124 | if (T.isNull()) |
1125 | return true; |
1126 | |
1127 | // Handle missing type-source info. |
1128 | if (!BaseTypeInfo) |
1129 | BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); |
1130 | |
1131 | // Extract type arguments. |
1132 | SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; |
1133 | for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { |
1134 | TypeSourceInfo *TypeArgInfo = nullptr; |
1135 | QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); |
1136 | if (TypeArg.isNull()) { |
1137 | ActualTypeArgInfos.clear(); |
1138 | break; |
1139 | } |
1140 | |
1141 | assert(TypeArgInfo && "No type source info?")((TypeArgInfo && "No type source info?") ? static_cast <void> (0) : __assert_fail ("TypeArgInfo && \"No type source info?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1141, __PRETTY_FUNCTION__)); |
1142 | ActualTypeArgInfos.push_back(TypeArgInfo); |
1143 | } |
1144 | |
1145 | // Build the object type. |
1146 | QualType Result = BuildObjCObjectType( |
1147 | T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), |
1148 | TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, |
1149 | ProtocolLAngleLoc, |
1150 | llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), |
1151 | Protocols.size()), |
1152 | ProtocolLocs, ProtocolRAngleLoc, |
1153 | /*FailOnError=*/false); |
1154 | |
1155 | if (Result == T) |
1156 | return BaseType; |
1157 | |
1158 | // Create source information for this type. |
1159 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); |
1160 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); |
1161 | |
1162 | // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an |
1163 | // object pointer type. Fill in source information for it. |
1164 | if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { |
1165 | // The '*' is implicit. |
1166 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); |
1167 | ResultTL = ObjCObjectPointerTL.getPointeeLoc(); |
1168 | } |
1169 | |
1170 | if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) { |
1171 | // Protocol qualifier information. |
1172 | if (OTPTL.getNumProtocols() > 0) { |
1173 | assert(OTPTL.getNumProtocols() == Protocols.size())((OTPTL.getNumProtocols() == Protocols.size()) ? static_cast< void> (0) : __assert_fail ("OTPTL.getNumProtocols() == Protocols.size()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1173, __PRETTY_FUNCTION__)); |
1174 | OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc); |
1175 | OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc); |
1176 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) |
1177 | OTPTL.setProtocolLoc(i, ProtocolLocs[i]); |
1178 | } |
1179 | |
1180 | // We're done. Return the completed type to the parser. |
1181 | return CreateParsedType(Result, ResultTInfo); |
1182 | } |
1183 | |
1184 | auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); |
1185 | |
1186 | // Type argument information. |
1187 | if (ObjCObjectTL.getNumTypeArgs() > 0) { |
1188 | assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size())((ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()) ? static_cast<void> (0) : __assert_fail ("ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1188, __PRETTY_FUNCTION__)); |
1189 | ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); |
1190 | ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); |
1191 | for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) |
1192 | ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); |
1193 | } else { |
1194 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); |
1195 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); |
1196 | } |
1197 | |
1198 | // Protocol qualifier information. |
1199 | if (ObjCObjectTL.getNumProtocols() > 0) { |
1200 | assert(ObjCObjectTL.getNumProtocols() == Protocols.size())((ObjCObjectTL.getNumProtocols() == Protocols.size()) ? static_cast <void> (0) : __assert_fail ("ObjCObjectTL.getNumProtocols() == Protocols.size()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1200, __PRETTY_FUNCTION__)); |
1201 | ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); |
1202 | ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); |
1203 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) |
1204 | ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); |
1205 | } else { |
1206 | ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); |
1207 | ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); |
1208 | } |
1209 | |
1210 | // Base type. |
1211 | ObjCObjectTL.setHasBaseTypeAsWritten(true); |
1212 | if (ObjCObjectTL.getType() == T) |
1213 | ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); |
1214 | else |
1215 | ObjCObjectTL.getBaseLoc().initialize(Context, Loc); |
1216 | |
1217 | // We're done. Return the completed type to the parser. |
1218 | return CreateParsedType(Result, ResultTInfo); |
1219 | } |
1220 | |
1221 | static OpenCLAccessAttr::Spelling |
1222 | getImageAccess(const ParsedAttributesView &Attrs) { |
1223 | for (const ParsedAttr &AL : Attrs) |
1224 | if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) |
1225 | return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); |
1226 | return OpenCLAccessAttr::Keyword_read_only; |
1227 | } |
1228 | |
1229 | /// Convert the specified declspec to the appropriate type |
1230 | /// object. |
1231 | /// \param state Specifies the declarator containing the declaration specifier |
1232 | /// to be converted, along with other associated processing state. |
1233 | /// \returns The type described by the declaration specifiers. This function |
1234 | /// never returns null. |
1235 | static QualType ConvertDeclSpecToType(TypeProcessingState &state) { |
1236 | // FIXME: Should move the logic from DeclSpec::Finish to here for validity |
1237 | // checking. |
1238 | |
1239 | Sema &S = state.getSema(); |
1240 | Declarator &declarator = state.getDeclarator(); |
1241 | DeclSpec &DS = declarator.getMutableDeclSpec(); |
1242 | SourceLocation DeclLoc = declarator.getIdentifierLoc(); |
1243 | if (DeclLoc.isInvalid()) |
1244 | DeclLoc = DS.getBeginLoc(); |
1245 | |
1246 | ASTContext &Context = S.Context; |
1247 | |
1248 | QualType Result; |
1249 | switch (DS.getTypeSpecType()) { |
1250 | case DeclSpec::TST_void: |
1251 | Result = Context.VoidTy; |
1252 | break; |
1253 | case DeclSpec::TST_char: |
1254 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) |
1255 | Result = Context.CharTy; |
1256 | else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) |
1257 | Result = Context.SignedCharTy; |
1258 | else { |
1259 | assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&((DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && "Unknown TSS value" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1260, __PRETTY_FUNCTION__)) |
1260 | "Unknown TSS value")((DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && "Unknown TSS value" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1260, __PRETTY_FUNCTION__)); |
1261 | Result = Context.UnsignedCharTy; |
1262 | } |
1263 | break; |
1264 | case DeclSpec::TST_wchar: |
1265 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) |
1266 | Result = Context.WCharTy; |
1267 | else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { |
1268 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) |
1269 | << DS.getSpecifierName(DS.getTypeSpecType(), |
1270 | Context.getPrintingPolicy()); |
1271 | Result = Context.getSignedWCharType(); |
1272 | } else { |
1273 | assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&((DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && "Unknown TSS value" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1274, __PRETTY_FUNCTION__)) |
1274 | "Unknown TSS value")((DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && "Unknown TSS value" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1274, __PRETTY_FUNCTION__)); |
1275 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) |
1276 | << DS.getSpecifierName(DS.getTypeSpecType(), |
1277 | Context.getPrintingPolicy()); |
1278 | Result = Context.getUnsignedWCharType(); |
1279 | } |
1280 | break; |
1281 | case DeclSpec::TST_char8: |
1282 | assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&((DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1283, __PRETTY_FUNCTION__)) |
1283 | "Unknown TSS value")((DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1283, __PRETTY_FUNCTION__)); |
1284 | Result = Context.Char8Ty; |
1285 | break; |
1286 | case DeclSpec::TST_char16: |
1287 | assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&((DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1288, __PRETTY_FUNCTION__)) |
1288 | "Unknown TSS value")((DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1288, __PRETTY_FUNCTION__)); |
1289 | Result = Context.Char16Ty; |
1290 | break; |
1291 | case DeclSpec::TST_char32: |
1292 | assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&((DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1293, __PRETTY_FUNCTION__)) |
1293 | "Unknown TSS value")((DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && "Unknown TSS value") ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1293, __PRETTY_FUNCTION__)); |
1294 | Result = Context.Char32Ty; |
1295 | break; |
1296 | case DeclSpec::TST_unspecified: |
1297 | // If this is a missing declspec in a block literal return context, then it |
1298 | // is inferred from the return statements inside the block. |
1299 | // The declspec is always missing in a lambda expr context; it is either |
1300 | // specified with a trailing return type or inferred. |
1301 | if (S.getLangOpts().CPlusPlus14 && |
1302 | declarator.getContext() == DeclaratorContext::LambdaExprContext) { |
1303 | // In C++1y, a lambda's implicit return type is 'auto'. |
1304 | Result = Context.getAutoDeductType(); |
1305 | break; |
1306 | } else if (declarator.getContext() == |
1307 | DeclaratorContext::LambdaExprContext || |
1308 | checkOmittedBlockReturnType(S, declarator, |
1309 | Context.DependentTy)) { |
1310 | Result = Context.DependentTy; |
1311 | break; |
1312 | } |
1313 | |
1314 | // Unspecified typespec defaults to int in C90. However, the C90 grammar |
1315 | // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, |
1316 | // type-qualifier, or storage-class-specifier. If not, emit an extwarn. |
1317 | // Note that the one exception to this is function definitions, which are |
1318 | // allowed to be completely missing a declspec. This is handled in the |
1319 | // parser already though by it pretending to have seen an 'int' in this |
1320 | // case. |
1321 | if (S.getLangOpts().ImplicitInt) { |
1322 | // In C89 mode, we only warn if there is a completely missing declspec |
1323 | // when one is not allowed. |
1324 | if (DS.isEmpty()) { |
1325 | S.Diag(DeclLoc, diag::ext_missing_declspec) |
1326 | << DS.getSourceRange() |
1327 | << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); |
1328 | } |
1329 | } else if (!DS.hasTypeSpecifier()) { |
1330 | // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: |
1331 | // "At least one type specifier shall be given in the declaration |
1332 | // specifiers in each declaration, and in the specifier-qualifier list in |
1333 | // each struct declaration and type name." |
1334 | if (S.getLangOpts().CPlusPlus) { |
1335 | S.Diag(DeclLoc, diag::err_missing_type_specifier) |
1336 | << DS.getSourceRange(); |
1337 | |
1338 | // When this occurs in C++ code, often something is very broken with the |
1339 | // value being declared, poison it as invalid so we don't get chains of |
1340 | // errors. |
1341 | declarator.setInvalidType(true); |
1342 | } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){ |
1343 | S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) |
1344 | << DS.getSourceRange(); |
1345 | declarator.setInvalidType(true); |
1346 | } else { |
1347 | S.Diag(DeclLoc, diag::ext_missing_type_specifier) |
1348 | << DS.getSourceRange(); |
1349 | } |
1350 | } |
1351 | |
1352 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
1353 | case DeclSpec::TST_int: { |
1354 | if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { |
1355 | switch (DS.getTypeSpecWidth()) { |
1356 | case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; |
1357 | case DeclSpec::TSW_short: Result = Context.ShortTy; break; |
1358 | case DeclSpec::TSW_long: Result = Context.LongTy; break; |
1359 | case DeclSpec::TSW_longlong: |
1360 | Result = Context.LongLongTy; |
1361 | |
1362 | // 'long long' is a C99 or C++11 feature. |
1363 | if (!S.getLangOpts().C99) { |
1364 | if (S.getLangOpts().CPlusPlus) |
1365 | S.Diag(DS.getTypeSpecWidthLoc(), |
1366 | S.getLangOpts().CPlusPlus11 ? |
1367 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); |
1368 | else |
1369 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); |
1370 | } |
1371 | break; |
1372 | } |
1373 | } else { |
1374 | switch (DS.getTypeSpecWidth()) { |
1375 | case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; |
1376 | case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; |
1377 | case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; |
1378 | case DeclSpec::TSW_longlong: |
1379 | Result = Context.UnsignedLongLongTy; |
1380 | |
1381 | // 'long long' is a C99 or C++11 feature. |
1382 | if (!S.getLangOpts().C99) { |
1383 | if (S.getLangOpts().CPlusPlus) |
1384 | S.Diag(DS.getTypeSpecWidthLoc(), |
1385 | S.getLangOpts().CPlusPlus11 ? |
1386 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); |
1387 | else |
1388 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); |
1389 | } |
1390 | break; |
1391 | } |
1392 | } |
1393 | break; |
1394 | } |
1395 | case DeclSpec::TST_accum: { |
1396 | switch (DS.getTypeSpecWidth()) { |
1397 | case DeclSpec::TSW_short: |
1398 | Result = Context.ShortAccumTy; |
1399 | break; |
1400 | case DeclSpec::TSW_unspecified: |
1401 | Result = Context.AccumTy; |
1402 | break; |
1403 | case DeclSpec::TSW_long: |
1404 | Result = Context.LongAccumTy; |
1405 | break; |
1406 | case DeclSpec::TSW_longlong: |
1407 | llvm_unreachable("Unable to specify long long as _Accum width")::llvm::llvm_unreachable_internal("Unable to specify long long as _Accum width" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1407); |
1408 | } |
1409 | |
1410 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) |
1411 | Result = Context.getCorrespondingUnsignedType(Result); |
1412 | |
1413 | if (DS.isTypeSpecSat()) |
1414 | Result = Context.getCorrespondingSaturatedType(Result); |
1415 | |
1416 | break; |
1417 | } |
1418 | case DeclSpec::TST_fract: { |
1419 | switch (DS.getTypeSpecWidth()) { |
1420 | case DeclSpec::TSW_short: |
1421 | Result = Context.ShortFractTy; |
1422 | break; |
1423 | case DeclSpec::TSW_unspecified: |
1424 | Result = Context.FractTy; |
1425 | break; |
1426 | case DeclSpec::TSW_long: |
1427 | Result = Context.LongFractTy; |
1428 | break; |
1429 | case DeclSpec::TSW_longlong: |
1430 | llvm_unreachable("Unable to specify long long as _Fract width")::llvm::llvm_unreachable_internal("Unable to specify long long as _Fract width" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1430); |
1431 | } |
1432 | |
1433 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) |
1434 | Result = Context.getCorrespondingUnsignedType(Result); |
1435 | |
1436 | if (DS.isTypeSpecSat()) |
1437 | Result = Context.getCorrespondingSaturatedType(Result); |
1438 | |
1439 | break; |
1440 | } |
1441 | case DeclSpec::TST_int128: |
1442 | if (!S.Context.getTargetInfo().hasInt128Type()) |
1443 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) |
1444 | << "__int128"; |
1445 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) |
1446 | Result = Context.UnsignedInt128Ty; |
1447 | else |
1448 | Result = Context.Int128Ty; |
1449 | break; |
1450 | case DeclSpec::TST_float16: Result = Context.Float16Ty; break; |
1451 | case DeclSpec::TST_half: Result = Context.HalfTy; break; |
1452 | case DeclSpec::TST_float: Result = Context.FloatTy; break; |
1453 | case DeclSpec::TST_double: |
1454 | if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) |
1455 | Result = Context.LongDoubleTy; |
1456 | else |
1457 | Result = Context.DoubleTy; |
1458 | break; |
1459 | case DeclSpec::TST_float128: |
1460 | if (!S.Context.getTargetInfo().hasFloat128Type()) |
1461 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) |
1462 | << "__float128"; |
1463 | Result = Context.Float128Ty; |
1464 | break; |
1465 | case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool |
1466 | break; |
1467 | case DeclSpec::TST_decimal32: // _Decimal32 |
1468 | case DeclSpec::TST_decimal64: // _Decimal64 |
1469 | case DeclSpec::TST_decimal128: // _Decimal128 |
1470 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); |
1471 | Result = Context.IntTy; |
1472 | declarator.setInvalidType(true); |
1473 | break; |
1474 | case DeclSpec::TST_class: |
1475 | case DeclSpec::TST_enum: |
1476 | case DeclSpec::TST_union: |
1477 | case DeclSpec::TST_struct: |
1478 | case DeclSpec::TST_interface: { |
1479 | TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()); |
1480 | if (!D) { |
1481 | // This can happen in C++ with ambiguous lookups. |
1482 | Result = Context.IntTy; |
1483 | declarator.setInvalidType(true); |
1484 | break; |
1485 | } |
1486 | |
1487 | // If the type is deprecated or unavailable, diagnose it. |
1488 | S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); |
1489 | |
1490 | assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&((DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex () == 0 && DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"No qualifiers on tag names!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1491, __PRETTY_FUNCTION__)) |
1491 | DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!")((DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex () == 0 && DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"No qualifiers on tag names!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1491, __PRETTY_FUNCTION__)); |
1492 | |
1493 | // TypeQuals handled by caller. |
1494 | Result = Context.getTypeDeclType(D); |
1495 | |
1496 | // In both C and C++, make an ElaboratedType. |
1497 | ElaboratedTypeKeyword Keyword |
1498 | = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); |
1499 | Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result, |
1500 | DS.isTypeSpecOwned() ? D : nullptr); |
1501 | break; |
1502 | } |
1503 | case DeclSpec::TST_typename: { |
1504 | assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&((DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex () == 0 && DS.getTypeSpecSign() == 0 && "Can't handle qualifiers on typedef names yet!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"Can't handle qualifiers on typedef names yet!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1506, __PRETTY_FUNCTION__)) |
1505 | DS.getTypeSpecSign() == 0 &&((DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex () == 0 && DS.getTypeSpecSign() == 0 && "Can't handle qualifiers on typedef names yet!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"Can't handle qualifiers on typedef names yet!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1506, __PRETTY_FUNCTION__)) |
1506 | "Can't handle qualifiers on typedef names yet!")((DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex () == 0 && DS.getTypeSpecSign() == 0 && "Can't handle qualifiers on typedef names yet!" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"Can't handle qualifiers on typedef names yet!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1506, __PRETTY_FUNCTION__)); |
1507 | Result = S.GetTypeFromParser(DS.getRepAsType()); |
1508 | if (Result.isNull()) { |
1509 | declarator.setInvalidType(true); |
1510 | } |
1511 | |
1512 | // TypeQuals handled by caller. |
1513 | break; |
1514 | } |
1515 | case DeclSpec::TST_typeofType: |
1516 | // FIXME: Preserve type source info. |
1517 | Result = S.GetTypeFromParser(DS.getRepAsType()); |
1518 | assert(!Result.isNull() && "Didn't get a type for typeof?")((!Result.isNull() && "Didn't get a type for typeof?" ) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for typeof?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1518, __PRETTY_FUNCTION__)); |
1519 | if (!Result->isDependentType()) |
1520 | if (const TagType *TT = Result->getAs<TagType>()) |
1521 | S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); |
1522 | // TypeQuals handled by caller. |
1523 | Result = Context.getTypeOfType(Result); |
1524 | break; |
1525 | case DeclSpec::TST_typeofExpr: { |
1526 | Expr *E = DS.getRepAsExpr(); |
1527 | assert(E && "Didn't get an expression for typeof?")((E && "Didn't get an expression for typeof?") ? static_cast <void> (0) : __assert_fail ("E && \"Didn't get an expression for typeof?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1527, __PRETTY_FUNCTION__)); |
1528 | // TypeQuals handled by caller. |
1529 | Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); |
1530 | if (Result.isNull()) { |
1531 | Result = Context.IntTy; |
1532 | declarator.setInvalidType(true); |
1533 | } |
1534 | break; |
1535 | } |
1536 | case DeclSpec::TST_decltype: { |
1537 | Expr *E = DS.getRepAsExpr(); |
1538 | assert(E && "Didn't get an expression for decltype?")((E && "Didn't get an expression for decltype?") ? static_cast <void> (0) : __assert_fail ("E && \"Didn't get an expression for decltype?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1538, __PRETTY_FUNCTION__)); |
1539 | // TypeQuals handled by caller. |
1540 | Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); |
1541 | if (Result.isNull()) { |
1542 | Result = Context.IntTy; |
1543 | declarator.setInvalidType(true); |
1544 | } |
1545 | break; |
1546 | } |
1547 | case DeclSpec::TST_underlyingType: |
1548 | Result = S.GetTypeFromParser(DS.getRepAsType()); |
1549 | assert(!Result.isNull() && "Didn't get a type for __underlying_type?")((!Result.isNull() && "Didn't get a type for __underlying_type?" ) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for __underlying_type?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1549, __PRETTY_FUNCTION__)); |
1550 | Result = S.BuildUnaryTransformType(Result, |
1551 | UnaryTransformType::EnumUnderlyingType, |
1552 | DS.getTypeSpecTypeLoc()); |
1553 | if (Result.isNull()) { |
1554 | Result = Context.IntTy; |
1555 | declarator.setInvalidType(true); |
1556 | } |
1557 | break; |
1558 | |
1559 | case DeclSpec::TST_auto: |
1560 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false); |
1561 | break; |
1562 | |
1563 | case DeclSpec::TST_auto_type: |
1564 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); |
1565 | break; |
1566 | |
1567 | case DeclSpec::TST_decltype_auto: |
1568 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto, |
1569 | /*IsDependent*/ false); |
1570 | break; |
1571 | |
1572 | case DeclSpec::TST_unknown_anytype: |
1573 | Result = Context.UnknownAnyTy; |
1574 | break; |
1575 | |
1576 | case DeclSpec::TST_atomic: |
1577 | Result = S.GetTypeFromParser(DS.getRepAsType()); |
1578 | assert(!Result.isNull() && "Didn't get a type for _Atomic?")((!Result.isNull() && "Didn't get a type for _Atomic?" ) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for _Atomic?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1578, __PRETTY_FUNCTION__)); |
1579 | Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); |
1580 | if (Result.isNull()) { |
1581 | Result = Context.IntTy; |
1582 | declarator.setInvalidType(true); |
1583 | } |
1584 | break; |
1585 | |
1586 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ |
1587 | case DeclSpec::TST_##ImgType##_t: \ |
1588 | switch (getImageAccess(DS.getAttributes())) { \ |
1589 | case OpenCLAccessAttr::Keyword_write_only: \ |
1590 | Result = Context.Id##WOTy; \ |
1591 | break; \ |
1592 | case OpenCLAccessAttr::Keyword_read_write: \ |
1593 | Result = Context.Id##RWTy; \ |
1594 | break; \ |
1595 | case OpenCLAccessAttr::Keyword_read_only: \ |
1596 | Result = Context.Id##ROTy; \ |
1597 | break; \ |
1598 | } \ |
1599 | break; |
1600 | #include "clang/Basic/OpenCLImageTypes.def" |
1601 | |
1602 | case DeclSpec::TST_error: |
1603 | Result = Context.IntTy; |
1604 | declarator.setInvalidType(true); |
1605 | break; |
1606 | } |
1607 | |
1608 | if (S.getLangOpts().OpenCL && |
1609 | S.checkOpenCLDisabledTypeDeclSpec(DS, Result)) |
1610 | declarator.setInvalidType(true); |
1611 | |
1612 | bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum || |
1613 | DS.getTypeSpecType() == DeclSpec::TST_fract; |
1614 | |
1615 | // Only fixed point types can be saturated |
1616 | if (DS.isTypeSpecSat() && !IsFixedPointType) |
1617 | S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec) |
1618 | << DS.getSpecifierName(DS.getTypeSpecType(), |
1619 | Context.getPrintingPolicy()); |
1620 | |
1621 | // Handle complex types. |
1622 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { |
1623 | if (S.getLangOpts().Freestanding) |
1624 | S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); |
1625 | Result = Context.getComplexType(Result); |
1626 | } else if (DS.isTypeAltiVecVector()) { |
1627 | unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); |
1628 | assert(typeSize > 0 && "type size for vector must be greater than 0 bits")((typeSize > 0 && "type size for vector must be greater than 0 bits" ) ? static_cast<void> (0) : __assert_fail ("typeSize > 0 && \"type size for vector must be greater than 0 bits\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1628, __PRETTY_FUNCTION__)); |
1629 | VectorType::VectorKind VecKind = VectorType::AltiVecVector; |
1630 | if (DS.isTypeAltiVecPixel()) |
1631 | VecKind = VectorType::AltiVecPixel; |
1632 | else if (DS.isTypeAltiVecBool()) |
1633 | VecKind = VectorType::AltiVecBool; |
1634 | Result = Context.getVectorType(Result, 128/typeSize, VecKind); |
1635 | } |
1636 | |
1637 | // FIXME: Imaginary. |
1638 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) |
1639 | S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); |
1640 | |
1641 | // Before we process any type attributes, synthesize a block literal |
1642 | // function declarator if necessary. |
1643 | if (declarator.getContext() == DeclaratorContext::BlockLiteralContext) |
1644 | maybeSynthesizeBlockSignature(state, Result); |
1645 | |
1646 | // Apply any type attributes from the decl spec. This may cause the |
1647 | // list of type attributes to be temporarily saved while the type |
1648 | // attributes are pushed around. |
1649 | // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) |
1650 | if (!DS.isTypeSpecPipe()) |
1651 | processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes()); |
1652 | |
1653 | // Apply const/volatile/restrict qualifiers to T. |
1654 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { |
1655 | // Warn about CV qualifiers on function types. |
1656 | // C99 6.7.3p8: |
1657 | // If the specification of a function type includes any type qualifiers, |
1658 | // the behavior is undefined. |
1659 | // C++11 [dcl.fct]p7: |
1660 | // The effect of a cv-qualifier-seq in a function declarator is not the |
1661 | // same as adding cv-qualification on top of the function type. In the |
1662 | // latter case, the cv-qualifiers are ignored. |
1663 | if (TypeQuals && Result->isFunctionType()) { |
1664 | diagnoseAndRemoveTypeQualifiers( |
1665 | S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, |
1666 | S.getLangOpts().CPlusPlus |
1667 | ? diag::warn_typecheck_function_qualifiers_ignored |
1668 | : diag::warn_typecheck_function_qualifiers_unspecified); |
1669 | // No diagnostic for 'restrict' or '_Atomic' applied to a |
1670 | // function type; we'll diagnose those later, in BuildQualifiedType. |
1671 | } |
1672 | |
1673 | // C++11 [dcl.ref]p1: |
1674 | // Cv-qualified references are ill-formed except when the |
1675 | // cv-qualifiers are introduced through the use of a typedef-name |
1676 | // or decltype-specifier, in which case the cv-qualifiers are ignored. |
1677 | // |
1678 | // There don't appear to be any other contexts in which a cv-qualified |
1679 | // reference type could be formed, so the 'ill-formed' clause here appears |
1680 | // to never happen. |
1681 | if (TypeQuals && Result->isReferenceType()) { |
1682 | diagnoseAndRemoveTypeQualifiers( |
1683 | S, DS, TypeQuals, Result, |
1684 | DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, |
1685 | diag::warn_typecheck_reference_qualifiers); |
1686 | } |
1687 | |
1688 | // C90 6.5.3 constraints: "The same type qualifier shall not appear more |
1689 | // than once in the same specifier-list or qualifier-list, either directly |
1690 | // or via one or more typedefs." |
1691 | if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus |
1692 | && TypeQuals & Result.getCVRQualifiers()) { |
1693 | if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { |
1694 | S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) |
1695 | << "const"; |
1696 | } |
1697 | |
1698 | if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { |
1699 | S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) |
1700 | << "volatile"; |
1701 | } |
1702 | |
1703 | // C90 doesn't have restrict nor _Atomic, so it doesn't force us to |
1704 | // produce a warning in this case. |
1705 | } |
1706 | |
1707 | QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); |
1708 | |
1709 | // If adding qualifiers fails, just use the unqualified type. |
1710 | if (Qualified.isNull()) |
1711 | declarator.setInvalidType(true); |
1712 | else |
1713 | Result = Qualified; |
1714 | } |
1715 | |
1716 | assert(!Result.isNull() && "This function should not return a null type")((!Result.isNull() && "This function should not return a null type" ) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"This function should not return a null type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1716, __PRETTY_FUNCTION__)); |
1717 | return Result; |
1718 | } |
1719 | |
1720 | static std::string getPrintableNameForEntity(DeclarationName Entity) { |
1721 | if (Entity) |
1722 | return Entity.getAsString(); |
1723 | |
1724 | return "type name"; |
1725 | } |
1726 | |
1727 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, |
1728 | Qualifiers Qs, const DeclSpec *DS) { |
1729 | if (T.isNull()) |
1730 | return QualType(); |
1731 | |
1732 | // Ignore any attempt to form a cv-qualified reference. |
1733 | if (T->isReferenceType()) { |
1734 | Qs.removeConst(); |
1735 | Qs.removeVolatile(); |
1736 | } |
1737 | |
1738 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from |
1739 | // object or incomplete types shall not be restrict-qualified." |
1740 | if (Qs.hasRestrict()) { |
1741 | unsigned DiagID = 0; |
1742 | QualType ProblemTy; |
1743 | |
1744 | if (T->isAnyPointerType() || T->isReferenceType() || |
1745 | T->isMemberPointerType()) { |
1746 | QualType EltTy; |
1747 | if (T->isObjCObjectPointerType()) |
1748 | EltTy = T; |
1749 | else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) |
1750 | EltTy = PTy->getPointeeType(); |
1751 | else |
1752 | EltTy = T->getPointeeType(); |
1753 | |
1754 | // If we have a pointer or reference, the pointee must have an object |
1755 | // incomplete type. |
1756 | if (!EltTy->isIncompleteOrObjectType()) { |
1757 | DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; |
1758 | ProblemTy = EltTy; |
1759 | } |
1760 | } else if (!T->isDependentType()) { |
1761 | DiagID = diag::err_typecheck_invalid_restrict_not_pointer; |
1762 | ProblemTy = T; |
1763 | } |
1764 | |
1765 | if (DiagID) { |
1766 | Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; |
1767 | Qs.removeRestrict(); |
1768 | } |
1769 | } |
1770 | |
1771 | return Context.getQualifiedType(T, Qs); |
1772 | } |
1773 | |
1774 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, |
1775 | unsigned CVRAU, const DeclSpec *DS) { |
1776 | if (T.isNull()) |
1777 | return QualType(); |
1778 | |
1779 | // Ignore any attempt to form a cv-qualified reference. |
1780 | if (T->isReferenceType()) |
1781 | CVRAU &= |
1782 | ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); |
1783 | |
1784 | // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and |
1785 | // TQ_unaligned; |
1786 | unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); |
1787 | |
1788 | // C11 6.7.3/5: |
1789 | // If the same qualifier appears more than once in the same |
1790 | // specifier-qualifier-list, either directly or via one or more typedefs, |
1791 | // the behavior is the same as if it appeared only once. |
1792 | // |
1793 | // It's not specified what happens when the _Atomic qualifier is applied to |
1794 | // a type specified with the _Atomic specifier, but we assume that this |
1795 | // should be treated as if the _Atomic qualifier appeared multiple times. |
1796 | if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { |
1797 | // C11 6.7.3/5: |
1798 | // If other qualifiers appear along with the _Atomic qualifier in a |
1799 | // specifier-qualifier-list, the resulting type is the so-qualified |
1800 | // atomic type. |
1801 | // |
1802 | // Don't need to worry about array types here, since _Atomic can't be |
1803 | // applied to such types. |
1804 | SplitQualType Split = T.getSplitUnqualifiedType(); |
1805 | T = BuildAtomicType(QualType(Split.Ty, 0), |
1806 | DS ? DS->getAtomicSpecLoc() : Loc); |
1807 | if (T.isNull()) |
1808 | return T; |
1809 | Split.Quals.addCVRQualifiers(CVR); |
1810 | return BuildQualifiedType(T, Loc, Split.Quals); |
1811 | } |
1812 | |
1813 | Qualifiers Q = Qualifiers::fromCVRMask(CVR); |
1814 | Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); |
1815 | return BuildQualifiedType(T, Loc, Q, DS); |
1816 | } |
1817 | |
1818 | /// Build a paren type including \p T. |
1819 | QualType Sema::BuildParenType(QualType T) { |
1820 | return Context.getParenType(T); |
1821 | } |
1822 | |
1823 | /// Given that we're building a pointer or reference to the given |
1824 | static QualType inferARCLifetimeForPointee(Sema &S, QualType type, |
1825 | SourceLocation loc, |
1826 | bool isReference) { |
1827 | // Bail out if retention is unrequired or already specified. |
1828 | if (!type->isObjCLifetimeType() || |
1829 | type.getObjCLifetime() != Qualifiers::OCL_None) |
1830 | return type; |
1831 | |
1832 | Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; |
1833 | |
1834 | // If the object type is const-qualified, we can safely use |
1835 | // __unsafe_unretained. This is safe (because there are no read |
1836 | // barriers), and it'll be safe to coerce anything but __weak* to |
1837 | // the resulting type. |
1838 | if (type.isConstQualified()) { |
1839 | implicitLifetime = Qualifiers::OCL_ExplicitNone; |
1840 | |
1841 | // Otherwise, check whether the static type does not require |
1842 | // retaining. This currently only triggers for Class (possibly |
1843 | // protocol-qualifed, and arrays thereof). |
1844 | } else if (type->isObjCARCImplicitlyUnretainedType()) { |
1845 | implicitLifetime = Qualifiers::OCL_ExplicitNone; |
1846 | |
1847 | // If we are in an unevaluated context, like sizeof, skip adding a |
1848 | // qualification. |
1849 | } else if (S.isUnevaluatedContext()) { |
1850 | return type; |
1851 | |
1852 | // If that failed, give an error and recover using __strong. __strong |
1853 | // is the option most likely to prevent spurious second-order diagnostics, |
1854 | // like when binding a reference to a field. |
1855 | } else { |
1856 | // These types can show up in private ivars in system headers, so |
1857 | // we need this to not be an error in those cases. Instead we |
1858 | // want to delay. |
1859 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { |
1860 | S.DelayedDiagnostics.add( |
1861 | sema::DelayedDiagnostic::makeForbiddenType(loc, |
1862 | diag::err_arc_indirect_no_ownership, type, isReference)); |
1863 | } else { |
1864 | S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; |
1865 | } |
1866 | implicitLifetime = Qualifiers::OCL_Strong; |
1867 | } |
1868 | assert(implicitLifetime && "didn't infer any lifetime!")((implicitLifetime && "didn't infer any lifetime!") ? static_cast<void> (0) : __assert_fail ("implicitLifetime && \"didn't infer any lifetime!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1868, __PRETTY_FUNCTION__)); |
1869 | |
1870 | Qualifiers qs; |
1871 | qs.addObjCLifetime(implicitLifetime); |
1872 | return S.Context.getQualifiedType(type, qs); |
1873 | } |
1874 | |
1875 | static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ |
1876 | std::string Quals = FnTy->getTypeQuals().getAsString(); |
1877 | |
1878 | switch (FnTy->getRefQualifier()) { |
1879 | case RQ_None: |
1880 | break; |
1881 | |
1882 | case RQ_LValue: |
1883 | if (!Quals.empty()) |
1884 | Quals += ' '; |
1885 | Quals += '&'; |
1886 | break; |
1887 | |
1888 | case RQ_RValue: |
1889 | if (!Quals.empty()) |
1890 | Quals += ' '; |
1891 | Quals += "&&"; |
1892 | break; |
1893 | } |
1894 | |
1895 | return Quals; |
1896 | } |
1897 | |
1898 | namespace { |
1899 | /// Kinds of declarator that cannot contain a qualified function type. |
1900 | /// |
1901 | /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: |
1902 | /// a function type with a cv-qualifier or a ref-qualifier can only appear |
1903 | /// at the topmost level of a type. |
1904 | /// |
1905 | /// Parens and member pointers are permitted. We don't diagnose array and |
1906 | /// function declarators, because they don't allow function types at all. |
1907 | /// |
1908 | /// The values of this enum are used in diagnostics. |
1909 | enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; |
1910 | } // end anonymous namespace |
1911 | |
1912 | /// Check whether the type T is a qualified function type, and if it is, |
1913 | /// diagnose that it cannot be contained within the given kind of declarator. |
1914 | static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, |
1915 | QualifiedFunctionKind QFK) { |
1916 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? |
1917 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); |
1918 | if (!FPT || (FPT->getTypeQuals().empty() && FPT->getRefQualifier() == RQ_None)) |
1919 | return false; |
1920 | |
1921 | S.Diag(Loc, diag::err_compound_qualified_function_type) |
1922 | << QFK << isa<FunctionType>(T.IgnoreParens()) << T |
1923 | << getFunctionQualifiersAsString(FPT); |
1924 | return true; |
1925 | } |
1926 | |
1927 | /// Build a pointer type. |
1928 | /// |
1929 | /// \param T The type to which we'll be building a pointer. |
1930 | /// |
1931 | /// \param Loc The location of the entity whose type involves this |
1932 | /// pointer type or, if there is no such entity, the location of the |
1933 | /// type that will have pointer type. |
1934 | /// |
1935 | /// \param Entity The name of the entity that involves the pointer |
1936 | /// type, if known. |
1937 | /// |
1938 | /// \returns A suitable pointer type, if there are no |
1939 | /// errors. Otherwise, returns a NULL type. |
1940 | QualType Sema::BuildPointerType(QualType T, |
1941 | SourceLocation Loc, DeclarationName Entity) { |
1942 | if (T->isReferenceType()) { |
1943 | // C++ 8.3.2p4: There shall be no ... pointers to references ... |
1944 | Diag(Loc, diag::err_illegal_decl_pointer_to_reference) |
1945 | << getPrintableNameForEntity(Entity) << T; |
1946 | return QualType(); |
1947 | } |
1948 | |
1949 | if (T->isFunctionType() && getLangOpts().OpenCL) { |
1950 | Diag(Loc, diag::err_opencl_function_pointer); |
1951 | return QualType(); |
1952 | } |
1953 | |
1954 | if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) |
1955 | return QualType(); |
1956 | |
1957 | assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType")((!T->isObjCObjectType() && "Should build ObjCObjectPointerType" ) ? static_cast<void> (0) : __assert_fail ("!T->isObjCObjectType() && \"Should build ObjCObjectPointerType\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1957, __PRETTY_FUNCTION__)); |
1958 | |
1959 | // In ARC, it is forbidden to build pointers to unqualified pointers. |
1960 | if (getLangOpts().ObjCAutoRefCount) |
1961 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); |
1962 | |
1963 | // Build the pointer type. |
1964 | return Context.getPointerType(T); |
1965 | } |
1966 | |
1967 | /// Build a reference type. |
1968 | /// |
1969 | /// \param T The type to which we'll be building a reference. |
1970 | /// |
1971 | /// \param Loc The location of the entity whose type involves this |
1972 | /// reference type or, if there is no such entity, the location of the |
1973 | /// type that will have reference type. |
1974 | /// |
1975 | /// \param Entity The name of the entity that involves the reference |
1976 | /// type, if known. |
1977 | /// |
1978 | /// \returns A suitable reference type, if there are no |
1979 | /// errors. Otherwise, returns a NULL type. |
1980 | QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, |
1981 | SourceLocation Loc, |
1982 | DeclarationName Entity) { |
1983 | assert(Context.getCanonicalType(T) != Context.OverloadTy &&((Context.getCanonicalType(T) != Context.OverloadTy && "Unresolved overloaded function type") ? static_cast<void > (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1984, __PRETTY_FUNCTION__)) |
1984 | "Unresolved overloaded function type")((Context.getCanonicalType(T) != Context.OverloadTy && "Unresolved overloaded function type") ? static_cast<void > (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 1984, __PRETTY_FUNCTION__)); |
1985 | |
1986 | // C++0x [dcl.ref]p6: |
1987 | // If a typedef (7.1.3), a type template-parameter (14.3.1), or a |
1988 | // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a |
1989 | // type T, an attempt to create the type "lvalue reference to cv TR" creates |
1990 | // the type "lvalue reference to T", while an attempt to create the type |
1991 | // "rvalue reference to cv TR" creates the type TR. |
1992 | bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); |
1993 | |
1994 | // C++ [dcl.ref]p4: There shall be no references to references. |
1995 | // |
1996 | // According to C++ DR 106, references to references are only |
1997 | // diagnosed when they are written directly (e.g., "int & &"), |
1998 | // but not when they happen via a typedef: |
1999 | // |
2000 | // typedef int& intref; |
2001 | // typedef intref& intref2; |
2002 | // |
2003 | // Parser::ParseDeclaratorInternal diagnoses the case where |
2004 | // references are written directly; here, we handle the |
2005 | // collapsing of references-to-references as described in C++0x. |
2006 | // DR 106 and 540 introduce reference-collapsing into C++98/03. |
2007 | |
2008 | // C++ [dcl.ref]p1: |
2009 | // A declarator that specifies the type "reference to cv void" |
2010 | // is ill-formed. |
2011 | if (T->isVoidType()) { |
2012 | Diag(Loc, diag::err_reference_to_void); |
2013 | return QualType(); |
2014 | } |
2015 | |
2016 | if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) |
2017 | return QualType(); |
2018 | |
2019 | // In ARC, it is forbidden to build references to unqualified pointers. |
2020 | if (getLangOpts().ObjCAutoRefCount) |
2021 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); |
2022 | |
2023 | // Handle restrict on references. |
2024 | if (LValueRef) |
2025 | return Context.getLValueReferenceType(T, SpelledAsLValue); |
2026 | return Context.getRValueReferenceType(T); |
2027 | } |
2028 | |
2029 | /// Build a Read-only Pipe type. |
2030 | /// |
2031 | /// \param T The type to which we'll be building a Pipe. |
2032 | /// |
2033 | /// \param Loc We do not use it for now. |
2034 | /// |
2035 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a |
2036 | /// NULL type. |
2037 | QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { |
2038 | return Context.getReadPipeType(T); |
2039 | } |
2040 | |
2041 | /// Build a Write-only Pipe type. |
2042 | /// |
2043 | /// \param T The type to which we'll be building a Pipe. |
2044 | /// |
2045 | /// \param Loc We do not use it for now. |
2046 | /// |
2047 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a |
2048 | /// NULL type. |
2049 | QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { |
2050 | return Context.getWritePipeType(T); |
2051 | } |
2052 | |
2053 | /// Check whether the specified array size makes the array type a VLA. If so, |
2054 | /// return true, if not, return the size of the array in SizeVal. |
2055 | static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { |
2056 | // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode |
2057 | // (like gnu99, but not c99) accept any evaluatable value as an extension. |
2058 | class VLADiagnoser : public Sema::VerifyICEDiagnoser { |
2059 | public: |
2060 | VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} |
2061 | |
2062 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { |
2063 | } |
2064 | |
2065 | void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override { |
2066 | S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; |
2067 | } |
2068 | } Diagnoser; |
2069 | |
2070 | return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, |
2071 | S.LangOpts.GNUMode || |
2072 | S.LangOpts.OpenCL).isInvalid(); |
2073 | } |
2074 | |
2075 | /// Build an array type. |
2076 | /// |
2077 | /// \param T The type of each element in the array. |
2078 | /// |
2079 | /// \param ASM C99 array size modifier (e.g., '*', 'static'). |
2080 | /// |
2081 | /// \param ArraySize Expression describing the size of the array. |
2082 | /// |
2083 | /// \param Brackets The range from the opening '[' to the closing ']'. |
2084 | /// |
2085 | /// \param Entity The name of the entity that involves the array |
2086 | /// type, if known. |
2087 | /// |
2088 | /// \returns A suitable array type, if there are no errors. Otherwise, |
2089 | /// returns a NULL type. |
2090 | QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, |
2091 | Expr *ArraySize, unsigned Quals, |
2092 | SourceRange Brackets, DeclarationName Entity) { |
2093 | |
2094 | SourceLocation Loc = Brackets.getBegin(); |
2095 | if (getLangOpts().CPlusPlus) { |
2096 | // C++ [dcl.array]p1: |
2097 | // T is called the array element type; this type shall not be a reference |
2098 | // type, the (possibly cv-qualified) type void, a function type or an |
2099 | // abstract class type. |
2100 | // |
2101 | // C++ [dcl.array]p3: |
2102 | // When several "array of" specifications are adjacent, [...] only the |
2103 | // first of the constant expressions that specify the bounds of the arrays |
2104 | // may be omitted. |
2105 | // |
2106 | // Note: function types are handled in the common path with C. |
2107 | if (T->isReferenceType()) { |
2108 | Diag(Loc, diag::err_illegal_decl_array_of_references) |
2109 | << getPrintableNameForEntity(Entity) << T; |
2110 | return QualType(); |
2111 | } |
2112 | |
2113 | if (T->isVoidType() || T->isIncompleteArrayType()) { |
2114 | Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; |
2115 | return QualType(); |
2116 | } |
2117 | |
2118 | if (RequireNonAbstractType(Brackets.getBegin(), T, |
2119 | diag::err_array_of_abstract_type)) |
2120 | return QualType(); |
2121 | |
2122 | // Mentioning a member pointer type for an array type causes us to lock in |
2123 | // an inheritance model, even if it's inside an unused typedef. |
2124 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
2125 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) |
2126 | if (!MPTy->getClass()->isDependentType()) |
2127 | (void)isCompleteType(Loc, T); |
2128 | |
2129 | } else { |
2130 | // C99 6.7.5.2p1: If the element type is an incomplete or function type, |
2131 | // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) |
2132 | if (RequireCompleteType(Loc, T, |
2133 | diag::err_illegal_decl_array_incomplete_type)) |
2134 | return QualType(); |
2135 | } |
2136 | |
2137 | if (T->isFunctionType()) { |
2138 | Diag(Loc, diag::err_illegal_decl_array_of_functions) |
2139 | << getPrintableNameForEntity(Entity) << T; |
2140 | return QualType(); |
2141 | } |
2142 | |
2143 | if (const RecordType *EltTy = T->getAs<RecordType>()) { |
2144 | // If the element type is a struct or union that contains a variadic |
2145 | // array, accept it as a GNU extension: C99 6.7.2.1p2. |
2146 | if (EltTy->getDecl()->hasFlexibleArrayMember()) |
2147 | Diag(Loc, diag::ext_flexible_array_in_array) << T; |
2148 | } else if (T->isObjCObjectType()) { |
2149 | Diag(Loc, diag::err_objc_array_of_interfaces) << T; |
2150 | return QualType(); |
2151 | } |
2152 | |
2153 | // Do placeholder conversions on the array size expression. |
2154 | if (ArraySize && ArraySize->hasPlaceholderType()) { |
2155 | ExprResult Result = CheckPlaceholderExpr(ArraySize); |
2156 | if (Result.isInvalid()) return QualType(); |
2157 | ArraySize = Result.get(); |
2158 | } |
2159 | |
2160 | // Do lvalue-to-rvalue conversions on the array size expression. |
2161 | if (ArraySize && !ArraySize->isRValue()) { |
2162 | ExprResult Result = DefaultLvalueConversion(ArraySize); |
2163 | if (Result.isInvalid()) |
2164 | return QualType(); |
2165 | |
2166 | ArraySize = Result.get(); |
2167 | } |
2168 | |
2169 | // C99 6.7.5.2p1: The size expression shall have integer type. |
2170 | // C++11 allows contextual conversions to such types. |
2171 | if (!getLangOpts().CPlusPlus11 && |
2172 | ArraySize && !ArraySize->isTypeDependent() && |
2173 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { |
2174 | Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) |
2175 | << ArraySize->getType() << ArraySize->getSourceRange(); |
2176 | return QualType(); |
2177 | } |
2178 | |
2179 | llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); |
2180 | if (!ArraySize) { |
2181 | if (ASM == ArrayType::Star) |
2182 | T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); |
2183 | else |
2184 | T = Context.getIncompleteArrayType(T, ASM, Quals); |
2185 | } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { |
2186 | T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); |
2187 | } else if ((!T->isDependentType() && !T->isIncompleteType() && |
2188 | !T->isConstantSizeType()) || |
2189 | isArraySizeVLA(*this, ArraySize, ConstVal)) { |
2190 | // Even in C++11, don't allow contextual conversions in the array bound |
2191 | // of a VLA. |
2192 | if (getLangOpts().CPlusPlus11 && |
2193 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { |
2194 | Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) |
2195 | << ArraySize->getType() << ArraySize->getSourceRange(); |
2196 | return QualType(); |
2197 | } |
2198 | |
2199 | // C99: an array with an element type that has a non-constant-size is a VLA. |
2200 | // C99: an array with a non-ICE size is a VLA. We accept any expression |
2201 | // that we can fold to a non-zero positive value as an extension. |
2202 | T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); |
2203 | } else { |
2204 | // C99 6.7.5.2p1: If the expression is a constant expression, it shall |
2205 | // have a value greater than zero. |
2206 | if (ConstVal.isSigned() && ConstVal.isNegative()) { |
2207 | if (Entity) |
2208 | Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size) |
2209 | << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); |
2210 | else |
2211 | Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size) |
2212 | << ArraySize->getSourceRange(); |
2213 | return QualType(); |
2214 | } |
2215 | if (ConstVal == 0) { |
2216 | // GCC accepts zero sized static arrays. We allow them when |
2217 | // we're not in a SFINAE context. |
2218 | Diag(ArraySize->getBeginLoc(), isSFINAEContext() |
2219 | ? diag::err_typecheck_zero_array_size |
2220 | : diag::ext_typecheck_zero_array_size) |
2221 | << ArraySize->getSourceRange(); |
2222 | |
2223 | if (ASM == ArrayType::Static) { |
2224 | Diag(ArraySize->getBeginLoc(), |
2225 | diag::warn_typecheck_zero_static_array_size) |
2226 | << ArraySize->getSourceRange(); |
2227 | ASM = ArrayType::Normal; |
2228 | } |
2229 | } else if (!T->isDependentType() && !T->isVariablyModifiedType() && |
2230 | !T->isIncompleteType() && !T->isUndeducedType()) { |
2231 | // Is the array too large? |
2232 | unsigned ActiveSizeBits |
2233 | = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); |
2234 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { |
2235 | Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) |
2236 | << ConstVal.toString(10) << ArraySize->getSourceRange(); |
2237 | return QualType(); |
2238 | } |
2239 | } |
2240 | |
2241 | T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); |
2242 | } |
2243 | |
2244 | // OpenCL v1.2 s6.9.d: variable length arrays are not supported. |
2245 | if (getLangOpts().OpenCL && T->isVariableArrayType()) { |
2246 | Diag(Loc, diag::err_opencl_vla); |
2247 | return QualType(); |
2248 | } |
2249 | |
2250 | if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) { |
2251 | if (getLangOpts().CUDA) { |
2252 | // CUDA device code doesn't support VLAs. |
2253 | CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget(); |
2254 | } else if (!getLangOpts().OpenMP || |
2255 | shouldDiagnoseTargetSupportFromOpenMP()) { |
2256 | // Some targets don't support VLAs. |
2257 | Diag(Loc, diag::err_vla_unsupported); |
2258 | return QualType(); |
2259 | } |
2260 | } |
2261 | |
2262 | // If this is not C99, extwarn about VLA's and C99 array size modifiers. |
2263 | if (!getLangOpts().C99) { |
2264 | if (T->isVariableArrayType()) { |
2265 | // Prohibit the use of VLAs during template argument deduction. |
2266 | if (isSFINAEContext()) { |
2267 | Diag(Loc, diag::err_vla_in_sfinae); |
2268 | return QualType(); |
2269 | } |
2270 | // Just extwarn about VLAs. |
2271 | else |
2272 | Diag(Loc, diag::ext_vla); |
2273 | } else if (ASM != ArrayType::Normal || Quals != 0) |
2274 | Diag(Loc, |
2275 | getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx |
2276 | : diag::ext_c99_array_usage) << ASM; |
2277 | } |
2278 | |
2279 | if (T->isVariableArrayType()) { |
2280 | // Warn about VLAs for -Wvla. |
2281 | Diag(Loc, diag::warn_vla_used); |
2282 | } |
2283 | |
2284 | // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. |
2285 | // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. |
2286 | // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. |
2287 | if (getLangOpts().OpenCL) { |
2288 | const QualType ArrType = Context.getBaseElementType(T); |
2289 | if (ArrType->isBlockPointerType() || ArrType->isPipeType() || |
2290 | ArrType->isSamplerT() || ArrType->isImageType()) { |
2291 | Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; |
2292 | return QualType(); |
2293 | } |
2294 | } |
2295 | |
2296 | return T; |
2297 | } |
2298 | |
2299 | QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, |
2300 | SourceLocation AttrLoc) { |
2301 | // The base type must be integer (not Boolean or enumeration) or float, and |
2302 | // can't already be a vector. |
2303 | if (!CurType->isDependentType() && |
2304 | (!CurType->isBuiltinType() || CurType->isBooleanType() || |
2305 | (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) { |
2306 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType; |
2307 | return QualType(); |
2308 | } |
2309 | |
2310 | if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent()) |
2311 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, |
2312 | VectorType::GenericVector); |
2313 | |
2314 | llvm::APSInt VecSize(32); |
2315 | if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) { |
2316 | Diag(AttrLoc, diag::err_attribute_argument_type) |
2317 | << "vector_size" << AANT_ArgumentIntegerConstant |
2318 | << SizeExpr->getSourceRange(); |
2319 | return QualType(); |
2320 | } |
2321 | |
2322 | if (CurType->isDependentType()) |
2323 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, |
2324 | VectorType::GenericVector); |
2325 | |
2326 | unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8); |
2327 | unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType)); |
2328 | |
2329 | if (VectorSize == 0) { |
2330 | Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange(); |
2331 | return QualType(); |
2332 | } |
2333 | |
2334 | // vecSize is specified in bytes - convert to bits. |
2335 | if (VectorSize % TypeSize) { |
2336 | Diag(AttrLoc, diag::err_attribute_invalid_size) |
2337 | << SizeExpr->getSourceRange(); |
2338 | return QualType(); |
2339 | } |
2340 | |
2341 | if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) { |
2342 | Diag(AttrLoc, diag::err_attribute_size_too_large) |
2343 | << SizeExpr->getSourceRange(); |
2344 | return QualType(); |
2345 | } |
2346 | |
2347 | return Context.getVectorType(CurType, VectorSize / TypeSize, |
2348 | VectorType::GenericVector); |
2349 | } |
2350 | |
2351 | /// Build an ext-vector type. |
2352 | /// |
2353 | /// Run the required checks for the extended vector type. |
2354 | QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, |
2355 | SourceLocation AttrLoc) { |
2356 | // Unlike gcc's vector_size attribute, we do not allow vectors to be defined |
2357 | // in conjunction with complex types (pointers, arrays, functions, etc.). |
2358 | // |
2359 | // Additionally, OpenCL prohibits vectors of booleans (they're considered a |
2360 | // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects |
2361 | // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors |
2362 | // of bool aren't allowed. |
2363 | if ((!T->isDependentType() && !T->isIntegerType() && |
2364 | !T->isRealFloatingType()) || |
2365 | T->isBooleanType()) { |
2366 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; |
2367 | return QualType(); |
2368 | } |
2369 | |
2370 | if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { |
2371 | llvm::APSInt vecSize(32); |
2372 | if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { |
2373 | Diag(AttrLoc, diag::err_attribute_argument_type) |
2374 | << "ext_vector_type" << AANT_ArgumentIntegerConstant |
2375 | << ArraySize->getSourceRange(); |
2376 | return QualType(); |
2377 | } |
2378 | |
2379 | // Unlike gcc's vector_size attribute, the size is specified as the |
2380 | // number of elements, not the number of bytes. |
2381 | unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); |
2382 | |
2383 | if (vectorSize == 0) { |
2384 | Diag(AttrLoc, diag::err_attribute_zero_size) |
2385 | << ArraySize->getSourceRange(); |
2386 | return QualType(); |
2387 | } |
2388 | |
2389 | if (VectorType::isVectorSizeTooLarge(vectorSize)) { |
2390 | Diag(AttrLoc, diag::err_attribute_size_too_large) |
2391 | << ArraySize->getSourceRange(); |
2392 | return QualType(); |
2393 | } |
2394 | |
2395 | return Context.getExtVectorType(T, vectorSize); |
2396 | } |
2397 | |
2398 | return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); |
2399 | } |
2400 | |
2401 | bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { |
2402 | if (T->isArrayType() || T->isFunctionType()) { |
2403 | Diag(Loc, diag::err_func_returning_array_function) |
2404 | << T->isFunctionType() << T; |
2405 | return true; |
2406 | } |
2407 | |
2408 | // Functions cannot return half FP. |
2409 | if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { |
2410 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << |
2411 | FixItHint::CreateInsertion(Loc, "*"); |
2412 | return true; |
2413 | } |
2414 | |
2415 | // Methods cannot return interface types. All ObjC objects are |
2416 | // passed by reference. |
2417 | if (T->isObjCObjectType()) { |
2418 | Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) |
2419 | << 0 << T << FixItHint::CreateInsertion(Loc, "*"); |
2420 | return true; |
2421 | } |
2422 | |
2423 | return false; |
2424 | } |
2425 | |
2426 | /// Check the extended parameter information. Most of the necessary |
2427 | /// checking should occur when applying the parameter attribute; the |
2428 | /// only other checks required are positional restrictions. |
2429 | static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, |
2430 | const FunctionProtoType::ExtProtoInfo &EPI, |
2431 | llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { |
2432 | assert(EPI.ExtParameterInfos && "shouldn't get here without param infos")((EPI.ExtParameterInfos && "shouldn't get here without param infos" ) ? static_cast<void> (0) : __assert_fail ("EPI.ExtParameterInfos && \"shouldn't get here without param infos\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 2432, __PRETTY_FUNCTION__)); |
2433 | |
2434 | bool hasCheckedSwiftCall = false; |
2435 | auto checkForSwiftCC = [&](unsigned paramIndex) { |
2436 | // Only do this once. |
2437 | if (hasCheckedSwiftCall) return; |
2438 | hasCheckedSwiftCall = true; |
2439 | if (EPI.ExtInfo.getCC() == CC_Swift) return; |
2440 | S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) |
2441 | << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()); |
2442 | }; |
2443 | |
2444 | for (size_t paramIndex = 0, numParams = paramTypes.size(); |
2445 | paramIndex != numParams; ++paramIndex) { |
2446 | switch (EPI.ExtParameterInfos[paramIndex].getABI()) { |
2447 | // Nothing interesting to check for orindary-ABI parameters. |
2448 | case ParameterABI::Ordinary: |
2449 | continue; |
2450 | |
2451 | // swift_indirect_result parameters must be a prefix of the function |
2452 | // arguments. |
2453 | case ParameterABI::SwiftIndirectResult: |
2454 | checkForSwiftCC(paramIndex); |
2455 | if (paramIndex != 0 && |
2456 | EPI.ExtParameterInfos[paramIndex - 1].getABI() |
2457 | != ParameterABI::SwiftIndirectResult) { |
2458 | S.Diag(getParamLoc(paramIndex), |
2459 | diag::err_swift_indirect_result_not_first); |
2460 | } |
2461 | continue; |
2462 | |
2463 | case ParameterABI::SwiftContext: |
2464 | checkForSwiftCC(paramIndex); |
2465 | continue; |
2466 | |
2467 | // swift_error parameters must be preceded by a swift_context parameter. |
2468 | case ParameterABI::SwiftErrorResult: |
2469 | checkForSwiftCC(paramIndex); |
2470 | if (paramIndex == 0 || |
2471 | EPI.ExtParameterInfos[paramIndex - 1].getABI() != |
2472 | ParameterABI::SwiftContext) { |
2473 | S.Diag(getParamLoc(paramIndex), |
2474 | diag::err_swift_error_result_not_after_swift_context); |
2475 | } |
2476 | continue; |
2477 | } |
2478 | llvm_unreachable("bad ABI kind")::llvm::llvm_unreachable_internal("bad ABI kind", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 2478); |
2479 | } |
2480 | } |
2481 | |
2482 | QualType Sema::BuildFunctionType(QualType T, |
2483 | MutableArrayRef<QualType> ParamTypes, |
2484 | SourceLocation Loc, DeclarationName Entity, |
2485 | const FunctionProtoType::ExtProtoInfo &EPI) { |
2486 | bool Invalid = false; |
2487 | |
2488 | Invalid |= CheckFunctionReturnType(T, Loc); |
2489 | |
2490 | for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { |
2491 | // FIXME: Loc is too inprecise here, should use proper locations for args. |
2492 | QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); |
2493 | if (ParamType->isVoidType()) { |
2494 | Diag(Loc, diag::err_param_with_void_type); |
2495 | Invalid = true; |
2496 | } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { |
2497 | // Disallow half FP arguments. |
2498 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << |
2499 | FixItHint::CreateInsertion(Loc, "*"); |
2500 | Invalid = true; |
2501 | } |
2502 | |
2503 | ParamTypes[Idx] = ParamType; |
2504 | } |
2505 | |
2506 | if (EPI.ExtParameterInfos) { |
2507 | checkExtParameterInfos(*this, ParamTypes, EPI, |
2508 | [=](unsigned i) { return Loc; }); |
2509 | } |
2510 | |
2511 | if (EPI.ExtInfo.getProducesResult()) { |
2512 | // This is just a warning, so we can't fail to build if we see it. |
2513 | checkNSReturnsRetainedReturnType(Loc, T); |
2514 | } |
2515 | |
2516 | if (Invalid) |
2517 | return QualType(); |
2518 | |
2519 | return Context.getFunctionType(T, ParamTypes, EPI); |
2520 | } |
2521 | |
2522 | /// Build a member pointer type \c T Class::*. |
2523 | /// |
2524 | /// \param T the type to which the member pointer refers. |
2525 | /// \param Class the class type into which the member pointer points. |
2526 | /// \param Loc the location where this type begins |
2527 | /// \param Entity the name of the entity that will have this member pointer type |
2528 | /// |
2529 | /// \returns a member pointer type, if successful, or a NULL type if there was |
2530 | /// an error. |
2531 | QualType Sema::BuildMemberPointerType(QualType T, QualType Class, |
2532 | SourceLocation Loc, |
2533 | DeclarationName Entity) { |
2534 | // Verify that we're not building a pointer to pointer to function with |
2535 | // exception specification. |
2536 | if (CheckDistantExceptionSpec(T)) { |
2537 | Diag(Loc, diag::err_distant_exception_spec); |
2538 | return QualType(); |
2539 | } |
2540 | |
2541 | // C++ 8.3.3p3: A pointer to member shall not point to ... a member |
2542 | // with reference type, or "cv void." |
2543 | if (T->isReferenceType()) { |
2544 | Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) |
2545 | << getPrintableNameForEntity(Entity) << T; |
2546 | return QualType(); |
2547 | } |
2548 | |
2549 | if (T->isVoidType()) { |
2550 | Diag(Loc, diag::err_illegal_decl_mempointer_to_void) |
2551 | << getPrintableNameForEntity(Entity); |
2552 | return QualType(); |
2553 | } |
2554 | |
2555 | if (!Class->isDependentType() && !Class->isRecordType()) { |
2556 | Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; |
2557 | return QualType(); |
2558 | } |
2559 | |
2560 | // Adjust the default free function calling convention to the default method |
2561 | // calling convention. |
2562 | bool IsCtorOrDtor = |
2563 | (Entity.getNameKind() == DeclarationName::CXXConstructorName) || |
2564 | (Entity.getNameKind() == DeclarationName::CXXDestructorName); |
2565 | if (T->isFunctionType()) |
2566 | adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); |
2567 | |
2568 | return Context.getMemberPointerType(T, Class.getTypePtr()); |
2569 | } |
2570 | |
2571 | /// Build a block pointer type. |
2572 | /// |
2573 | /// \param T The type to which we'll be building a block pointer. |
2574 | /// |
2575 | /// \param Loc The source location, used for diagnostics. |
2576 | /// |
2577 | /// \param Entity The name of the entity that involves the block pointer |
2578 | /// type, if known. |
2579 | /// |
2580 | /// \returns A suitable block pointer type, if there are no |
2581 | /// errors. Otherwise, returns a NULL type. |
2582 | QualType Sema::BuildBlockPointerType(QualType T, |
2583 | SourceLocation Loc, |
2584 | DeclarationName Entity) { |
2585 | if (!T->isFunctionType()) { |
2586 | Diag(Loc, diag::err_nonfunction_block_type); |
2587 | return QualType(); |
2588 | } |
2589 | |
2590 | if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) |
2591 | return QualType(); |
2592 | |
2593 | return Context.getBlockPointerType(T); |
2594 | } |
2595 | |
2596 | QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { |
2597 | QualType QT = Ty.get(); |
2598 | if (QT.isNull()) { |
2599 | if (TInfo) *TInfo = nullptr; |
2600 | return QualType(); |
2601 | } |
2602 | |
2603 | TypeSourceInfo *DI = nullptr; |
2604 | if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { |
2605 | QT = LIT->getType(); |
2606 | DI = LIT->getTypeSourceInfo(); |
2607 | } |
2608 | |
2609 | if (TInfo) *TInfo = DI; |
2610 | return QT; |
2611 | } |
2612 | |
2613 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, |
2614 | Qualifiers::ObjCLifetime ownership, |
2615 | unsigned chunkIndex); |
2616 | |
2617 | /// Given that this is the declaration of a parameter under ARC, |
2618 | /// attempt to infer attributes and such for pointer-to-whatever |
2619 | /// types. |
2620 | static void inferARCWriteback(TypeProcessingState &state, |
2621 | QualType &declSpecType) { |
2622 | Sema &S = state.getSema(); |
2623 | Declarator &declarator = state.getDeclarator(); |
2624 | |
2625 | // TODO: should we care about decl qualifiers? |
2626 | |
2627 | // Check whether the declarator has the expected form. We walk |
2628 | // from the inside out in order to make the block logic work. |
2629 | unsigned outermostPointerIndex = 0; |
2630 | bool isBlockPointer = false; |
2631 | unsigned numPointers = 0; |
2632 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { |
2633 | unsigned chunkIndex = i; |
2634 | DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); |
2635 | switch (chunk.Kind) { |
2636 | case DeclaratorChunk::Paren: |
2637 | // Ignore parens. |
2638 | break; |
2639 | |
2640 | case DeclaratorChunk::Reference: |
2641 | case DeclaratorChunk::Pointer: |
2642 | // Count the number of pointers. Treat references |
2643 | // interchangeably as pointers; if they're mis-ordered, normal |
2644 | // type building will discover that. |
2645 | outermostPointerIndex = chunkIndex; |
2646 | numPointers++; |
2647 | break; |
2648 | |
2649 | case DeclaratorChunk::BlockPointer: |
2650 | // If we have a pointer to block pointer, that's an acceptable |
2651 | // indirect reference; anything else is not an application of |
2652 | // the rules. |
2653 | if (numPointers != 1) return; |
2654 | numPointers++; |
2655 | outermostPointerIndex = chunkIndex; |
2656 | isBlockPointer = true; |
2657 | |
2658 | // We don't care about pointer structure in return values here. |
2659 | goto done; |
2660 | |
2661 | case DeclaratorChunk::Array: // suppress if written (id[])? |
2662 | case DeclaratorChunk::Function: |
2663 | case DeclaratorChunk::MemberPointer: |
2664 | case DeclaratorChunk::Pipe: |
2665 | return; |
2666 | } |
2667 | } |
2668 | done: |
2669 | |
2670 | // If we have *one* pointer, then we want to throw the qualifier on |
2671 | // the declaration-specifiers, which means that it needs to be a |
2672 | // retainable object type. |
2673 | if (numPointers == 1) { |
2674 | // If it's not a retainable object type, the rule doesn't apply. |
2675 | if (!declSpecType->isObjCRetainableType()) return; |
2676 | |
2677 | // If it already has lifetime, don't do anything. |
2678 | if (declSpecType.getObjCLifetime()) return; |
2679 | |
2680 | // Otherwise, modify the type in-place. |
2681 | Qualifiers qs; |
2682 | |
2683 | if (declSpecType->isObjCARCImplicitlyUnretainedType()) |
2684 | qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); |
2685 | else |
2686 | qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); |
2687 | declSpecType = S.Context.getQualifiedType(declSpecType, qs); |
2688 | |
2689 | // If we have *two* pointers, then we want to throw the qualifier on |
2690 | // the outermost pointer. |
2691 | } else if (numPointers == 2) { |
2692 | // If we don't have a block pointer, we need to check whether the |
2693 | // declaration-specifiers gave us something that will turn into a |
2694 | // retainable object pointer after we slap the first pointer on it. |
2695 | if (!isBlockPointer && !declSpecType->isObjCObjectType()) |
2696 | return; |
2697 | |
2698 | // Look for an explicit lifetime attribute there. |
2699 | DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); |
2700 | if (chunk.Kind != DeclaratorChunk::Pointer && |
2701 | chunk.Kind != DeclaratorChunk::BlockPointer) |
2702 | return; |
2703 | for (const ParsedAttr &AL : chunk.getAttrs()) |
2704 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) |
2705 | return; |
2706 | |
2707 | transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, |
2708 | outermostPointerIndex); |
2709 | |
2710 | // Any other number of pointers/references does not trigger the rule. |
2711 | } else return; |
2712 | |
2713 | // TODO: mark whether we did this inference? |
2714 | } |
2715 | |
2716 | void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, |
2717 | SourceLocation FallbackLoc, |
2718 | SourceLocation ConstQualLoc, |
2719 | SourceLocation VolatileQualLoc, |
2720 | SourceLocation RestrictQualLoc, |
2721 | SourceLocation AtomicQualLoc, |
2722 | SourceLocation UnalignedQualLoc) { |
2723 | if (!Quals) |
2724 | return; |
2725 | |
2726 | struct Qual { |
2727 | const char *Name; |
2728 | unsigned Mask; |
2729 | SourceLocation Loc; |
2730 | } const QualKinds[5] = { |
2731 | { "const", DeclSpec::TQ_const, ConstQualLoc }, |
2732 | { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, |
2733 | { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, |
2734 | { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc }, |
2735 | { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } |
2736 | }; |
2737 | |
2738 | SmallString<32> QualStr; |
2739 | unsigned NumQuals = 0; |
2740 | SourceLocation Loc; |
2741 | FixItHint FixIts[5]; |
2742 | |
2743 | // Build a string naming the redundant qualifiers. |
2744 | for (auto &E : QualKinds) { |
2745 | if (Quals & E.Mask) { |
2746 | if (!QualStr.empty()) QualStr += ' '; |
2747 | QualStr += E.Name; |
2748 | |
2749 | // If we have a location for the qualifier, offer a fixit. |
2750 | SourceLocation QualLoc = E.Loc; |
2751 | if (QualLoc.isValid()) { |
2752 | FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); |
2753 | if (Loc.isInvalid() || |
2754 | getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) |
2755 | Loc = QualLoc; |
2756 | } |
2757 | |
2758 | ++NumQuals; |
2759 | } |
2760 | } |
2761 | |
2762 | Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) |
2763 | << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; |
2764 | } |
2765 | |
2766 | // Diagnose pointless type qualifiers on the return type of a function. |
2767 | static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, |
2768 | Declarator &D, |
2769 | unsigned FunctionChunkIndex) { |
2770 | if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { |
2771 | // FIXME: TypeSourceInfo doesn't preserve location information for |
2772 | // qualifiers. |
2773 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, |
2774 | RetTy.getLocalCVRQualifiers(), |
2775 | D.getIdentifierLoc()); |
2776 | return; |
2777 | } |
2778 | |
2779 | for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, |
2780 | End = D.getNumTypeObjects(); |
2781 | OuterChunkIndex != End; ++OuterChunkIndex) { |
2782 | DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); |
2783 | switch (OuterChunk.Kind) { |
2784 | case DeclaratorChunk::Paren: |
2785 | continue; |
2786 | |
2787 | case DeclaratorChunk::Pointer: { |
2788 | DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; |
2789 | S.diagnoseIgnoredQualifiers( |
2790 | diag::warn_qual_return_type, |
2791 | PTI.TypeQuals, |
2792 | SourceLocation(), |
2793 | SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), |
2794 | SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), |
2795 | SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), |
2796 | SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc), |
2797 | SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc)); |
2798 | return; |
2799 | } |
2800 | |
2801 | case DeclaratorChunk::Function: |
2802 | case DeclaratorChunk::BlockPointer: |
2803 | case DeclaratorChunk::Reference: |
2804 | case DeclaratorChunk::Array: |
2805 | case DeclaratorChunk::MemberPointer: |
2806 | case DeclaratorChunk::Pipe: |
2807 | // FIXME: We can't currently provide an accurate source location and a |
2808 | // fix-it hint for these. |
2809 | unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; |
2810 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, |
2811 | RetTy.getCVRQualifiers() | AtomicQual, |
2812 | D.getIdentifierLoc()); |
2813 | return; |
2814 | } |
2815 | |
2816 | llvm_unreachable("unknown declarator chunk kind")::llvm::llvm_unreachable_internal("unknown declarator chunk kind" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 2816); |
2817 | } |
2818 | |
2819 | // If the qualifiers come from a conversion function type, don't diagnose |
2820 | // them -- they're not necessarily redundant, since such a conversion |
2821 | // operator can be explicitly called as "x.operator const int()". |
2822 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) |
2823 | return; |
2824 | |
2825 | // Just parens all the way out to the decl specifiers. Diagnose any qualifiers |
2826 | // which are present there. |
2827 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, |
2828 | D.getDeclSpec().getTypeQualifiers(), |
2829 | D.getIdentifierLoc(), |
2830 | D.getDeclSpec().getConstSpecLoc(), |
2831 | D.getDeclSpec().getVolatileSpecLoc(), |
2832 | D.getDeclSpec().getRestrictSpecLoc(), |
2833 | D.getDeclSpec().getAtomicSpecLoc(), |
2834 | D.getDeclSpec().getUnalignedSpecLoc()); |
2835 | } |
2836 | |
2837 | static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, |
2838 | TypeSourceInfo *&ReturnTypeInfo) { |
2839 | Sema &SemaRef = state.getSema(); |
2840 | Declarator &D = state.getDeclarator(); |
2841 | QualType T; |
2842 | ReturnTypeInfo = nullptr; |
2843 | |
2844 | // The TagDecl owned by the DeclSpec. |
2845 | TagDecl *OwnedTagDecl = nullptr; |
2846 | |
2847 | switch (D.getName().getKind()) { |
2848 | case UnqualifiedIdKind::IK_ImplicitSelfParam: |
2849 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
2850 | case UnqualifiedIdKind::IK_Identifier: |
2851 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
2852 | case UnqualifiedIdKind::IK_TemplateId: |
2853 | T = ConvertDeclSpecToType(state); |
2854 | |
2855 | if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { |
2856 | OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); |
2857 | // Owned declaration is embedded in declarator. |
2858 | OwnedTagDecl->setEmbeddedInDeclarator(true); |
2859 | } |
2860 | break; |
2861 | |
2862 | case UnqualifiedIdKind::IK_ConstructorName: |
2863 | case UnqualifiedIdKind::IK_ConstructorTemplateId: |
2864 | case UnqualifiedIdKind::IK_DestructorName: |
2865 | // Constructors and destructors don't have return types. Use |
2866 | // "void" instead. |
2867 | T = SemaRef.Context.VoidTy; |
2868 | processTypeAttrs(state, T, TAL_DeclSpec, |
2869 | D.getMutableDeclSpec().getAttributes()); |
2870 | break; |
2871 | |
2872 | case UnqualifiedIdKind::IK_DeductionGuideName: |
2873 | // Deduction guides have a trailing return type and no type in their |
2874 | // decl-specifier sequence. Use a placeholder return type for now. |
2875 | T = SemaRef.Context.DependentTy; |
2876 | break; |
2877 | |
2878 | case UnqualifiedIdKind::IK_ConversionFunctionId: |
2879 | // The result type of a conversion function is the type that it |
2880 | // converts to. |
2881 | T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, |
2882 | &ReturnTypeInfo); |
2883 | break; |
2884 | } |
2885 | |
2886 | if (!D.getAttributes().empty()) |
2887 | distributeTypeAttrsFromDeclarator(state, T); |
2888 | |
2889 | // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. |
2890 | if (DeducedType *Deduced = T->getContainedDeducedType()) { |
2891 | AutoType *Auto = dyn_cast<AutoType>(Deduced); |
2892 | int Error = -1; |
2893 | |
2894 | // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or |
2895 | // class template argument deduction)? |
2896 | bool IsCXXAutoType = |
2897 | (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); |
2898 | bool IsDeducedReturnType = false; |
2899 | |
2900 | switch (D.getContext()) { |
2901 | case DeclaratorContext::LambdaExprContext: |
2902 | // Declared return type of a lambda-declarator is implicit and is always |
2903 | // 'auto'. |
2904 | break; |
2905 | case DeclaratorContext::ObjCParameterContext: |
2906 | case DeclaratorContext::ObjCResultContext: |
2907 | case DeclaratorContext::PrototypeContext: |
2908 | Error = 0; |
2909 | break; |
2910 | case DeclaratorContext::LambdaExprParameterContext: |
2911 | // In C++14, generic lambdas allow 'auto' in their parameters. |
2912 | if (!SemaRef.getLangOpts().CPlusPlus14 || |
2913 | !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) |
2914 | Error = 16; |
2915 | else { |
2916 | // If auto is mentioned in a lambda parameter context, convert it to a |
2917 | // template parameter type. |
2918 | sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda(); |
2919 | assert(LSI && "No LambdaScopeInfo on the stack!")((LSI && "No LambdaScopeInfo on the stack!") ? static_cast <void> (0) : __assert_fail ("LSI && \"No LambdaScopeInfo on the stack!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 2919, __PRETTY_FUNCTION__)); |
2920 | const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth; |
2921 | const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size(); |
2922 | const bool IsParameterPack = D.hasEllipsis(); |
2923 | |
2924 | // Create the TemplateTypeParmDecl here to retrieve the corresponding |
2925 | // template parameter type. Template parameters are temporarily added |
2926 | // to the TU until the associated TemplateDecl is created. |
2927 | TemplateTypeParmDecl *CorrespondingTemplateParam = |
2928 | TemplateTypeParmDecl::Create( |
2929 | SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(), |
2930 | /*KeyLoc*/ SourceLocation(), /*NameLoc*/ D.getBeginLoc(), |
2931 | TemplateParameterDepth, AutoParameterPosition, |
2932 | /*Identifier*/ nullptr, false, IsParameterPack); |
2933 | LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam); |
2934 | // Replace the 'auto' in the function parameter with this invented |
2935 | // template type parameter. |
2936 | // FIXME: Retain some type sugar to indicate that this was written |
2937 | // as 'auto'. |
2938 | T = SemaRef.ReplaceAutoType( |
2939 | T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0)); |
2940 | } |
2941 | break; |
2942 | case DeclaratorContext::MemberContext: { |
2943 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || |
2944 | D.isFunctionDeclarator()) |
2945 | break; |
2946 | bool Cxx = SemaRef.getLangOpts().CPlusPlus; |
2947 | switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { |
2948 | case TTK_Enum: llvm_unreachable("unhandled tag kind")::llvm::llvm_unreachable_internal("unhandled tag kind", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 2948); |
2949 | case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; |
2950 | case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; |
2951 | case TTK_Class: Error = 5; /* Class member */ break; |
2952 | case TTK_Interface: Error = 6; /* Interface member */ break; |
2953 | } |
2954 | if (D.getDeclSpec().isFriendSpecified()) |
2955 | Error = 20; // Friend type |
2956 | break; |
2957 | } |
2958 | case DeclaratorContext::CXXCatchContext: |
2959 | case DeclaratorContext::ObjCCatchContext: |
2960 | Error = 7; // Exception declaration |
2961 | break; |
2962 | case DeclaratorContext::TemplateParamContext: |
2963 | if (isa<DeducedTemplateSpecializationType>(Deduced)) |
2964 | Error = 19; // Template parameter |
2965 | else if (!SemaRef.getLangOpts().CPlusPlus17) |
2966 | Error = 8; // Template parameter (until C++17) |
2967 | break; |
2968 | case DeclaratorContext::BlockLiteralContext: |
2969 | Error = 9; // Block literal |
2970 | break; |
2971 | case DeclaratorContext::TemplateArgContext: |
2972 | // Within a template argument list, a deduced template specialization |
2973 | // type will be reinterpreted as a template template argument. |
2974 | if (isa<DeducedTemplateSpecializationType>(Deduced) && |
2975 | !D.getNumTypeObjects() && |
2976 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) |
2977 | break; |
2978 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
2979 | case DeclaratorContext::TemplateTypeArgContext: |
2980 | Error = 10; // Template type argument |
2981 | break; |
2982 | case DeclaratorContext::AliasDeclContext: |
2983 | case DeclaratorContext::AliasTemplateContext: |
2984 | Error = 12; // Type alias |
2985 | break; |
2986 | case DeclaratorContext::TrailingReturnContext: |
2987 | case DeclaratorContext::TrailingReturnVarContext: |
2988 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) |
2989 | Error = 13; // Function return type |
2990 | IsDeducedReturnType = true; |
2991 | break; |
2992 | case DeclaratorContext::ConversionIdContext: |
2993 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) |
2994 | Error = 14; // conversion-type-id |
2995 | IsDeducedReturnType = true; |
2996 | break; |
2997 | case DeclaratorContext::FunctionalCastContext: |
2998 | if (isa<DeducedTemplateSpecializationType>(Deduced)) |
2999 | break; |
3000 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
3001 | case DeclaratorContext::TypeNameContext: |
3002 | Error = 15; // Generic |
3003 | break; |
3004 | case DeclaratorContext::FileContext: |
3005 | case DeclaratorContext::BlockContext: |
3006 | case DeclaratorContext::ForContext: |
3007 | case DeclaratorContext::InitStmtContext: |
3008 | case DeclaratorContext::ConditionContext: |
3009 | // FIXME: P0091R3 (erroneously) does not permit class template argument |
3010 | // deduction in conditions, for-init-statements, and other declarations |
3011 | // that are not simple-declarations. |
3012 | break; |
3013 | case DeclaratorContext::CXXNewContext: |
3014 | // FIXME: P0091R3 does not permit class template argument deduction here, |
3015 | // but we follow GCC and allow it anyway. |
3016 | if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) |
3017 | Error = 17; // 'new' type |
3018 | break; |
3019 | case DeclaratorContext::KNRTypeListContext: |
3020 | Error = 18; // K&R function parameter |
3021 | break; |
3022 | } |
3023 | |
3024 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) |
3025 | Error = 11; |
3026 | |
3027 | // In Objective-C it is an error to use 'auto' on a function declarator |
3028 | // (and everywhere for '__auto_type'). |
3029 | if (D.isFunctionDeclarator() && |
3030 | (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) |
3031 | Error = 13; |
3032 | |
3033 | bool HaveTrailing = false; |
3034 | |
3035 | // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator |
3036 | // contains a trailing return type. That is only legal at the outermost |
3037 | // level. Check all declarator chunks (outermost first) anyway, to give |
3038 | // better diagnostics. |
3039 | // We don't support '__auto_type' with trailing return types. |
3040 | // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'? |
3041 | if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType && |
3042 | D.hasTrailingReturnType()) { |
3043 | HaveTrailing = true; |
3044 | Error = -1; |
3045 | } |
3046 | |
3047 | SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); |
3048 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) |
3049 | AutoRange = D.getName().getSourceRange(); |
3050 | |
3051 | if (Error != -1) { |
3052 | unsigned Kind; |
3053 | if (Auto) { |
3054 | switch (Auto->getKeyword()) { |
3055 | case AutoTypeKeyword::Auto: Kind = 0; break; |
3056 | case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; |
3057 | case AutoTypeKeyword::GNUAutoType: Kind = 2; break; |
3058 | } |
3059 | } else { |
3060 | assert(isa<DeducedTemplateSpecializationType>(Deduced) &&((isa<DeducedTemplateSpecializationType>(Deduced) && "unknown auto type") ? static_cast<void> (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3061, __PRETTY_FUNCTION__)) |
3061 | "unknown auto type")((isa<DeducedTemplateSpecializationType>(Deduced) && "unknown auto type") ? static_cast<void> (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3061, __PRETTY_FUNCTION__)); |
3062 | Kind = 3; |
3063 | } |
3064 | |
3065 | auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); |
3066 | TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); |
3067 | |
3068 | SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) |
3069 | << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) |
3070 | << QualType(Deduced, 0) << AutoRange; |
3071 | if (auto *TD = TN.getAsTemplateDecl()) |
3072 | SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here); |
3073 | |
3074 | T = SemaRef.Context.IntTy; |
3075 | D.setInvalidType(true); |
3076 | } else if (!HaveTrailing && |
3077 | D.getContext() != DeclaratorContext::LambdaExprContext) { |
3078 | // If there was a trailing return type, we already got |
3079 | // warn_cxx98_compat_trailing_return_type in the parser. |
3080 | SemaRef.Diag(AutoRange.getBegin(), |
3081 | D.getContext() == |
3082 | DeclaratorContext::LambdaExprParameterContext |
3083 | ? diag::warn_cxx11_compat_generic_lambda |
3084 | : IsDeducedReturnType |
3085 | ? diag::warn_cxx11_compat_deduced_return_type |
3086 | : diag::warn_cxx98_compat_auto_type_specifier) |
3087 | << AutoRange; |
3088 | } |
3089 | } |
3090 | |
3091 | if (SemaRef.getLangOpts().CPlusPlus && |
3092 | OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { |
3093 | // Check the contexts where C++ forbids the declaration of a new class |
3094 | // or enumeration in a type-specifier-seq. |
3095 | unsigned DiagID = 0; |
3096 | switch (D.getContext()) { |
3097 | case DeclaratorContext::TrailingReturnContext: |
3098 | case DeclaratorContext::TrailingReturnVarContext: |
3099 | // Class and enumeration definitions are syntactically not allowed in |
3100 | // trailing return types. |
3101 | llvm_unreachable("parser should not have allowed this")::llvm::llvm_unreachable_internal("parser should not have allowed this" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3101); |
3102 | break; |
3103 | case DeclaratorContext::FileContext: |
3104 | case DeclaratorContext::MemberContext: |
3105 | case DeclaratorContext::BlockContext: |
3106 | case DeclaratorContext::ForContext: |
3107 | case DeclaratorContext::InitStmtContext: |
3108 | case DeclaratorContext::BlockLiteralContext: |
3109 | case DeclaratorContext::LambdaExprContext: |
3110 | // C++11 [dcl.type]p3: |
3111 | // A type-specifier-seq shall not define a class or enumeration unless |
3112 | // it appears in the type-id of an alias-declaration (7.1.3) that is not |
3113 | // the declaration of a template-declaration. |
3114 | case DeclaratorContext::AliasDeclContext: |
3115 | break; |
3116 | case DeclaratorContext::AliasTemplateContext: |
3117 | DiagID = diag::err_type_defined_in_alias_template; |
3118 | break; |
3119 | case DeclaratorContext::TypeNameContext: |
3120 | case DeclaratorContext::FunctionalCastContext: |
3121 | case DeclaratorContext::ConversionIdContext: |
3122 | case DeclaratorContext::TemplateParamContext: |
3123 | case DeclaratorContext::CXXNewContext: |
3124 | case DeclaratorContext::CXXCatchContext: |
3125 | case DeclaratorContext::ObjCCatchContext: |
3126 | case DeclaratorContext::TemplateArgContext: |
3127 | case DeclaratorContext::TemplateTypeArgContext: |
3128 | DiagID = diag::err_type_defined_in_type_specifier; |
3129 | break; |
3130 | case DeclaratorContext::PrototypeContext: |
3131 | case DeclaratorContext::LambdaExprParameterContext: |
3132 | case DeclaratorContext::ObjCParameterContext: |
3133 | case DeclaratorContext::ObjCResultContext: |
3134 | case DeclaratorContext::KNRTypeListContext: |
3135 | // C++ [dcl.fct]p6: |
3136 | // Types shall not be defined in return or parameter types. |
3137 | DiagID = diag::err_type_defined_in_param_type; |
3138 | break; |
3139 | case DeclaratorContext::ConditionContext: |
3140 | // C++ 6.4p2: |
3141 | // The type-specifier-seq shall not contain typedef and shall not declare |
3142 | // a new class or enumeration. |
3143 | DiagID = diag::err_type_defined_in_condition; |
3144 | break; |
3145 | } |
3146 | |
3147 | if (DiagID != 0) { |
3148 | SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) |
3149 | << SemaRef.Context.getTypeDeclType(OwnedTagDecl); |
3150 | D.setInvalidType(true); |
3151 | } |
3152 | } |
3153 | |
3154 | assert(!T.isNull() && "This function should not return a null type")((!T.isNull() && "This function should not return a null type" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"This function should not return a null type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3154, __PRETTY_FUNCTION__)); |
3155 | return T; |
3156 | } |
3157 | |
3158 | /// Produce an appropriate diagnostic for an ambiguity between a function |
3159 | /// declarator and a C++ direct-initializer. |
3160 | static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, |
3161 | DeclaratorChunk &DeclType, QualType RT) { |
3162 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; |
3163 | assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity")((FTI.isAmbiguous && "no direct-initializer / function ambiguity" ) ? static_cast<void> (0) : __assert_fail ("FTI.isAmbiguous && \"no direct-initializer / function ambiguity\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3163, __PRETTY_FUNCTION__)); |
3164 | |
3165 | // If the return type is void there is no ambiguity. |
3166 | if (RT->isVoidType()) |
3167 | return; |
3168 | |
3169 | // An initializer for a non-class type can have at most one argument. |
3170 | if (!RT->isRecordType() && FTI.NumParams > 1) |
3171 | return; |
3172 | |
3173 | // An initializer for a reference must have exactly one argument. |
3174 | if (RT->isReferenceType() && FTI.NumParams != 1) |
3175 | return; |
3176 | |
3177 | // Only warn if this declarator is declaring a function at block scope, and |
3178 | // doesn't have a storage class (such as 'extern') specified. |
3179 | if (!D.isFunctionDeclarator() || |
3180 | D.getFunctionDefinitionKind() != FDK_Declaration || |
3181 | !S.CurContext->isFunctionOrMethod() || |
3182 | D.getDeclSpec().getStorageClassSpec() |
3183 | != DeclSpec::SCS_unspecified) |
3184 | return; |
3185 | |
3186 | // Inside a condition, a direct initializer is not permitted. We allow one to |
3187 | // be parsed in order to give better diagnostics in condition parsing. |
3188 | if (D.getContext() == DeclaratorContext::ConditionContext) |
3189 | return; |
3190 | |
3191 | SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); |
3192 | |
3193 | S.Diag(DeclType.Loc, |
3194 | FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration |
3195 | : diag::warn_empty_parens_are_function_decl) |
3196 | << ParenRange; |
3197 | |
3198 | // If the declaration looks like: |
3199 | // T var1, |
3200 | // f(); |
3201 | // and name lookup finds a function named 'f', then the ',' was |
3202 | // probably intended to be a ';'. |
3203 | if (!D.isFirstDeclarator() && D.getIdentifier()) { |
3204 | FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); |
3205 | FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); |
3206 | if (Comma.getFileID() != Name.getFileID() || |
3207 | Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { |
3208 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), |
3209 | Sema::LookupOrdinaryName); |
3210 | if (S.LookupName(Result, S.getCurScope())) |
3211 | S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) |
3212 | << FixItHint::CreateReplacement(D.getCommaLoc(), ";") |
3213 | << D.getIdentifier(); |
3214 | Result.suppressDiagnostics(); |
3215 | } |
3216 | } |
3217 | |
3218 | if (FTI.NumParams > 0) { |
3219 | // For a declaration with parameters, eg. "T var(T());", suggest adding |
3220 | // parens around the first parameter to turn the declaration into a |
3221 | // variable declaration. |
3222 | SourceRange Range = FTI.Params[0].Param->getSourceRange(); |
3223 | SourceLocation B = Range.getBegin(); |
3224 | SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); |
3225 | // FIXME: Maybe we should suggest adding braces instead of parens |
3226 | // in C++11 for classes that don't have an initializer_list constructor. |
3227 | S.Diag(B, diag::note_additional_parens_for_variable_declaration) |
3228 | << FixItHint::CreateInsertion(B, "(") |
3229 | << FixItHint::CreateInsertion(E, ")"); |
3230 | } else { |
3231 | // For a declaration without parameters, eg. "T var();", suggest replacing |
3232 | // the parens with an initializer to turn the declaration into a variable |
3233 | // declaration. |
3234 | const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); |
3235 | |
3236 | // Empty parens mean value-initialization, and no parens mean |
3237 | // default initialization. These are equivalent if the default |
3238 | // constructor is user-provided or if zero-initialization is a |
3239 | // no-op. |
3240 | if (RD && RD->hasDefinition() && |
3241 | (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) |
3242 | S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) |
3243 | << FixItHint::CreateRemoval(ParenRange); |
3244 | else { |
3245 | std::string Init = |
3246 | S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); |
3247 | if (Init.empty() && S.LangOpts.CPlusPlus11) |
3248 | Init = "{}"; |
3249 | if (!Init.empty()) |
3250 | S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) |
3251 | << FixItHint::CreateReplacement(ParenRange, Init); |
3252 | } |
3253 | } |
3254 | } |
3255 | |
3256 | /// Produce an appropriate diagnostic for a declarator with top-level |
3257 | /// parentheses. |
3258 | static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { |
3259 | DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); |
3260 | assert(Paren.Kind == DeclaratorChunk::Paren &&((Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses" ) ? static_cast<void> (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3261, __PRETTY_FUNCTION__)) |
3261 | "do not have redundant top-level parentheses")((Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses" ) ? static_cast<void> (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3261, __PRETTY_FUNCTION__)); |
3262 | |
3263 | // This is a syntactic check; we're not interested in cases that arise |
3264 | // during template instantiation. |
3265 | if (S.inTemplateInstantiation()) |
3266 | return; |
3267 | |
3268 | // Check whether this could be intended to be a construction of a temporary |
3269 | // object in C++ via a function-style cast. |
3270 | bool CouldBeTemporaryObject = |
3271 | S.getLangOpts().CPlusPlus && D.isExpressionContext() && |
3272 | !D.isInvalidType() && D.getIdentifier() && |
3273 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && |
3274 | (T->isRecordType() || T->isDependentType()) && |
3275 | D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); |
3276 | |
3277 | bool StartsWithDeclaratorId = true; |
3278 | for (auto &C : D.type_objects()) { |
3279 | switch (C.Kind) { |
3280 | case DeclaratorChunk::Paren: |
3281 | if (&C == &Paren) |
3282 | continue; |
3283 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
3284 | case DeclaratorChunk::Pointer: |
3285 | StartsWithDeclaratorId = false; |
3286 | continue; |
3287 | |
3288 | case DeclaratorChunk::Array: |
3289 | if (!C.Arr.NumElts) |
3290 | CouldBeTemporaryObject = false; |
3291 | continue; |
3292 | |
3293 | case DeclaratorChunk::Reference: |
3294 | // FIXME: Suppress the warning here if there is no initializer; we're |
3295 | // going to give an error anyway. |
3296 | // We assume that something like 'T (&x) = y;' is highly likely to not |
3297 | // be intended to be a temporary object. |
3298 | CouldBeTemporaryObject = false; |
3299 | StartsWithDeclaratorId = false; |
3300 | continue; |
3301 | |
3302 | case DeclaratorChunk::Function: |
3303 | // In a new-type-id, function chunks require parentheses. |
3304 | if (D.getContext() == DeclaratorContext::CXXNewContext) |
3305 | return; |
3306 | // FIXME: "A(f())" deserves a vexing-parse warning, not just a |
3307 | // redundant-parens warning, but we don't know whether the function |
3308 | // chunk was syntactically valid as an expression here. |
3309 | CouldBeTemporaryObject = false; |
3310 | continue; |
3311 | |
3312 | case DeclaratorChunk::BlockPointer: |
3313 | case DeclaratorChunk::MemberPointer: |
3314 | case DeclaratorChunk::Pipe: |
3315 | // These cannot appear in expressions. |
3316 | CouldBeTemporaryObject = false; |
3317 | StartsWithDeclaratorId = false; |
3318 | continue; |
3319 | } |
3320 | } |
3321 | |
3322 | // FIXME: If there is an initializer, assume that this is not intended to be |
3323 | // a construction of a temporary object. |
3324 | |
3325 | // Check whether the name has already been declared; if not, this is not a |
3326 | // function-style cast. |
3327 | if (CouldBeTemporaryObject) { |
3328 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), |
3329 | Sema::LookupOrdinaryName); |
3330 | if (!S.LookupName(Result, S.getCurScope())) |
3331 | CouldBeTemporaryObject = false; |
3332 | Result.suppressDiagnostics(); |
3333 | } |
3334 | |
3335 | SourceRange ParenRange(Paren.Loc, Paren.EndLoc); |
3336 | |
3337 | if (!CouldBeTemporaryObject) { |
3338 | // If we have A (::B), the parentheses affect the meaning of the program. |
3339 | // Suppress the warning in that case. Don't bother looking at the DeclSpec |
3340 | // here: even (e.g.) "int ::x" is visually ambiguous even though it's |
3341 | // formally unambiguous. |
3342 | if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { |
3343 | for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; |
3344 | NNS = NNS->getPrefix()) { |
3345 | if (NNS->getKind() == NestedNameSpecifier::Global) |
3346 | return; |
3347 | } |
3348 | } |
3349 | |
3350 | S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) |
3351 | << ParenRange << FixItHint::CreateRemoval(Paren.Loc) |
3352 | << FixItHint::CreateRemoval(Paren.EndLoc); |
3353 | return; |
3354 | } |
3355 | |
3356 | S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) |
3357 | << ParenRange << D.getIdentifier(); |
3358 | auto *RD = T->getAsCXXRecordDecl(); |
3359 | if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) |
3360 | S.Diag(Paren.Loc, diag::note_raii_guard_add_name) |
3361 | << FixItHint::CreateInsertion(Paren.Loc, " varname") << T |
3362 | << D.getIdentifier(); |
3363 | // FIXME: A cast to void is probably a better suggestion in cases where it's |
3364 | // valid (when there is no initializer and we're not in a condition). |
3365 | S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) |
3366 | << FixItHint::CreateInsertion(D.getBeginLoc(), "(") |
3367 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")"); |
3368 | S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) |
3369 | << FixItHint::CreateRemoval(Paren.Loc) |
3370 | << FixItHint::CreateRemoval(Paren.EndLoc); |
3371 | } |
3372 | |
3373 | /// Helper for figuring out the default CC for a function declarator type. If |
3374 | /// this is the outermost chunk, then we can determine the CC from the |
3375 | /// declarator context. If not, then this could be either a member function |
3376 | /// type or normal function type. |
3377 | static CallingConv getCCForDeclaratorChunk( |
3378 | Sema &S, Declarator &D, const ParsedAttributesView &AttrList, |
3379 | const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { |
3380 | assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function)((D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function ) ? static_cast<void> (0) : __assert_fail ("D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3380, __PRETTY_FUNCTION__)); |
3381 | |
3382 | // Check for an explicit CC attribute. |
3383 | for (const ParsedAttr &AL : AttrList) { |
3384 | switch (AL.getKind()) { |
3385 | 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_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 : { |
3386 | // Ignore attributes that don't validate or can't apply to the |
3387 | // function type. We'll diagnose the failure to apply them in |
3388 | // handleFunctionTypeAttr. |
3389 | CallingConv CC; |
3390 | if (!S.CheckCallingConvAttr(AL, CC) && |
3391 | (!FTI.isVariadic || supportsVariadicCall(CC))) { |
3392 | return CC; |
3393 | } |
3394 | break; |
3395 | } |
3396 | |
3397 | default: |
3398 | break; |
3399 | } |
3400 | } |
3401 | |
3402 | bool IsCXXInstanceMethod = false; |
3403 | |
3404 | if (S.getLangOpts().CPlusPlus) { |
3405 | // Look inwards through parentheses to see if this chunk will form a |
3406 | // member pointer type or if we're the declarator. Any type attributes |
3407 | // between here and there will override the CC we choose here. |
3408 | unsigned I = ChunkIndex; |
3409 | bool FoundNonParen = false; |
3410 | while (I && !FoundNonParen) { |
3411 | --I; |
3412 | if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) |
3413 | FoundNonParen = true; |
3414 | } |
3415 | |
3416 | if (FoundNonParen) { |
3417 | // If we're not the declarator, we're a regular function type unless we're |
3418 | // in a member pointer. |
3419 | IsCXXInstanceMethod = |
3420 | D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; |
3421 | } else if (D.getContext() == DeclaratorContext::LambdaExprContext) { |
3422 | // This can only be a call operator for a lambda, which is an instance |
3423 | // method. |
3424 | IsCXXInstanceMethod = true; |
3425 | } else { |
3426 | // We're the innermost decl chunk, so must be a function declarator. |
3427 | assert(D.isFunctionDeclarator())((D.isFunctionDeclarator()) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3427, __PRETTY_FUNCTION__)); |
3428 | |
3429 | // If we're inside a record, we're declaring a method, but it could be |
3430 | // explicitly or implicitly static. |
3431 | IsCXXInstanceMethod = |
3432 | D.isFirstDeclarationOfMember() && |
3433 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && |
3434 | !D.isStaticMember(); |
3435 | } |
3436 | } |
3437 | |
3438 | CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, |
3439 | IsCXXInstanceMethod); |
3440 | |
3441 | // Attribute AT_OpenCLKernel affects the calling convention for SPIR |
3442 | // and AMDGPU targets, hence it cannot be treated as a calling |
3443 | // convention attribute. This is the simplest place to infer |
3444 | // calling convention for OpenCL kernels. |
3445 | if (S.getLangOpts().OpenCL) { |
3446 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { |
3447 | if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { |
3448 | CC = CC_OpenCLKernel; |
3449 | break; |
3450 | } |
3451 | } |
3452 | } |
3453 | |
3454 | return CC; |
3455 | } |
3456 | |
3457 | namespace { |
3458 | /// A simple notion of pointer kinds, which matches up with the various |
3459 | /// pointer declarators. |
3460 | enum class SimplePointerKind { |
3461 | Pointer, |
3462 | BlockPointer, |
3463 | MemberPointer, |
3464 | Array, |
3465 | }; |
3466 | } // end anonymous namespace |
3467 | |
3468 | IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { |
3469 | switch (nullability) { |
3470 | case NullabilityKind::NonNull: |
3471 | if (!Ident__Nonnull) |
3472 | Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); |
3473 | return Ident__Nonnull; |
3474 | |
3475 | case NullabilityKind::Nullable: |
3476 | if (!Ident__Nullable) |
3477 | Ident__Nullable = PP.getIdentifierInfo("_Nullable"); |
3478 | return Ident__Nullable; |
3479 | |
3480 | case NullabilityKind::Unspecified: |
3481 | if (!Ident__Null_unspecified) |
3482 | Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); |
3483 | return Ident__Null_unspecified; |
3484 | } |
3485 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3485); |
3486 | } |
3487 | |
3488 | /// Retrieve the identifier "NSError". |
3489 | IdentifierInfo *Sema::getNSErrorIdent() { |
3490 | if (!Ident_NSError) |
3491 | Ident_NSError = PP.getIdentifierInfo("NSError"); |
3492 | |
3493 | return Ident_NSError; |
3494 | } |
3495 | |
3496 | /// Check whether there is a nullability attribute of any kind in the given |
3497 | /// attribute list. |
3498 | static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { |
3499 | for (const ParsedAttr &AL : attrs) { |
3500 | if (AL.getKind() == ParsedAttr::AT_TypeNonNull || |
3501 | AL.getKind() == ParsedAttr::AT_TypeNullable || |
3502 | AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) |
3503 | return true; |
3504 | } |
3505 | |
3506 | return false; |
3507 | } |
3508 | |
3509 | namespace { |
3510 | /// Describes the kind of a pointer a declarator describes. |
3511 | enum class PointerDeclaratorKind { |
3512 | // Not a pointer. |
3513 | NonPointer, |
3514 | // Single-level pointer. |
3515 | SingleLevelPointer, |
3516 | // Multi-level pointer (of any pointer kind). |
3517 | MultiLevelPointer, |
3518 | // CFFooRef* |
3519 | MaybePointerToCFRef, |
3520 | // CFErrorRef* |
3521 | CFErrorRefPointer, |
3522 | // NSError** |
3523 | NSErrorPointerPointer, |
3524 | }; |
3525 | |
3526 | /// Describes a declarator chunk wrapping a pointer that marks inference as |
3527 | /// unexpected. |
3528 | // These values must be kept in sync with diagnostics. |
3529 | enum class PointerWrappingDeclaratorKind { |
3530 | /// Pointer is top-level. |
3531 | None = -1, |
3532 | /// Pointer is an array element. |
3533 | Array = 0, |
3534 | /// Pointer is the referent type of a C++ reference. |
3535 | Reference = 1 |
3536 | }; |
3537 | } // end anonymous namespace |
3538 | |
3539 | /// Classify the given declarator, whose type-specified is \c type, based on |
3540 | /// what kind of pointer it refers to. |
3541 | /// |
3542 | /// This is used to determine the default nullability. |
3543 | static PointerDeclaratorKind |
3544 | classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, |
3545 | PointerWrappingDeclaratorKind &wrappingKind) { |
3546 | unsigned numNormalPointers = 0; |
3547 | |
3548 | // For any dependent type, we consider it a non-pointer. |
3549 | if (type->isDependentType()) |
3550 | return PointerDeclaratorKind::NonPointer; |
3551 | |
3552 | // Look through the declarator chunks to identify pointers. |
3553 | for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { |
3554 | DeclaratorChunk &chunk = declarator.getTypeObject(i); |
3555 | switch (chunk.Kind) { |
3556 | case DeclaratorChunk::Array: |
3557 | if (numNormalPointers == 0) |
3558 | wrappingKind = PointerWrappingDeclaratorKind::Array; |
3559 | break; |
3560 | |
3561 | case DeclaratorChunk::Function: |
3562 | case DeclaratorChunk::Pipe: |
3563 | break; |
3564 | |
3565 | case DeclaratorChunk::BlockPointer: |
3566 | case DeclaratorChunk::MemberPointer: |
3567 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer |
3568 | : PointerDeclaratorKind::SingleLevelPointer; |
3569 | |
3570 | case DeclaratorChunk::Paren: |
3571 | break; |
3572 | |
3573 | case DeclaratorChunk::Reference: |
3574 | if (numNormalPointers == 0) |
3575 | wrappingKind = PointerWrappingDeclaratorKind::Reference; |
3576 | break; |
3577 | |
3578 | case DeclaratorChunk::Pointer: |
3579 | ++numNormalPointers; |
3580 | if (numNormalPointers > 2) |
3581 | return PointerDeclaratorKind::MultiLevelPointer; |
3582 | break; |
3583 | } |
3584 | } |
3585 | |
3586 | // Then, dig into the type specifier itself. |
3587 | unsigned numTypeSpecifierPointers = 0; |
3588 | do { |
3589 | // Decompose normal pointers. |
3590 | if (auto ptrType = type->getAs<PointerType>()) { |
3591 | ++numNormalPointers; |
3592 | |
3593 | if (numNormalPointers > 2) |
3594 | return PointerDeclaratorKind::MultiLevelPointer; |
3595 | |
3596 | type = ptrType->getPointeeType(); |
3597 | ++numTypeSpecifierPointers; |
3598 | continue; |
3599 | } |
3600 | |
3601 | // Decompose block pointers. |
3602 | if (type->getAs<BlockPointerType>()) { |
3603 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer |
3604 | : PointerDeclaratorKind::SingleLevelPointer; |
3605 | } |
3606 | |
3607 | // Decompose member pointers. |
3608 | if (type->getAs<MemberPointerType>()) { |
3609 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer |
3610 | : PointerDeclaratorKind::SingleLevelPointer; |
3611 | } |
3612 | |
3613 | // Look at Objective-C object pointers. |
3614 | if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { |
3615 | ++numNormalPointers; |
3616 | ++numTypeSpecifierPointers; |
3617 | |
3618 | // If this is NSError**, report that. |
3619 | if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { |
3620 | if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && |
3621 | numNormalPointers == 2 && numTypeSpecifierPointers < 2) { |
3622 | return PointerDeclaratorKind::NSErrorPointerPointer; |
3623 | } |
3624 | } |
3625 | |
3626 | break; |
3627 | } |
3628 | |
3629 | // Look at Objective-C class types. |
3630 | if (auto objcClass = type->getAs<ObjCInterfaceType>()) { |
3631 | if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { |
3632 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) |
3633 | return PointerDeclaratorKind::NSErrorPointerPointer; |
3634 | } |
3635 | |
3636 | break; |
3637 | } |
3638 | |
3639 | // If at this point we haven't seen a pointer, we won't see one. |
3640 | if (numNormalPointers == 0) |
3641 | return PointerDeclaratorKind::NonPointer; |
3642 | |
3643 | if (auto recordType = type->getAs<RecordType>()) { |
3644 | RecordDecl *recordDecl = recordType->getDecl(); |
3645 | |
3646 | bool isCFError = false; |
3647 | if (S.CFError) { |
3648 | // If we already know about CFError, test it directly. |
3649 | isCFError = (S.CFError == recordDecl); |
3650 | } else { |
3651 | // Check whether this is CFError, which we identify based on its bridge |
3652 | // to NSError. CFErrorRef used to be declared with "objc_bridge" but is |
3653 | // now declared with "objc_bridge_mutable", so look for either one of |
3654 | // the two attributes. |
3655 | if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) { |
3656 | IdentifierInfo *bridgedType = nullptr; |
3657 | if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) |
3658 | bridgedType = bridgeAttr->getBridgedType(); |
3659 | else if (auto bridgeAttr = |
3660 | recordDecl->getAttr<ObjCBridgeMutableAttr>()) |
3661 | bridgedType = bridgeAttr->getBridgedType(); |
3662 | |
3663 | if (bridgedType == S.getNSErrorIdent()) { |
3664 | S.CFError = recordDecl; |
3665 | isCFError = true; |
3666 | } |
3667 | } |
3668 | } |
3669 | |
3670 | // If this is CFErrorRef*, report it as such. |
3671 | if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) { |
3672 | return PointerDeclaratorKind::CFErrorRefPointer; |
3673 | } |
3674 | break; |
3675 | } |
3676 | |
3677 | break; |
3678 | } while (true); |
3679 | |
3680 | switch (numNormalPointers) { |
3681 | case 0: |
3682 | return PointerDeclaratorKind::NonPointer; |
3683 | |
3684 | case 1: |
3685 | return PointerDeclaratorKind::SingleLevelPointer; |
3686 | |
3687 | case 2: |
3688 | return PointerDeclaratorKind::MaybePointerToCFRef; |
3689 | |
3690 | default: |
3691 | return PointerDeclaratorKind::MultiLevelPointer; |
3692 | } |
3693 | } |
3694 | |
3695 | static FileID getNullabilityCompletenessCheckFileID(Sema &S, |
3696 | SourceLocation loc) { |
3697 | // If we're anywhere in a function, method, or closure context, don't perform |
3698 | // completeness checks. |
3699 | for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { |
3700 | if (ctx->isFunctionOrMethod()) |
3701 | return FileID(); |
3702 | |
3703 | if (ctx->isFileContext()) |
3704 | break; |
3705 | } |
3706 | |
3707 | // We only care about the expansion location. |
3708 | loc = S.SourceMgr.getExpansionLoc(loc); |
3709 | FileID file = S.SourceMgr.getFileID(loc); |
3710 | if (file.isInvalid()) |
3711 | return FileID(); |
3712 | |
3713 | // Retrieve file information. |
3714 | bool invalid = false; |
3715 | const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); |
3716 | if (invalid || !sloc.isFile()) |
3717 | return FileID(); |
3718 | |
3719 | // We don't want to perform completeness checks on the main file or in |
3720 | // system headers. |
3721 | const SrcMgr::FileInfo &fileInfo = sloc.getFile(); |
3722 | if (fileInfo.getIncludeLoc().isInvalid()) |
3723 | return FileID(); |
3724 | if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && |
3725 | S.Diags.getSuppressSystemWarnings()) { |
3726 | return FileID(); |
3727 | } |
3728 | |
3729 | return file; |
3730 | } |
3731 | |
3732 | /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, |
3733 | /// taking into account whitespace before and after. |
3734 | static void fixItNullability(Sema &S, DiagnosticBuilder &Diag, |
3735 | SourceLocation PointerLoc, |
3736 | NullabilityKind Nullability) { |
3737 | assert(PointerLoc.isValid())((PointerLoc.isValid()) ? static_cast<void> (0) : __assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3737, __PRETTY_FUNCTION__)); |
3738 | if (PointerLoc.isMacroID()) |
3739 | return; |
3740 | |
3741 | SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); |
3742 | if (!FixItLoc.isValid() || FixItLoc == PointerLoc) |
3743 | return; |
3744 | |
3745 | const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); |
3746 | if (!NextChar) |
3747 | return; |
3748 | |
3749 | SmallString<32> InsertionTextBuf{" "}; |
3750 | InsertionTextBuf += getNullabilitySpelling(Nullability); |
3751 | InsertionTextBuf += " "; |
3752 | StringRef InsertionText = InsertionTextBuf.str(); |
3753 | |
3754 | if (isWhitespace(*NextChar)) { |
3755 | InsertionText = InsertionText.drop_back(); |
3756 | } else if (NextChar[-1] == '[') { |
3757 | if (NextChar[0] == ']') |
3758 | InsertionText = InsertionText.drop_back().drop_front(); |
3759 | else |
3760 | InsertionText = InsertionText.drop_front(); |
3761 | } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) && |
3762 | !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) { |
3763 | InsertionText = InsertionText.drop_back().drop_front(); |
3764 | } |
3765 | |
3766 | Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); |
3767 | } |
3768 | |
3769 | static void emitNullabilityConsistencyWarning(Sema &S, |
3770 | SimplePointerKind PointerKind, |
3771 | SourceLocation PointerLoc, |
3772 | SourceLocation PointerEndLoc) { |
3773 | assert(PointerLoc.isValid())((PointerLoc.isValid()) ? static_cast<void> (0) : __assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3773, __PRETTY_FUNCTION__)); |
3774 | |
3775 | if (PointerKind == SimplePointerKind::Array) { |
3776 | S.Diag(PointerLoc, diag::warn_nullability_missing_array); |
3777 | } else { |
3778 | S.Diag(PointerLoc, diag::warn_nullability_missing) |
3779 | << static_cast<unsigned>(PointerKind); |
3780 | } |
3781 | |
3782 | auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; |
3783 | if (FixItLoc.isMacroID()) |
3784 | return; |
3785 | |
3786 | auto addFixIt = [&](NullabilityKind Nullability) { |
3787 | auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); |
3788 | Diag << static_cast<unsigned>(Nullability); |
3789 | Diag << static_cast<unsigned>(PointerKind); |
3790 | fixItNullability(S, Diag, FixItLoc, Nullability); |
3791 | }; |
3792 | addFixIt(NullabilityKind::Nullable); |
3793 | addFixIt(NullabilityKind::NonNull); |
3794 | } |
3795 | |
3796 | /// Complains about missing nullability if the file containing \p pointerLoc |
3797 | /// has other uses of nullability (either the keywords or the \c assume_nonnull |
3798 | /// pragma). |
3799 | /// |
3800 | /// If the file has \e not seen other uses of nullability, this particular |
3801 | /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). |
3802 | static void |
3803 | checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, |
3804 | SourceLocation pointerLoc, |
3805 | SourceLocation pointerEndLoc = SourceLocation()) { |
3806 | // Determine which file we're performing consistency checking for. |
3807 | FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); |
3808 | if (file.isInvalid()) |
3809 | return; |
3810 | |
3811 | // If we haven't seen any type nullability in this file, we won't warn now |
3812 | // about anything. |
3813 | FileNullability &fileNullability = S.NullabilityMap[file]; |
3814 | if (!fileNullability.SawTypeNullability) { |
3815 | // If this is the first pointer declarator in the file, and the appropriate |
3816 | // warning is on, record it in case we need to diagnose it retroactively. |
3817 | diag::kind diagKind; |
3818 | if (pointerKind == SimplePointerKind::Array) |
3819 | diagKind = diag::warn_nullability_missing_array; |
3820 | else |
3821 | diagKind = diag::warn_nullability_missing; |
3822 | |
3823 | if (fileNullability.PointerLoc.isInvalid() && |
3824 | !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { |
3825 | fileNullability.PointerLoc = pointerLoc; |
3826 | fileNullability.PointerEndLoc = pointerEndLoc; |
3827 | fileNullability.PointerKind = static_cast<unsigned>(pointerKind); |
3828 | } |
3829 | |
3830 | return; |
3831 | } |
3832 | |
3833 | // Complain about missing nullability. |
3834 | emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); |
3835 | } |
3836 | |
3837 | /// Marks that a nullability feature has been used in the file containing |
3838 | /// \p loc. |
3839 | /// |
3840 | /// If this file already had pointer types in it that were missing nullability, |
3841 | /// the first such instance is retroactively diagnosed. |
3842 | /// |
3843 | /// \sa checkNullabilityConsistency |
3844 | static void recordNullabilitySeen(Sema &S, SourceLocation loc) { |
3845 | FileID file = getNullabilityCompletenessCheckFileID(S, loc); |
3846 | if (file.isInvalid()) |
3847 | return; |
3848 | |
3849 | FileNullability &fileNullability = S.NullabilityMap[file]; |
3850 | if (fileNullability.SawTypeNullability) |
3851 | return; |
3852 | fileNullability.SawTypeNullability = true; |
3853 | |
3854 | // If we haven't seen any type nullability before, now we have. Retroactively |
3855 | // diagnose the first unannotated pointer, if there was one. |
3856 | if (fileNullability.PointerLoc.isInvalid()) |
3857 | return; |
3858 | |
3859 | auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); |
3860 | emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, |
3861 | fileNullability.PointerEndLoc); |
3862 | } |
3863 | |
3864 | /// Returns true if any of the declarator chunks before \p endIndex include a |
3865 | /// level of indirection: array, pointer, reference, or pointer-to-member. |
3866 | /// |
3867 | /// Because declarator chunks are stored in outer-to-inner order, testing |
3868 | /// every chunk before \p endIndex is testing all chunks that embed the current |
3869 | /// chunk as part of their type. |
3870 | /// |
3871 | /// It is legal to pass the result of Declarator::getNumTypeObjects() as the |
3872 | /// end index, in which case all chunks are tested. |
3873 | static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { |
3874 | unsigned i = endIndex; |
3875 | while (i != 0) { |
3876 | // Walk outwards along the declarator chunks. |
3877 | --i; |
3878 | const DeclaratorChunk &DC = D.getTypeObject(i); |
3879 | switch (DC.Kind) { |
3880 | case DeclaratorChunk::Paren: |
3881 | break; |
3882 | case DeclaratorChunk::Array: |
3883 | case DeclaratorChunk::Pointer: |
3884 | case DeclaratorChunk::Reference: |
3885 | case DeclaratorChunk::MemberPointer: |
3886 | return true; |
3887 | case DeclaratorChunk::Function: |
3888 | case DeclaratorChunk::BlockPointer: |
3889 | case DeclaratorChunk::Pipe: |
3890 | // These are invalid anyway, so just ignore. |
3891 | break; |
3892 | } |
3893 | } |
3894 | return false; |
3895 | } |
3896 | |
3897 | static bool IsNoDerefableChunk(DeclaratorChunk Chunk) { |
3898 | return (Chunk.Kind == DeclaratorChunk::Pointer || |
3899 | Chunk.Kind == DeclaratorChunk::Array); |
3900 | } |
3901 | |
3902 | template<typename AttrT> |
3903 | static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &Attr) { |
3904 | Attr.setUsedAsTypeAttr(); |
3905 | return ::new (Ctx) |
3906 | AttrT(Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex()); |
3907 | } |
3908 | |
3909 | static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, |
3910 | NullabilityKind NK) { |
3911 | switch (NK) { |
3912 | case NullabilityKind::NonNull: |
3913 | return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); |
3914 | |
3915 | case NullabilityKind::Nullable: |
3916 | return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); |
3917 | |
3918 | case NullabilityKind::Unspecified: |
3919 | return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); |
3920 | } |
3921 | llvm_unreachable("unknown NullabilityKind")::llvm::llvm_unreachable_internal("unknown NullabilityKind", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 3921); |
3922 | } |
3923 | |
3924 | static TypeSourceInfo * |
3925 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, |
3926 | QualType T, TypeSourceInfo *ReturnTypeInfo); |
3927 | |
3928 | static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, |
3929 | QualType declSpecType, |
3930 | TypeSourceInfo *TInfo) { |
3931 | // The TypeSourceInfo that this function returns will not be a null type. |
3932 | // If there is an error, this function will fill in a dummy type as fallback. |
3933 | QualType T = declSpecType; |
3934 | Declarator &D = state.getDeclarator(); |
3935 | Sema &S = state.getSema(); |
3936 | ASTContext &Context = S.Context; |
3937 | const LangOptions &LangOpts = S.getLangOpts(); |
3938 | |
3939 | // The name we're declaring, if any. |
3940 | DeclarationName Name; |
3941 | if (D.getIdentifier()) |
3942 | Name = D.getIdentifier(); |
3943 | |
3944 | // Does this declaration declare a typedef-name? |
3945 | bool IsTypedefName = |
3946 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || |
3947 | D.getContext() == DeclaratorContext::AliasDeclContext || |
3948 | D.getContext() == DeclaratorContext::AliasTemplateContext; |
3949 | |
3950 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? |
3951 | bool IsQualifiedFunction = T->isFunctionProtoType() && |
3952 | (!T->castAs<FunctionProtoType>()->getTypeQuals().empty() || |
3953 | T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); |
3954 | |
3955 | // If T is 'decltype(auto)', the only declarators we can have are parens |
3956 | // and at most one function declarator if this is a function declaration. |
3957 | // If T is a deduced class template specialization type, we can have no |
3958 | // declarator chunks at all. |
3959 | if (auto *DT = T->getAs<DeducedType>()) { |
3960 | const AutoType *AT = T->getAs<AutoType>(); |
3961 | bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); |
3962 | if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { |
3963 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { |
3964 | unsigned Index = E - I - 1; |
3965 | DeclaratorChunk &DeclChunk = D.getTypeObject(Index); |
3966 | unsigned DiagId = IsClassTemplateDeduction |
3967 | ? diag::err_deduced_class_template_compound_type |
3968 | : diag::err_decltype_auto_compound_type; |
3969 | unsigned DiagKind = 0; |
3970 | switch (DeclChunk.Kind) { |
3971 | case DeclaratorChunk::Paren: |
3972 | // FIXME: Rejecting this is a little silly. |
3973 | if (IsClassTemplateDeduction) { |
3974 | DiagKind = 4; |
3975 | break; |
3976 | } |
3977 | continue; |
3978 | case DeclaratorChunk::Function: { |
3979 | if (IsClassTemplateDeduction) { |
3980 | DiagKind = 3; |
3981 | break; |
3982 | } |
3983 | unsigned FnIndex; |
3984 | if (D.isFunctionDeclarationContext() && |
3985 | D.isFunctionDeclarator(FnIndex) && FnIndex == Index) |
3986 | continue; |
3987 | DiagId = diag::err_decltype_auto_function_declarator_not_declaration; |
3988 | break; |
3989 | } |
3990 | case DeclaratorChunk::Pointer: |
3991 | case DeclaratorChunk::BlockPointer: |
3992 | case DeclaratorChunk::MemberPointer: |
3993 | DiagKind = 0; |
3994 | break; |
3995 | case DeclaratorChunk::Reference: |
3996 | DiagKind = 1; |
3997 | break; |
3998 | case DeclaratorChunk::Array: |
3999 | DiagKind = 2; |
4000 | break; |
4001 | case DeclaratorChunk::Pipe: |
4002 | break; |
4003 | } |
4004 | |
4005 | S.Diag(DeclChunk.Loc, DiagId) << DiagKind; |
4006 | D.setInvalidType(true); |
4007 | break; |
4008 | } |
4009 | } |
4010 | } |
4011 | |
4012 | // Determine whether we should infer _Nonnull on pointer types. |
4013 | Optional<NullabilityKind> inferNullability; |
4014 | bool inferNullabilityCS = false; |
4015 | bool inferNullabilityInnerOnly = false; |
4016 | bool inferNullabilityInnerOnlyComplete = false; |
4017 | |
4018 | // Are we in an assume-nonnull region? |
4019 | bool inAssumeNonNullRegion = false; |
4020 | SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); |
4021 | if (assumeNonNullLoc.isValid()) { |
4022 | inAssumeNonNullRegion = true; |
4023 | recordNullabilitySeen(S, assumeNonNullLoc); |
4024 | } |
4025 | |
4026 | // Whether to complain about missing nullability specifiers or not. |
4027 | enum { |
4028 | /// Never complain. |
4029 | CAMN_No, |
4030 | /// Complain on the inner pointers (but not the outermost |
4031 | /// pointer). |
4032 | CAMN_InnerPointers, |
4033 | /// Complain about any pointers that don't have nullability |
4034 | /// specified or inferred. |
4035 | CAMN_Yes |
4036 | } complainAboutMissingNullability = CAMN_No; |
4037 | unsigned NumPointersRemaining = 0; |
4038 | auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; |
4039 | |
4040 | if (IsTypedefName) { |
4041 | // For typedefs, we do not infer any nullability (the default), |
4042 | // and we only complain about missing nullability specifiers on |
4043 | // inner pointers. |
4044 | complainAboutMissingNullability = CAMN_InnerPointers; |
4045 | |
4046 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && |
4047 | !T->getNullability(S.Context)) { |
4048 | // Note that we allow but don't require nullability on dependent types. |
4049 | ++NumPointersRemaining; |
4050 | } |
4051 | |
4052 | for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { |
4053 | DeclaratorChunk &chunk = D.getTypeObject(i); |
4054 | switch (chunk.Kind) { |
4055 | case DeclaratorChunk::Array: |
4056 | case DeclaratorChunk::Function: |
4057 | case DeclaratorChunk::Pipe: |
4058 | break; |
4059 | |
4060 | case DeclaratorChunk::BlockPointer: |
4061 | case DeclaratorChunk::MemberPointer: |
4062 | ++NumPointersRemaining; |
4063 | break; |
4064 | |
4065 | case DeclaratorChunk::Paren: |
4066 | case DeclaratorChunk::Reference: |
4067 | continue; |
4068 | |
4069 | case DeclaratorChunk::Pointer: |
4070 | ++NumPointersRemaining; |
4071 | continue; |
4072 | } |
4073 | } |
4074 | } else { |
4075 | bool isFunctionOrMethod = false; |
4076 | switch (auto context = state.getDeclarator().getContext()) { |
4077 | case DeclaratorContext::ObjCParameterContext: |
4078 | case DeclaratorContext::ObjCResultContext: |
4079 | case DeclaratorContext::PrototypeContext: |
4080 | case DeclaratorContext::TrailingReturnContext: |
4081 | case DeclaratorContext::TrailingReturnVarContext: |
4082 | isFunctionOrMethod = true; |
4083 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
4084 | |
4085 | case DeclaratorContext::MemberContext: |
4086 | if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { |
4087 | complainAboutMissingNullability = CAMN_No; |
4088 | break; |
4089 | } |
4090 | |
4091 | // Weak properties are inferred to be nullable. |
4092 | if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { |
4093 | inferNullability = NullabilityKind::Nullable; |
4094 | break; |
4095 | } |
4096 | |
4097 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
4098 | |
4099 | case DeclaratorContext::FileContext: |
4100 | case DeclaratorContext::KNRTypeListContext: { |
4101 | complainAboutMissingNullability = CAMN_Yes; |
4102 | |
4103 | // Nullability inference depends on the type and declarator. |
4104 | auto wrappingKind = PointerWrappingDeclaratorKind::None; |
4105 | switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { |
4106 | case PointerDeclaratorKind::NonPointer: |
4107 | case PointerDeclaratorKind::MultiLevelPointer: |
4108 | // Cannot infer nullability. |
4109 | break; |
4110 | |
4111 | case PointerDeclaratorKind::SingleLevelPointer: |
4112 | // Infer _Nonnull if we are in an assumes-nonnull region. |
4113 | if (inAssumeNonNullRegion) { |
4114 | complainAboutInferringWithinChunk = wrappingKind; |
4115 | inferNullability = NullabilityKind::NonNull; |
4116 | inferNullabilityCS = |
4117 | (context == DeclaratorContext::ObjCParameterContext || |
4118 | context == DeclaratorContext::ObjCResultContext); |
4119 | } |
4120 | break; |
4121 | |
4122 | case PointerDeclaratorKind::CFErrorRefPointer: |
4123 | case PointerDeclaratorKind::NSErrorPointerPointer: |
4124 | // Within a function or method signature, infer _Nullable at both |
4125 | // levels. |
4126 | if (isFunctionOrMethod && inAssumeNonNullRegion) |
4127 | inferNullability = NullabilityKind::Nullable; |
4128 | break; |
4129 | |
4130 | case PointerDeclaratorKind::MaybePointerToCFRef: |
4131 | if (isFunctionOrMethod) { |
4132 | // On pointer-to-pointer parameters marked cf_returns_retained or |
4133 | // cf_returns_not_retained, if the outer pointer is explicit then |
4134 | // infer the inner pointer as _Nullable. |
4135 | auto hasCFReturnsAttr = |
4136 | [](const ParsedAttributesView &AttrList) -> bool { |
4137 | return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || |
4138 | AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); |
4139 | }; |
4140 | if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { |
4141 | if (hasCFReturnsAttr(D.getAttributes()) || |
4142 | hasCFReturnsAttr(InnermostChunk->getAttrs()) || |
4143 | hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { |
4144 | inferNullability = NullabilityKind::Nullable; |
4145 | inferNullabilityInnerOnly = true; |
4146 | } |
4147 | } |
4148 | } |
4149 | break; |
4150 | } |
4151 | break; |
4152 | } |
4153 | |
4154 | case DeclaratorContext::ConversionIdContext: |
4155 | complainAboutMissingNullability = CAMN_Yes; |
4156 | break; |
4157 | |
4158 | case DeclaratorContext::AliasDeclContext: |
4159 | case DeclaratorContext::AliasTemplateContext: |
4160 | case DeclaratorContext::BlockContext: |
4161 | case DeclaratorContext::BlockLiteralContext: |
4162 | case DeclaratorContext::ConditionContext: |
4163 | case DeclaratorContext::CXXCatchContext: |
4164 | case DeclaratorContext::CXXNewContext: |
4165 | case DeclaratorContext::ForContext: |
4166 | case DeclaratorContext::InitStmtContext: |
4167 | case DeclaratorContext::LambdaExprContext: |
4168 | case DeclaratorContext::LambdaExprParameterContext: |
4169 | case DeclaratorContext::ObjCCatchContext: |
4170 | case DeclaratorContext::TemplateParamContext: |
4171 | case DeclaratorContext::TemplateArgContext: |
4172 | case DeclaratorContext::TemplateTypeArgContext: |
4173 | case DeclaratorContext::TypeNameContext: |
4174 | case DeclaratorContext::FunctionalCastContext: |
4175 | // Don't infer in these contexts. |
4176 | break; |
4177 | } |
4178 | } |
4179 | |
4180 | // Local function that returns true if its argument looks like a va_list. |
4181 | auto isVaList = [&S](QualType T) -> bool { |
4182 | auto *typedefTy = T->getAs<TypedefType>(); |
4183 | if (!typedefTy) |
4184 | return false; |
4185 | TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); |
4186 | do { |
4187 | if (typedefTy->getDecl() == vaListTypedef) |
4188 | return true; |
4189 | if (auto *name = typedefTy->getDecl()->getIdentifier()) |
4190 | if (name->isStr("va_list")) |
4191 | return true; |
4192 | typedefTy = typedefTy->desugar()->getAs<TypedefType>(); |
4193 | } while (typedefTy); |
4194 | return false; |
4195 | }; |
4196 | |
4197 | // Local function that checks the nullability for a given pointer declarator. |
4198 | // Returns true if _Nonnull was inferred. |
4199 | auto inferPointerNullability = |
4200 | [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, |
4201 | SourceLocation pointerEndLoc, |
4202 | ParsedAttributesView &attrs) -> ParsedAttr * { |
4203 | // We've seen a pointer. |
4204 | if (NumPointersRemaining > 0) |
4205 | --NumPointersRemaining; |
4206 | |
4207 | // If a nullability attribute is present, there's nothing to do. |
4208 | if (hasNullabilityAttr(attrs)) |
4209 | return nullptr; |
4210 | |
4211 | // If we're supposed to infer nullability, do so now. |
4212 | if (inferNullability && !inferNullabilityInnerOnlyComplete) { |
4213 | ParsedAttr::Syntax syntax = inferNullabilityCS |
4214 | ? ParsedAttr::AS_ContextSensitiveKeyword |
4215 | : ParsedAttr::AS_Keyword; |
4216 | ParsedAttr *nullabilityAttr = |
4217 | state.getDeclarator().getAttributePool().create( |
4218 | S.getNullabilityKeyword(*inferNullability), |
4219 | SourceRange(pointerLoc), nullptr, SourceLocation(), nullptr, 0, |
4220 | syntax); |
4221 | |
4222 | attrs.addAtEnd(nullabilityAttr); |
4223 | |
4224 | if (inferNullabilityCS) { |
4225 | state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() |
4226 | ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); |
4227 | } |
4228 | |
4229 | if (pointerLoc.isValid() && |
4230 | complainAboutInferringWithinChunk != |
4231 | PointerWrappingDeclaratorKind::None) { |
4232 | auto Diag = |
4233 | S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); |
4234 | Diag << static_cast<int>(complainAboutInferringWithinChunk); |
4235 | fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); |
4236 | } |
4237 | |
4238 | if (inferNullabilityInnerOnly) |
4239 | inferNullabilityInnerOnlyComplete = true; |
4240 | return nullabilityAttr; |
4241 | } |
4242 | |
4243 | // If we're supposed to complain about missing nullability, do so |
4244 | // now if it's truly missing. |
4245 | switch (complainAboutMissingNullability) { |
4246 | case CAMN_No: |
4247 | break; |
4248 | |
4249 | case CAMN_InnerPointers: |
4250 | if (NumPointersRemaining == 0) |
4251 | break; |
4252 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
4253 | |
4254 | case CAMN_Yes: |
4255 | checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); |
4256 | } |
4257 | return nullptr; |
4258 | }; |
4259 | |
4260 | // If the type itself could have nullability but does not, infer pointer |
4261 | // nullability and perform consistency checking. |
4262 | if (S.CodeSynthesisContexts.empty()) { |
4263 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && |
4264 | !T->getNullability(S.Context)) { |
4265 | if (isVaList(T)) { |
4266 | // Record that we've seen a pointer, but do nothing else. |
4267 | if (NumPointersRemaining > 0) |
4268 | --NumPointersRemaining; |
4269 | } else { |
4270 | SimplePointerKind pointerKind = SimplePointerKind::Pointer; |
4271 | if (T->isBlockPointerType()) |
4272 | pointerKind = SimplePointerKind::BlockPointer; |
4273 | else if (T->isMemberPointerType()) |
4274 | pointerKind = SimplePointerKind::MemberPointer; |
4275 | |
4276 | if (auto *attr = inferPointerNullability( |
4277 | pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), |
4278 | D.getDeclSpec().getEndLoc(), |
4279 | D.getMutableDeclSpec().getAttributes())) { |
4280 | T = state.getAttributedType( |
4281 | createNullabilityAttr(Context, *attr, *inferNullability), T, T); |
4282 | } |
4283 | } |
4284 | } |
4285 | |
4286 | if (complainAboutMissingNullability == CAMN_Yes && |
4287 | T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && |
4288 | D.isPrototypeContext() && |
4289 | !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { |
4290 | checkNullabilityConsistency(S, SimplePointerKind::Array, |
4291 | D.getDeclSpec().getTypeSpecTypeLoc()); |
4292 | } |
4293 | } |
4294 | |
4295 | bool ExpectNoDerefChunk = |
4296 | state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); |
4297 | |
4298 | // Walk the DeclTypeInfo, building the recursive type as we go. |
4299 | // DeclTypeInfos are ordered from the identifier out, which is |
4300 | // opposite of what we want :). |
4301 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { |
4302 | unsigned chunkIndex = e - i - 1; |
4303 | state.setCurrentChunkIndex(chunkIndex); |
4304 | DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); |
4305 | IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; |
4306 | switch (DeclType.Kind) { |
4307 | case DeclaratorChunk::Paren: |
4308 | if (i == 0) |
4309 | warnAboutRedundantParens(S, D, T); |
4310 | T = S.BuildParenType(T); |
4311 | break; |
4312 | case DeclaratorChunk::BlockPointer: |
4313 | // If blocks are disabled, emit an error. |
4314 | if (!LangOpts.Blocks) |
4315 | S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; |
4316 | |
4317 | // Handle pointer nullability. |
4318 | inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, |
4319 | DeclType.EndLoc, DeclType.getAttrs()); |
4320 | |
4321 | T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); |
4322 | if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { |
4323 | // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly |
4324 | // qualified with const. |
4325 | if (LangOpts.OpenCL) |
4326 | DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; |
4327 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); |
4328 | } |
4329 | break; |
4330 | case DeclaratorChunk::Pointer: |
4331 | // Verify that we're not building a pointer to pointer to function with |
4332 | // exception specification. |
4333 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { |
4334 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); |
4335 | D.setInvalidType(true); |
4336 | // Build the type anyway. |
4337 | } |
4338 | |
4339 | // Handle pointer nullability |
4340 | inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, |
4341 | DeclType.EndLoc, DeclType.getAttrs()); |
4342 | |
4343 | if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { |
4344 | T = Context.getObjCObjectPointerType(T); |
4345 | if (DeclType.Ptr.TypeQuals) |
4346 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); |
4347 | break; |
4348 | } |
4349 | |
4350 | // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. |
4351 | // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. |
4352 | // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. |
4353 | if (LangOpts.OpenCL) { |
4354 | if (T->isImageType() || T->isSamplerT() || T->isPipeType() || |
4355 | T->isBlockPointerType()) { |
4356 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; |
4357 | D.setInvalidType(true); |
4358 | } |
4359 | } |
4360 | |
4361 | T = S.BuildPointerType(T, DeclType.Loc, Name); |
4362 | if (DeclType.Ptr.TypeQuals) |
4363 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); |
4364 | break; |
4365 | case DeclaratorChunk::Reference: { |
4366 | // Verify that we're not building a reference to pointer to function with |
4367 | // exception specification. |
4368 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { |
4369 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); |
4370 | D.setInvalidType(true); |
4371 | // Build the type anyway. |
4372 | } |
4373 | T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); |
4374 | |
4375 | if (DeclType.Ref.HasRestrict) |
4376 | T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); |
4377 | break; |
4378 | } |
4379 | case DeclaratorChunk::Array: { |
4380 | // Verify that we're not building an array of pointers to function with |
4381 | // exception specification. |
4382 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { |
4383 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); |
4384 | D.setInvalidType(true); |
4385 | // Build the type anyway. |
4386 | } |
4387 | DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; |
4388 | Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); |
4389 | ArrayType::ArraySizeModifier ASM; |
4390 | if (ATI.isStar) |
4391 | ASM = ArrayType::Star; |
4392 | else if (ATI.hasStatic) |
4393 | ASM = ArrayType::Static; |
4394 | else |
4395 | ASM = ArrayType::Normal; |
4396 | if (ASM == ArrayType::Star && !D.isPrototypeContext()) { |
4397 | // FIXME: This check isn't quite right: it allows star in prototypes |
4398 | // for function definitions, and disallows some edge cases detailed |
4399 | // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html |
4400 | S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); |
4401 | ASM = ArrayType::Normal; |
4402 | D.setInvalidType(true); |
4403 | } |
4404 | |
4405 | // C99 6.7.5.2p1: The optional type qualifiers and the keyword static |
4406 | // shall appear only in a declaration of a function parameter with an |
4407 | // array type, ... |
4408 | if (ASM == ArrayType::Static || ATI.TypeQuals) { |
4409 | if (!(D.isPrototypeContext() || |
4410 | D.getContext() == DeclaratorContext::KNRTypeListContext)) { |
4411 | S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << |
4412 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); |
4413 | // Remove the 'static' and the type qualifiers. |
4414 | if (ASM == ArrayType::Static) |
4415 | ASM = ArrayType::Normal; |
4416 | ATI.TypeQuals = 0; |
4417 | D.setInvalidType(true); |
4418 | } |
4419 | |
4420 | // C99 6.7.5.2p1: ... and then only in the outermost array type |
4421 | // derivation. |
4422 | if (hasOuterPointerLikeChunk(D, chunkIndex)) { |
4423 | S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << |
4424 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); |
4425 | if (ASM == ArrayType::Static) |
4426 | ASM = ArrayType::Normal; |
4427 | ATI.TypeQuals = 0; |
4428 | D.setInvalidType(true); |
4429 | } |
4430 | } |
4431 | const AutoType *AT = T->getContainedAutoType(); |
4432 | // Allow arrays of auto if we are a generic lambda parameter. |
4433 | // i.e. [](auto (&array)[5]) { return array[0]; }; OK |
4434 | if (AT && |
4435 | D.getContext() != DeclaratorContext::LambdaExprParameterContext) { |
4436 | // We've already diagnosed this for decltype(auto). |
4437 | if (!AT->isDecltypeAuto()) |
4438 | S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) |
4439 | << getPrintableNameForEntity(Name) << T; |
4440 | T = QualType(); |
4441 | break; |
4442 | } |
4443 | |
4444 | // Array parameters can be marked nullable as well, although it's not |
4445 | // necessary if they're marked 'static'. |
4446 | if (complainAboutMissingNullability == CAMN_Yes && |
4447 | !hasNullabilityAttr(DeclType.getAttrs()) && |
4448 | ASM != ArrayType::Static && |
4449 | D.isPrototypeContext() && |
4450 | !hasOuterPointerLikeChunk(D, chunkIndex)) { |
4451 | checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); |
4452 | } |
4453 | |
4454 | T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, |
4455 | SourceRange(DeclType.Loc, DeclType.EndLoc), Name); |
4456 | break; |
4457 | } |
4458 | case DeclaratorChunk::Function: { |
4459 | // If the function declarator has a prototype (i.e. it is not () and |
4460 | // does not have a K&R-style identifier list), then the arguments are part |
4461 | // of the type, otherwise the argument list is (). |
4462 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; |
4463 | IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); |
4464 | |
4465 | // Check for auto functions and trailing return type and adjust the |
4466 | // return type accordingly. |
4467 | if (!D.isInvalidType()) { |
4468 | // trailing-return-type is only required if we're declaring a function, |
4469 | // and not, for instance, a pointer to a function. |
4470 | if (D.getDeclSpec().hasAutoTypeSpec() && |
4471 | !FTI.hasTrailingReturnType() && chunkIndex == 0) { |
4472 | if (!S.getLangOpts().CPlusPlus14) { |
4473 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), |
4474 | D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto |
4475 | ? diag::err_auto_missing_trailing_return |
4476 | : diag::err_deduced_return_type); |
4477 | T = Context.IntTy; |
4478 | D.setInvalidType(true); |
4479 | } else { |
4480 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), |
4481 | diag::warn_cxx11_compat_deduced_return_type); |
4482 | } |
4483 | } else if (FTI.hasTrailingReturnType()) { |
4484 | // T must be exactly 'auto' at this point. See CWG issue 681. |
4485 | if (isa<ParenType>(T)) { |
4486 | S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) |
4487 | << T << D.getSourceRange(); |
4488 | D.setInvalidType(true); |
4489 | } else if (D.getName().getKind() == |
4490 | UnqualifiedIdKind::IK_DeductionGuideName) { |
4491 | if (T != Context.DependentTy) { |
4492 | S.Diag(D.getDeclSpec().getBeginLoc(), |
4493 | diag::err_deduction_guide_with_complex_decl) |
4494 | << D.getSourceRange(); |
4495 | D.setInvalidType(true); |
4496 | } |
4497 | } else if (D.getContext() != DeclaratorContext::LambdaExprContext && |
4498 | (T.hasQualifiers() || !isa<AutoType>(T) || |
4499 | cast<AutoType>(T)->getKeyword() != |
4500 | AutoTypeKeyword::Auto)) { |
4501 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), |
4502 | diag::err_trailing_return_without_auto) |
4503 | << T << D.getDeclSpec().getSourceRange(); |
4504 | D.setInvalidType(true); |
4505 | } |
4506 | T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); |
4507 | if (T.isNull()) { |
4508 | // An error occurred parsing the trailing return type. |
4509 | T = Context.IntTy; |
4510 | D.setInvalidType(true); |
4511 | } |
4512 | } else { |
4513 | // This function type is not the type of the entity being declared, |
4514 | // so checking the 'auto' is not the responsibility of this chunk. |
4515 | } |
4516 | } |
4517 | |
4518 | // C99 6.7.5.3p1: The return type may not be a function or array type. |
4519 | // For conversion functions, we'll diagnose this particular error later. |
4520 | if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && |
4521 | (D.getName().getKind() != |
4522 | UnqualifiedIdKind::IK_ConversionFunctionId)) { |
4523 | unsigned diagID = diag::err_func_returning_array_function; |
4524 | // Last processing chunk in block context means this function chunk |
4525 | // represents the block. |
4526 | if (chunkIndex == 0 && |
4527 | D.getContext() == DeclaratorContext::BlockLiteralContext) |
4528 | diagID = diag::err_block_returning_array_function; |
4529 | S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; |
4530 | T = Context.IntTy; |
4531 | D.setInvalidType(true); |
4532 | } |
4533 | |
4534 | // Do not allow returning half FP value. |
4535 | // FIXME: This really should be in BuildFunctionType. |
4536 | if (T->isHalfType()) { |
4537 | if (S.getLangOpts().OpenCL) { |
4538 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { |
4539 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) |
4540 | << T << 0 /*pointer hint*/; |
4541 | D.setInvalidType(true); |
4542 | } |
4543 | } else if (!S.getLangOpts().HalfArgsAndReturns) { |
4544 | S.Diag(D.getIdentifierLoc(), |
4545 | diag::err_parameters_retval_cannot_have_fp16_type) << 1; |
4546 | D.setInvalidType(true); |
4547 | } |
4548 | } |
4549 | |
4550 | if (LangOpts.OpenCL) { |
4551 | // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a |
4552 | // function. |
4553 | if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || |
4554 | T->isPipeType()) { |
4555 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) |
4556 | << T << 1 /*hint off*/; |
4557 | D.setInvalidType(true); |
4558 | } |
4559 | // OpenCL doesn't support variadic functions and blocks |
4560 | // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. |
4561 | // We also allow here any toolchain reserved identifiers. |
4562 | if (FTI.isVariadic && |
4563 | !(D.getIdentifier() && |
4564 | ((D.getIdentifier()->getName() == "printf" && |
4565 | LangOpts.OpenCLVersion >= 120) || |
4566 | D.getIdentifier()->getName().startswith("__")))) { |
4567 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); |
4568 | D.setInvalidType(true); |
4569 | } |
4570 | } |
4571 | |
4572 | // Methods cannot return interface types. All ObjC objects are |
4573 | // passed by reference. |
4574 | if (T->isObjCObjectType()) { |
4575 | SourceLocation DiagLoc, FixitLoc; |
4576 | if (TInfo) { |
4577 | DiagLoc = TInfo->getTypeLoc().getBeginLoc(); |
4578 | FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc()); |
4579 | } else { |
4580 | DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); |
4581 | FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc()); |
4582 | } |
4583 | S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) |
4584 | << 0 << T |
4585 | << FixItHint::CreateInsertion(FixitLoc, "*"); |
4586 | |
4587 | T = Context.getObjCObjectPointerType(T); |
4588 | if (TInfo) { |
4589 | TypeLocBuilder TLB; |
4590 | TLB.pushFullCopy(TInfo->getTypeLoc()); |
4591 | ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); |
4592 | TLoc.setStarLoc(FixitLoc); |
4593 | TInfo = TLB.getTypeSourceInfo(Context, T); |
4594 | } |
4595 | |
4596 | D.setInvalidType(true); |
4597 | } |
4598 | |
4599 | // cv-qualifiers on return types are pointless except when the type is a |
4600 | // class type in C++. |
4601 | if ((T.getCVRQualifiers() || T->isAtomicType()) && |
4602 | !(S.getLangOpts().CPlusPlus && |
4603 | (T->isDependentType() || T->isRecordType()))) { |
4604 | if (T->isVoidType() && !S.getLangOpts().CPlusPlus && |
4605 | D.getFunctionDefinitionKind() == FDK_Definition) { |
4606 | // [6.9.1/3] qualified void return is invalid on a C |
4607 | // function definition. Apparently ok on declarations and |
4608 | // in C++ though (!) |
4609 | S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; |
4610 | } else |
4611 | diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); |
4612 | } |
4613 | |
4614 | // Objective-C ARC ownership qualifiers are ignored on the function |
4615 | // return type (by type canonicalization). Complain if this attribute |
4616 | // was written here. |
4617 | if (T.getQualifiers().hasObjCLifetime()) { |
4618 | SourceLocation AttrLoc; |
4619 | if (chunkIndex + 1 < D.getNumTypeObjects()) { |
4620 | DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); |
4621 | for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { |
4622 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { |
4623 | AttrLoc = AL.getLoc(); |
4624 | break; |
4625 | } |
4626 | } |
4627 | } |
4628 | if (AttrLoc.isInvalid()) { |
4629 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { |
4630 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { |
4631 | AttrLoc = AL.getLoc(); |
4632 | break; |
4633 | } |
4634 | } |
4635 | } |
4636 | |
4637 | if (AttrLoc.isValid()) { |
4638 | // The ownership attributes are almost always written via |
4639 | // the predefined |
4640 | // __strong/__weak/__autoreleasing/__unsafe_unretained. |
4641 | if (AttrLoc.isMacroID()) |
4642 | AttrLoc = |
4643 | S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); |
4644 | |
4645 | S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) |
4646 | << T.getQualifiers().getObjCLifetime(); |
4647 | } |
4648 | } |
4649 | |
4650 | if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { |
4651 | // C++ [dcl.fct]p6: |
4652 | // Types shall not be defined in return or parameter types. |
4653 | TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); |
4654 | S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) |
4655 | << Context.getTypeDeclType(Tag); |
4656 | } |
4657 | |
4658 | // Exception specs are not allowed in typedefs. Complain, but add it |
4659 | // anyway. |
4660 | if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) |
4661 | S.Diag(FTI.getExceptionSpecLocBeg(), |
4662 | diag::err_exception_spec_in_typedef) |
4663 | << (D.getContext() == DeclaratorContext::AliasDeclContext || |
4664 | D.getContext() == DeclaratorContext::AliasTemplateContext); |
4665 | |
4666 | // If we see "T var();" or "T var(T());" at block scope, it is probably |
4667 | // an attempt to initialize a variable, not a function declaration. |
4668 | if (FTI.isAmbiguous) |
4669 | warnAboutAmbiguousFunction(S, D, DeclType, T); |
4670 | |
4671 | FunctionType::ExtInfo EI( |
4672 | getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); |
4673 | |
4674 | if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus |
4675 | && !LangOpts.OpenCL) { |
4676 | // Simple void foo(), where the incoming T is the result type. |
4677 | T = Context.getFunctionNoProtoType(T, EI); |
4678 | } else { |
4679 | // We allow a zero-parameter variadic function in C if the |
4680 | // function is marked with the "overloadable" attribute. Scan |
4681 | // for this attribute now. |
4682 | if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) |
4683 | if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable)) |
4684 | S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); |
4685 | |
4686 | if (FTI.NumParams && FTI.Params[0].Param == nullptr) { |
4687 | // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function |
4688 | // definition. |
4689 | S.Diag(FTI.Params[0].IdentLoc, |
4690 | diag::err_ident_list_in_fn_declaration); |
4691 | D.setInvalidType(true); |
4692 | // Recover by creating a K&R-style function type. |
4693 | T = Context.getFunctionNoProtoType(T, EI); |
4694 | break; |
4695 | } |
4696 | |
4697 | FunctionProtoType::ExtProtoInfo EPI; |
4698 | EPI.ExtInfo = EI; |
4699 | EPI.Variadic = FTI.isVariadic; |
4700 | EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); |
4701 | EPI.TypeQuals.addCVRUQualifiers(FTI.TypeQuals); |
4702 | EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None |
4703 | : FTI.RefQualifierIsLValueRef? RQ_LValue |
4704 | : RQ_RValue; |
4705 | |
4706 | // Otherwise, we have a function with a parameter list that is |
4707 | // potentially variadic. |
4708 | SmallVector<QualType, 16> ParamTys; |
4709 | ParamTys.reserve(FTI.NumParams); |
4710 | |
4711 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> |
4712 | ExtParameterInfos(FTI.NumParams); |
4713 | bool HasAnyInterestingExtParameterInfos = false; |
4714 | |
4715 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { |
4716 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); |
4717 | QualType ParamTy = Param->getType(); |
4718 | assert(!ParamTy.isNull() && "Couldn't parse type?")((!ParamTy.isNull() && "Couldn't parse type?") ? static_cast <void> (0) : __assert_fail ("!ParamTy.isNull() && \"Couldn't parse type?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 4718, __PRETTY_FUNCTION__)); |
4719 | |
4720 | // Look for 'void'. void is allowed only as a single parameter to a |
4721 | // function with no other parameters (C99 6.7.5.3p10). We record |
4722 | // int(void) as a FunctionProtoType with an empty parameter list. |
4723 | if (ParamTy->isVoidType()) { |
4724 | // If this is something like 'float(int, void)', reject it. 'void' |
4725 | // is an incomplete type (C99 6.2.5p19) and function decls cannot |
4726 | // have parameters of incomplete type. |
4727 | if (FTI.NumParams != 1 || FTI.isVariadic) { |
4728 | S.Diag(DeclType.Loc, diag::err_void_only_param); |
4729 | ParamTy = Context.IntTy; |
4730 | Param->setType(ParamTy); |
4731 | } else if (FTI.Params[i].Ident) { |
4732 | // Reject, but continue to parse 'int(void abc)'. |
4733 | S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); |
4734 | ParamTy = Context.IntTy; |
4735 | Param->setType(ParamTy); |
4736 | } else { |
4737 | // Reject, but continue to parse 'float(const void)'. |
4738 | if (ParamTy.hasQualifiers()) |
4739 | S.Diag(DeclType.Loc, diag::err_void_param_qualified); |
4740 | |
4741 | // Do not add 'void' to the list. |
4742 | break; |
4743 | } |
4744 | } else if (ParamTy->isHalfType()) { |
4745 | // Disallow half FP parameters. |
4746 | // FIXME: This really should be in BuildFunctionType. |
4747 | if (S.getLangOpts().OpenCL) { |
4748 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { |
4749 | S.Diag(Param->getLocation(), |
4750 | diag::err_opencl_half_param) << ParamTy; |
4751 | D.setInvalidType(); |
4752 | Param->setInvalidDecl(); |
4753 | } |
4754 | } else if (!S.getLangOpts().HalfArgsAndReturns) { |
4755 | S.Diag(Param->getLocation(), |
4756 | diag::err_parameters_retval_cannot_have_fp16_type) << 0; |
4757 | D.setInvalidType(); |
4758 | } |
4759 | } else if (!FTI.hasPrototype) { |
4760 | if (ParamTy->isPromotableIntegerType()) { |
4761 | ParamTy = Context.getPromotedIntegerType(ParamTy); |
4762 | Param->setKNRPromoted(true); |
4763 | } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { |
4764 | if (BTy->getKind() == BuiltinType::Float) { |
4765 | ParamTy = Context.DoubleTy; |
4766 | Param->setKNRPromoted(true); |
4767 | } |
4768 | } |
4769 | } |
4770 | |
4771 | if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { |
4772 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); |
4773 | HasAnyInterestingExtParameterInfos = true; |
4774 | } |
4775 | |
4776 | if (auto attr = Param->getAttr<ParameterABIAttr>()) { |
4777 | ExtParameterInfos[i] = |
4778 | ExtParameterInfos[i].withABI(attr->getABI()); |
4779 | HasAnyInterestingExtParameterInfos = true; |
4780 | } |
4781 | |
4782 | if (Param->hasAttr<PassObjectSizeAttr>()) { |
4783 | ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); |
4784 | HasAnyInterestingExtParameterInfos = true; |
4785 | } |
4786 | |
4787 | if (Param->hasAttr<NoEscapeAttr>()) { |
4788 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); |
4789 | HasAnyInterestingExtParameterInfos = true; |
4790 | } |
4791 | |
4792 | ParamTys.push_back(ParamTy); |
4793 | } |
4794 | |
4795 | if (HasAnyInterestingExtParameterInfos) { |
4796 | EPI.ExtParameterInfos = ExtParameterInfos.data(); |
4797 | checkExtParameterInfos(S, ParamTys, EPI, |
4798 | [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); |
4799 | } |
4800 | |
4801 | SmallVector<QualType, 4> Exceptions; |
4802 | SmallVector<ParsedType, 2> DynamicExceptions; |
4803 | SmallVector<SourceRange, 2> DynamicExceptionRanges; |
4804 | Expr *NoexceptExpr = nullptr; |
4805 | |
4806 | if (FTI.getExceptionSpecType() == EST_Dynamic) { |
4807 | // FIXME: It's rather inefficient to have to split into two vectors |
4808 | // here. |
4809 | unsigned N = FTI.getNumExceptions(); |
4810 | DynamicExceptions.reserve(N); |
4811 | DynamicExceptionRanges.reserve(N); |
4812 | for (unsigned I = 0; I != N; ++I) { |
4813 | DynamicExceptions.push_back(FTI.Exceptions[I].Ty); |
4814 | DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); |
4815 | } |
4816 | } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { |
4817 | NoexceptExpr = FTI.NoexceptExpr; |
4818 | } |
4819 | |
4820 | S.checkExceptionSpecification(D.isFunctionDeclarationContext(), |
4821 | FTI.getExceptionSpecType(), |
4822 | DynamicExceptions, |
4823 | DynamicExceptionRanges, |
4824 | NoexceptExpr, |
4825 | Exceptions, |
4826 | EPI.ExceptionSpec); |
4827 | |
4828 | const auto &Spec = D.getCXXScopeSpec(); |
4829 | // OpenCLCPlusPlus: A class member function has an address space. |
4830 | if (state.getSema().getLangOpts().OpenCLCPlusPlus && |
4831 | ((!Spec.isEmpty() && |
4832 | Spec.getScopeRep()->getKind() == NestedNameSpecifier::TypeSpec) || |
4833 | state.getDeclarator().getContext() == |
4834 | DeclaratorContext::MemberContext)) { |
4835 | LangAS CurAS = EPI.TypeQuals.getAddressSpace(); |
4836 | // If a class member function's address space is not set, set it to |
4837 | // __generic. |
4838 | LangAS AS = |
4839 | (CurAS == LangAS::Default ? LangAS::opencl_generic : CurAS); |
4840 | EPI.TypeQuals.addAddressSpace(AS); |
4841 | T = Context.getFunctionType(T, ParamTys, EPI); |
4842 | T = state.getSema().Context.getAddrSpaceQualType(T, AS); |
4843 | } else { |
4844 | T = Context.getFunctionType(T, ParamTys, EPI); |
4845 | } |
4846 | } |
4847 | break; |
4848 | } |
4849 | case DeclaratorChunk::MemberPointer: { |
4850 | // The scope spec must refer to a class, or be dependent. |
4851 | CXXScopeSpec &SS = DeclType.Mem.Scope(); |
4852 | QualType ClsType; |
4853 | |
4854 | // Handle pointer nullability. |
4855 | inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, |
4856 | DeclType.EndLoc, DeclType.getAttrs()); |
4857 | |
4858 | if (SS.isInvalid()) { |
4859 | // Avoid emitting extra errors if we already errored on the scope. |
4860 | D.setInvalidType(true); |
4861 | } else if (S.isDependentScopeSpecifier(SS) || |
4862 | dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { |
4863 | NestedNameSpecifier *NNS = SS.getScopeRep(); |
4864 | NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); |
4865 | switch (NNS->getKind()) { |
4866 | case NestedNameSpecifier::Identifier: |
4867 | ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, |
4868 | NNS->getAsIdentifier()); |
4869 | break; |
4870 | |
4871 | case NestedNameSpecifier::Namespace: |
4872 | case NestedNameSpecifier::NamespaceAlias: |
4873 | case NestedNameSpecifier::Global: |
4874 | case NestedNameSpecifier::Super: |
4875 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 4875); |
4876 | |
4877 | case NestedNameSpecifier::TypeSpec: |
4878 | case NestedNameSpecifier::TypeSpecWithTemplate: |
4879 | ClsType = QualType(NNS->getAsType(), 0); |
4880 | // Note: if the NNS has a prefix and ClsType is a nondependent |
4881 | // TemplateSpecializationType, then the NNS prefix is NOT included |
4882 | // in ClsType; hence we wrap ClsType into an ElaboratedType. |
4883 | // NOTE: in particular, no wrap occurs if ClsType already is an |
4884 | // Elaborated, DependentName, or DependentTemplateSpecialization. |
4885 | if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) |
4886 | ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); |
4887 | break; |
4888 | } |
4889 | } else { |
4890 | S.Diag(DeclType.Mem.Scope().getBeginLoc(), |
4891 | diag::err_illegal_decl_mempointer_in_nonclass) |
4892 | << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") |
4893 | << DeclType.Mem.Scope().getRange(); |
4894 | D.setInvalidType(true); |
4895 | } |
4896 | |
4897 | if (!ClsType.isNull()) |
4898 | T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, |
4899 | D.getIdentifier()); |
4900 | if (T.isNull()) { |
4901 | T = Context.IntTy; |
4902 | D.setInvalidType(true); |
4903 | } else if (DeclType.Mem.TypeQuals) { |
4904 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); |
4905 | } |
4906 | break; |
4907 | } |
4908 | |
4909 | case DeclaratorChunk::Pipe: { |
4910 | T = S.BuildReadPipeType(T, DeclType.Loc); |
4911 | processTypeAttrs(state, T, TAL_DeclSpec, |
4912 | D.getMutableDeclSpec().getAttributes()); |
4913 | break; |
4914 | } |
4915 | } |
4916 | |
4917 | if (T.isNull()) { |
4918 | D.setInvalidType(true); |
4919 | T = Context.IntTy; |
4920 | } |
4921 | |
4922 | // See if there are any attributes on this declarator chunk. |
4923 | processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs()); |
4924 | |
4925 | if (DeclType.Kind != DeclaratorChunk::Paren) { |
4926 | if (ExpectNoDerefChunk) { |
4927 | if (!IsNoDerefableChunk(DeclType)) |
4928 | S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); |
4929 | ExpectNoDerefChunk = false; |
Value stored to 'ExpectNoDerefChunk' is never read | |
4930 | } |
4931 | |
4932 | ExpectNoDerefChunk = state.didParseNoDeref(); |
4933 | } |
4934 | } |
4935 | |
4936 | if (ExpectNoDerefChunk) |
4937 | S.Diag(state.getDeclarator().getBeginLoc(), |
4938 | diag::warn_noderef_on_non_pointer_or_array); |
4939 | |
4940 | // GNU warning -Wstrict-prototypes |
4941 | // Warn if a function declaration is without a prototype. |
4942 | // This warning is issued for all kinds of unprototyped function |
4943 | // declarations (i.e. function type typedef, function pointer etc.) |
4944 | // C99 6.7.5.3p14: |
4945 | // The empty list in a function declarator that is not part of a definition |
4946 | // of that function specifies that no information about the number or types |
4947 | // of the parameters is supplied. |
4948 | if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) { |
4949 | bool IsBlock = false; |
4950 | for (const DeclaratorChunk &DeclType : D.type_objects()) { |
4951 | switch (DeclType.Kind) { |
4952 | case DeclaratorChunk::BlockPointer: |
4953 | IsBlock = true; |
4954 | break; |
4955 | case DeclaratorChunk::Function: { |
4956 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; |
4957 | if (FTI.NumParams == 0 && !FTI.isVariadic) |
4958 | S.Diag(DeclType.Loc, diag::warn_strict_prototypes) |
4959 | << IsBlock |
4960 | << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); |
4961 | IsBlock = false; |
4962 | break; |
4963 | } |
4964 | default: |
4965 | break; |
4966 | } |
4967 | } |
4968 | } |
4969 | |
4970 | assert(!T.isNull() && "T must not be null after this point")((!T.isNull() && "T must not be null after this point" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"T must not be null after this point\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 4970, __PRETTY_FUNCTION__)); |
4971 | |
4972 | if (LangOpts.CPlusPlus && T->isFunctionType()) { |
4973 | const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); |
4974 | assert(FnTy && "Why oh why is there not a FunctionProtoType here?")((FnTy && "Why oh why is there not a FunctionProtoType here?" ) ? static_cast<void> (0) : __assert_fail ("FnTy && \"Why oh why is there not a FunctionProtoType here?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 4974, __PRETTY_FUNCTION__)); |
4975 | |
4976 | // C++ 8.3.5p4: |
4977 | // A cv-qualifier-seq shall only be part of the function type |
4978 | // for a nonstatic member function, the function type to which a pointer |
4979 | // to member refers, or the top-level function type of a function typedef |
4980 | // declaration. |
4981 | // |
4982 | // Core issue 547 also allows cv-qualifiers on function types that are |
4983 | // top-level template type arguments. |
4984 | enum { NonMember, Member, DeductionGuide } Kind = NonMember; |
4985 | if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) |
4986 | Kind = DeductionGuide; |
4987 | else if (!D.getCXXScopeSpec().isSet()) { |
4988 | if ((D.getContext() == DeclaratorContext::MemberContext || |
4989 | D.getContext() == DeclaratorContext::LambdaExprContext) && |
4990 | !D.getDeclSpec().isFriendSpecified()) |
4991 | Kind = Member; |
4992 | } else { |
4993 | DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); |
4994 | if (!DC || DC->isRecord()) |
4995 | Kind = Member; |
4996 | } |
4997 | |
4998 | // C++11 [dcl.fct]p6 (w/DR1417): |
4999 | // An attempt to specify a function type with a cv-qualifier-seq or a |
5000 | // ref-qualifier (including by typedef-name) is ill-formed unless it is: |
5001 | // - the function type for a non-static member function, |
5002 | // - the function type to which a pointer to member refers, |
5003 | // - the top-level function type of a function typedef declaration or |
5004 | // alias-declaration, |
5005 | // - the type-id in the default argument of a type-parameter, or |
5006 | // - the type-id of a template-argument for a type-parameter |
5007 | // |
5008 | // FIXME: Checking this here is insufficient. We accept-invalid on: |
5009 | // |
5010 | // template<typename T> struct S { void f(T); }; |
5011 | // S<int() const> s; |
5012 | // |
5013 | // ... for instance. |
5014 | if (IsQualifiedFunction && |
5015 | !(Kind == Member && |
5016 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && |
5017 | !IsTypedefName && |
5018 | D.getContext() != DeclaratorContext::TemplateArgContext && |
5019 | D.getContext() != DeclaratorContext::TemplateTypeArgContext) { |
5020 | SourceLocation Loc = D.getBeginLoc(); |
5021 | SourceRange RemovalRange; |
5022 | unsigned I; |
5023 | if (D.isFunctionDeclarator(I)) { |
5024 | SmallVector<SourceLocation, 4> RemovalLocs; |
5025 | const DeclaratorChunk &Chunk = D.getTypeObject(I); |
5026 | assert(Chunk.Kind == DeclaratorChunk::Function)((Chunk.Kind == DeclaratorChunk::Function) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5026, __PRETTY_FUNCTION__)); |
5027 | if (Chunk.Fun.hasRefQualifier()) |
5028 | RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); |
5029 | if (Chunk.Fun.TypeQuals & Qualifiers::Const) |
5030 | RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); |
5031 | if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) |
5032 | RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); |
5033 | if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) |
5034 | RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); |
5035 | if (!RemovalLocs.empty()) { |
5036 | llvm::sort(RemovalLocs, |
5037 | BeforeThanCompare<SourceLocation>(S.getSourceManager())); |
5038 | RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); |
5039 | Loc = RemovalLocs.front(); |
5040 | } |
5041 | } |
5042 | |
5043 | S.Diag(Loc, diag::err_invalid_qualified_function_type) |
5044 | << Kind << D.isFunctionDeclarator() << T |
5045 | << getFunctionQualifiersAsString(FnTy) |
5046 | << FixItHint::CreateRemoval(RemovalRange); |
5047 | |
5048 | // Strip the cv-qualifiers and ref-qualifiers from the type. |
5049 | FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); |
5050 | EPI.TypeQuals.removeCVRQualifiers(); |
5051 | EPI.RefQualifier = RQ_None; |
5052 | |
5053 | T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), |
5054 | EPI); |
5055 | // Rebuild any parens around the identifier in the function type. |
5056 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { |
5057 | if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) |
5058 | break; |
5059 | T = S.BuildParenType(T); |
5060 | } |
5061 | } |
5062 | } |
5063 | |
5064 | // Apply any undistributed attributes from the declarator. |
5065 | processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); |
5066 | |
5067 | // Diagnose any ignored type attributes. |
5068 | state.diagnoseIgnoredTypeAttrs(T); |
5069 | |
5070 | // C++0x [dcl.constexpr]p9: |
5071 | // A constexpr specifier used in an object declaration declares the object |
5072 | // as const. |
5073 | if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { |
5074 | T.addConst(); |
5075 | } |
5076 | |
5077 | // If there was an ellipsis in the declarator, the declaration declares a |
5078 | // parameter pack whose type may be a pack expansion type. |
5079 | if (D.hasEllipsis()) { |
5080 | // C++0x [dcl.fct]p13: |
5081 | // A declarator-id or abstract-declarator containing an ellipsis shall |
5082 | // only be used in a parameter-declaration. Such a parameter-declaration |
5083 | // is a parameter pack (14.5.3). [...] |
5084 | switch (D.getContext()) { |
5085 | case DeclaratorContext::PrototypeContext: |
5086 | case DeclaratorContext::LambdaExprParameterContext: |
5087 | // C++0x [dcl.fct]p13: |
5088 | // [...] When it is part of a parameter-declaration-clause, the |
5089 | // parameter pack is a function parameter pack (14.5.3). The type T |
5090 | // of the declarator-id of the function parameter pack shall contain |
5091 | // a template parameter pack; each template parameter pack in T is |
5092 | // expanded by the function parameter pack. |
5093 | // |
5094 | // We represent function parameter packs as function parameters whose |
5095 | // type is a pack expansion. |
5096 | if (!T->containsUnexpandedParameterPack()) { |
5097 | S.Diag(D.getEllipsisLoc(), |
5098 | diag::err_function_parameter_pack_without_parameter_packs) |
5099 | << T << D.getSourceRange(); |
5100 | D.setEllipsisLoc(SourceLocation()); |
5101 | } else { |
5102 | T = Context.getPackExpansionType(T, None); |
5103 | } |
5104 | break; |
5105 | case DeclaratorContext::TemplateParamContext: |
5106 | // C++0x [temp.param]p15: |
5107 | // If a template-parameter is a [...] is a parameter-declaration that |
5108 | // declares a parameter pack (8.3.5), then the template-parameter is a |
5109 | // template parameter pack (14.5.3). |
5110 | // |
5111 | // Note: core issue 778 clarifies that, if there are any unexpanded |
5112 | // parameter packs in the type of the non-type template parameter, then |
5113 | // it expands those parameter packs. |
5114 | if (T->containsUnexpandedParameterPack()) |
5115 | T = Context.getPackExpansionType(T, None); |
5116 | else |
5117 | S.Diag(D.getEllipsisLoc(), |
5118 | LangOpts.CPlusPlus11 |
5119 | ? diag::warn_cxx98_compat_variadic_templates |
5120 | : diag::ext_variadic_templates); |
5121 | break; |
5122 | |
5123 | case DeclaratorContext::FileContext: |
5124 | case DeclaratorContext::KNRTypeListContext: |
5125 | case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic |
5126 | // here? |
5127 | case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic |
5128 | // here? |
5129 | case DeclaratorContext::TypeNameContext: |
5130 | case DeclaratorContext::FunctionalCastContext: |
5131 | case DeclaratorContext::CXXNewContext: |
5132 | case DeclaratorContext::AliasDeclContext: |
5133 | case DeclaratorContext::AliasTemplateContext: |
5134 | case DeclaratorContext::MemberContext: |
5135 | case DeclaratorContext::BlockContext: |
5136 | case DeclaratorContext::ForContext: |
5137 | case DeclaratorContext::InitStmtContext: |
5138 | case DeclaratorContext::ConditionContext: |
5139 | case DeclaratorContext::CXXCatchContext: |
5140 | case DeclaratorContext::ObjCCatchContext: |
5141 | case DeclaratorContext::BlockLiteralContext: |
5142 | case DeclaratorContext::LambdaExprContext: |
5143 | case DeclaratorContext::ConversionIdContext: |
5144 | case DeclaratorContext::TrailingReturnContext: |
5145 | case DeclaratorContext::TrailingReturnVarContext: |
5146 | case DeclaratorContext::TemplateArgContext: |
5147 | case DeclaratorContext::TemplateTypeArgContext: |
5148 | // FIXME: We may want to allow parameter packs in block-literal contexts |
5149 | // in the future. |
5150 | S.Diag(D.getEllipsisLoc(), |
5151 | diag::err_ellipsis_in_declarator_not_parameter); |
5152 | D.setEllipsisLoc(SourceLocation()); |
5153 | break; |
5154 | } |
5155 | } |
5156 | |
5157 | assert(!T.isNull() && "T must not be null at the end of this function")((!T.isNull() && "T must not be null at the end of this function" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"T must not be null at the end of this function\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5157, __PRETTY_FUNCTION__)); |
5158 | if (D.isInvalidType()) |
5159 | return Context.getTrivialTypeSourceInfo(T); |
5160 | |
5161 | return GetTypeSourceInfoForDeclarator(state, T, TInfo); |
5162 | } |
5163 | |
5164 | /// GetTypeForDeclarator - Convert the type for the specified |
5165 | /// declarator to Type instances. |
5166 | /// |
5167 | /// The result of this call will never be null, but the associated |
5168 | /// type may be a null type if there's an unrecoverable error. |
5169 | TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { |
5170 | // Determine the type of the declarator. Not all forms of declarator |
5171 | // have a type. |
5172 | |
5173 | TypeProcessingState state(*this, D); |
5174 | |
5175 | TypeSourceInfo *ReturnTypeInfo = nullptr; |
5176 | QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); |
5177 | if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) |
5178 | inferARCWriteback(state, T); |
5179 | |
5180 | return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); |
5181 | } |
5182 | |
5183 | static void transferARCOwnershipToDeclSpec(Sema &S, |
5184 | QualType &declSpecTy, |
5185 | Qualifiers::ObjCLifetime ownership) { |
5186 | if (declSpecTy->isObjCRetainableType() && |
5187 | declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { |
5188 | Qualifiers qs; |
5189 | qs.addObjCLifetime(ownership); |
5190 | declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); |
5191 | } |
5192 | } |
5193 | |
5194 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, |
5195 | Qualifiers::ObjCLifetime ownership, |
5196 | unsigned chunkIndex) { |
5197 | Sema &S = state.getSema(); |
5198 | Declarator &D = state.getDeclarator(); |
5199 | |
5200 | // Look for an explicit lifetime attribute. |
5201 | DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); |
5202 | if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) |
5203 | return; |
5204 | |
5205 | const char *attrStr = nullptr; |
5206 | switch (ownership) { |
5207 | case Qualifiers::OCL_None: llvm_unreachable("no ownership!")::llvm::llvm_unreachable_internal("no ownership!", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5207); |
5208 | case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; |
5209 | case Qualifiers::OCL_Strong: attrStr = "strong"; break; |
5210 | case Qualifiers::OCL_Weak: attrStr = "weak"; break; |
5211 | case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; |
5212 | } |
5213 | |
5214 | IdentifierLoc *Arg = new (S.Context) IdentifierLoc; |
5215 | Arg->Ident = &S.Context.Idents.get(attrStr); |
5216 | Arg->Loc = SourceLocation(); |
5217 | |
5218 | ArgsUnion Args(Arg); |
5219 | |
5220 | // If there wasn't one, add one (with an invalid source location |
5221 | // so that we don't make an AttributedType for it). |
5222 | ParsedAttr *attr = D.getAttributePool().create( |
5223 | &S.Context.Idents.get("objc_ownership"), SourceLocation(), |
5224 | /*scope*/ nullptr, SourceLocation(), |
5225 | /*args*/ &Args, 1, ParsedAttr::AS_GNU); |
5226 | chunk.getAttrs().addAtEnd(attr); |
5227 | // TODO: mark whether we did this inference? |
5228 | } |
5229 | |
5230 | /// Used for transferring ownership in casts resulting in l-values. |
5231 | static void transferARCOwnership(TypeProcessingState &state, |
5232 | QualType &declSpecTy, |
5233 | Qualifiers::ObjCLifetime ownership) { |
5234 | Sema &S = state.getSema(); |
5235 | Declarator &D = state.getDeclarator(); |
5236 | |
5237 | int inner = -1; |
5238 | bool hasIndirection = false; |
5239 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { |
5240 | DeclaratorChunk &chunk = D.getTypeObject(i); |
5241 | switch (chunk.Kind) { |
5242 | case DeclaratorChunk::Paren: |
5243 | // Ignore parens. |
5244 | break; |
5245 | |
5246 | case DeclaratorChunk::Array: |
5247 | case DeclaratorChunk::Reference: |
5248 | case DeclaratorChunk::Pointer: |
5249 | if (inner != -1) |
5250 | hasIndirection = true; |
5251 | inner = i; |
5252 | break; |
5253 | |
5254 | case DeclaratorChunk::BlockPointer: |
5255 | if (inner != -1) |
5256 | transferARCOwnershipToDeclaratorChunk(state, ownership, i); |
5257 | return; |
5258 | |
5259 | case DeclaratorChunk::Function: |
5260 | case DeclaratorChunk::MemberPointer: |
5261 | case DeclaratorChunk::Pipe: |
5262 | return; |
5263 | } |
5264 | } |
5265 | |
5266 | if (inner == -1) |
5267 | return; |
5268 | |
5269 | DeclaratorChunk &chunk = D.getTypeObject(inner); |
5270 | if (chunk.Kind == DeclaratorChunk::Pointer) { |
5271 | if (declSpecTy->isObjCRetainableType()) |
5272 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); |
5273 | if (declSpecTy->isObjCObjectType() && hasIndirection) |
5274 | return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); |
5275 | } else { |
5276 | assert(chunk.Kind == DeclaratorChunk::Array ||((chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk ::Reference) ? static_cast<void> (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5277, __PRETTY_FUNCTION__)) |
5277 | chunk.Kind == DeclaratorChunk::Reference)((chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk ::Reference) ? static_cast<void> (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5277, __PRETTY_FUNCTION__)); |
5278 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); |
5279 | } |
5280 | } |
5281 | |
5282 | TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { |
5283 | TypeProcessingState state(*this, D); |
5284 | |
5285 | TypeSourceInfo *ReturnTypeInfo = nullptr; |
5286 | QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); |
5287 | |
5288 | if (getLangOpts().ObjC) { |
5289 | Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); |
5290 | if (ownership != Qualifiers::OCL_None) |
5291 | transferARCOwnership(state, declSpecTy, ownership); |
5292 | } |
5293 | |
5294 | return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); |
5295 | } |
5296 | |
5297 | static void fillAttributedTypeLoc(AttributedTypeLoc TL, |
5298 | TypeProcessingState &State) { |
5299 | TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); |
5300 | } |
5301 | |
5302 | namespace { |
5303 | class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { |
5304 | ASTContext &Context; |
5305 | TypeProcessingState &State; |
5306 | const DeclSpec &DS; |
5307 | |
5308 | public: |
5309 | TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State, |
5310 | const DeclSpec &DS) |
5311 | : Context(Context), State(State), DS(DS) {} |
5312 | |
5313 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { |
5314 | Visit(TL.getModifiedLoc()); |
5315 | fillAttributedTypeLoc(TL, State); |
5316 | } |
5317 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { |
5318 | Visit(TL.getUnqualifiedLoc()); |
5319 | } |
5320 | void VisitTypedefTypeLoc(TypedefTypeLoc TL) { |
5321 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); |
5322 | } |
5323 | void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { |
5324 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); |
5325 | // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires |
5326 | // addition field. What we have is good enough for dispay of location |
5327 | // of 'fixit' on interface name. |
5328 | TL.setNameEndLoc(DS.getEndLoc()); |
5329 | } |
5330 | void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { |
5331 | TypeSourceInfo *RepTInfo = nullptr; |
5332 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); |
5333 | TL.copy(RepTInfo->getTypeLoc()); |
5334 | } |
5335 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { |
5336 | TypeSourceInfo *RepTInfo = nullptr; |
5337 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); |
5338 | TL.copy(RepTInfo->getTypeLoc()); |
5339 | } |
5340 | void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { |
5341 | TypeSourceInfo *TInfo = nullptr; |
5342 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); |
5343 | |
5344 | // If we got no declarator info from previous Sema routines, |
5345 | // just fill with the typespec loc. |
5346 | if (!TInfo) { |
5347 | TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); |
5348 | return; |
5349 | } |
5350 | |
5351 | TypeLoc OldTL = TInfo->getTypeLoc(); |
5352 | if (TInfo->getType()->getAs<ElaboratedType>()) { |
5353 | ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); |
5354 | TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() |
5355 | .castAs<TemplateSpecializationTypeLoc>(); |
5356 | TL.copy(NamedTL); |
5357 | } else { |
5358 | TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); |
5359 | assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc())((TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc >().getRAngleLoc()) ? static_cast<void> (0) : __assert_fail ("TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5359, __PRETTY_FUNCTION__)); |
5360 | } |
5361 | |
5362 | } |
5363 | void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { |
5364 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr)((DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) ? static_cast <void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofExpr" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5364, __PRETTY_FUNCTION__)); |
5365 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); |
5366 | TL.setParensRange(DS.getTypeofParensRange()); |
5367 | } |
5368 | void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { |
5369 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType)((DS.getTypeSpecType() == DeclSpec::TST_typeofType) ? static_cast <void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofType" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5369, __PRETTY_FUNCTION__)); |
5370 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); |
5371 | TL.setParensRange(DS.getTypeofParensRange()); |
5372 | assert(DS.getRepAsType())((DS.getRepAsType()) ? static_cast<void> (0) : __assert_fail ("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5372, __PRETTY_FUNCTION__)); |
5373 | TypeSourceInfo *TInfo = nullptr; |
5374 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); |
5375 | TL.setUnderlyingTInfo(TInfo); |
5376 | } |
5377 | void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { |
5378 | // FIXME: This holds only because we only have one unary transform. |
5379 | assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType)((DS.getTypeSpecType() == DeclSpec::TST_underlyingType) ? static_cast <void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_underlyingType" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5379, __PRETTY_FUNCTION__)); |
5380 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); |
5381 | TL.setParensRange(DS.getTypeofParensRange()); |
5382 | assert(DS.getRepAsType())((DS.getRepAsType()) ? static_cast<void> (0) : __assert_fail ("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5382, __PRETTY_FUNCTION__)); |
5383 | TypeSourceInfo *TInfo = nullptr; |
5384 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); |
5385 | TL.setUnderlyingTInfo(TInfo); |
5386 | } |
5387 | void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { |
5388 | // By default, use the source location of the type specifier. |
5389 | TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); |
5390 | if (TL.needsExtraLocalData()) { |
5391 | // Set info for the written builtin specifiers. |
5392 | TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); |
5393 | // Try to have a meaningful source location. |
5394 | if (TL.getWrittenSignSpec() != TSS_unspecified) |
5395 | TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); |
5396 | if (TL.getWrittenWidthSpec() != TSW_unspecified) |
5397 | TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); |
5398 | } |
5399 | } |
5400 | void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { |
5401 | ElaboratedTypeKeyword Keyword |
5402 | = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); |
5403 | if (DS.getTypeSpecType() == TST_typename) { |
5404 | TypeSourceInfo *TInfo = nullptr; |
5405 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); |
5406 | if (TInfo) { |
5407 | TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); |
5408 | return; |
5409 | } |
5410 | } |
5411 | TL.setElaboratedKeywordLoc(Keyword != ETK_None |
5412 | ? DS.getTypeSpecTypeLoc() |
5413 | : SourceLocation()); |
5414 | const CXXScopeSpec& SS = DS.getTypeSpecScope(); |
5415 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
5416 | Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); |
5417 | } |
5418 | void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { |
5419 | assert(DS.getTypeSpecType() == TST_typename)((DS.getTypeSpecType() == TST_typename) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5419, __PRETTY_FUNCTION__)); |
5420 | TypeSourceInfo *TInfo = nullptr; |
5421 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); |
5422 | assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5422, __PRETTY_FUNCTION__)); |
5423 | TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); |
5424 | } |
5425 | void VisitDependentTemplateSpecializationTypeLoc( |
5426 | DependentTemplateSpecializationTypeLoc TL) { |
5427 | assert(DS.getTypeSpecType() == TST_typename)((DS.getTypeSpecType() == TST_typename) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5427, __PRETTY_FUNCTION__)); |
5428 | TypeSourceInfo *TInfo = nullptr; |
5429 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); |
5430 | assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5430, __PRETTY_FUNCTION__)); |
5431 | TL.copy( |
5432 | TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); |
5433 | } |
5434 | void VisitTagTypeLoc(TagTypeLoc TL) { |
5435 | TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); |
5436 | } |
5437 | void VisitAtomicTypeLoc(AtomicTypeLoc TL) { |
5438 | // An AtomicTypeLoc can come from either an _Atomic(...) type specifier |
5439 | // or an _Atomic qualifier. |
5440 | if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { |
5441 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); |
5442 | TL.setParensRange(DS.getTypeofParensRange()); |
5443 | |
5444 | TypeSourceInfo *TInfo = nullptr; |
5445 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); |
5446 | assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5446, __PRETTY_FUNCTION__)); |
5447 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); |
5448 | } else { |
5449 | TL.setKWLoc(DS.getAtomicSpecLoc()); |
5450 | // No parens, to indicate this was spelled as an _Atomic qualifier. |
5451 | TL.setParensRange(SourceRange()); |
5452 | Visit(TL.getValueLoc()); |
5453 | } |
5454 | } |
5455 | |
5456 | void VisitPipeTypeLoc(PipeTypeLoc TL) { |
5457 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); |
5458 | |
5459 | TypeSourceInfo *TInfo = nullptr; |
5460 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); |
5461 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); |
5462 | } |
5463 | |
5464 | void VisitTypeLoc(TypeLoc TL) { |
5465 | // FIXME: add other typespec types and change this to an assert. |
5466 | TL.initialize(Context, DS.getTypeSpecTypeLoc()); |
5467 | } |
5468 | }; |
5469 | |
5470 | class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { |
5471 | ASTContext &Context; |
5472 | TypeProcessingState &State; |
5473 | const DeclaratorChunk &Chunk; |
5474 | |
5475 | public: |
5476 | DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, |
5477 | const DeclaratorChunk &Chunk) |
5478 | : Context(Context), State(State), Chunk(Chunk) {} |
5479 | |
5480 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { |
5481 | llvm_unreachable("qualified type locs not expected here!")::llvm::llvm_unreachable_internal("qualified type locs not expected here!" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5481); |
5482 | } |
5483 | void VisitDecayedTypeLoc(DecayedTypeLoc TL) { |
5484 | llvm_unreachable("decayed type locs not expected here!")::llvm::llvm_unreachable_internal("decayed type locs not expected here!" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5484); |
5485 | } |
5486 | |
5487 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { |
5488 | fillAttributedTypeLoc(TL, State); |
5489 | } |
5490 | void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { |
5491 | // nothing |
5492 | } |
5493 | void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { |
5494 | assert(Chunk.Kind == DeclaratorChunk::BlockPointer)((Chunk.Kind == DeclaratorChunk::BlockPointer) ? static_cast< void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::BlockPointer" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5494, __PRETTY_FUNCTION__)); |
5495 | TL.setCaretLoc(Chunk.Loc); |
5496 | } |
5497 | void VisitPointerTypeLoc(PointerTypeLoc TL) { |
5498 | assert(Chunk.Kind == DeclaratorChunk::Pointer)((Chunk.Kind == DeclaratorChunk::Pointer) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5498, __PRETTY_FUNCTION__)); |
5499 | TL.setStarLoc(Chunk.Loc); |
5500 | } |
5501 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { |
5502 | assert(Chunk.Kind == DeclaratorChunk::Pointer)((Chunk.Kind == DeclaratorChunk::Pointer) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5502, __PRETTY_FUNCTION__)); |
5503 | TL.setStarLoc(Chunk.Loc); |
5504 | } |
5505 | void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { |
5506 | assert(Chunk.Kind == DeclaratorChunk::MemberPointer)((Chunk.Kind == DeclaratorChunk::MemberPointer) ? static_cast <void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::MemberPointer" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5506, __PRETTY_FUNCTION__)); |
5507 | const CXXScopeSpec& SS = Chunk.Mem.Scope(); |
5508 | NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); |
5509 | |
5510 | const Type* ClsTy = TL.getClass(); |
5511 | QualType ClsQT = QualType(ClsTy, 0); |
5512 | TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); |
5513 | // Now copy source location info into the type loc component. |
5514 | TypeLoc ClsTL = ClsTInfo->getTypeLoc(); |
5515 | switch (NNSLoc.getNestedNameSpecifier()->getKind()) { |
5516 | case NestedNameSpecifier::Identifier: |
5517 | assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc")((isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc" ) ? static_cast<void> (0) : __assert_fail ("isa<DependentNameType>(ClsTy) && \"Unexpected TypeLoc\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5517, __PRETTY_FUNCTION__)); |
5518 | { |
5519 | DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); |
5520 | DNTLoc.setElaboratedKeywordLoc(SourceLocation()); |
5521 | DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); |
5522 | DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); |
5523 | } |
5524 | break; |
5525 | |
5526 | case NestedNameSpecifier::TypeSpec: |
5527 | case NestedNameSpecifier::TypeSpecWithTemplate: |
5528 | if (isa<ElaboratedType>(ClsTy)) { |
5529 | ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); |
5530 | ETLoc.setElaboratedKeywordLoc(SourceLocation()); |
5531 | ETLoc.setQualifierLoc(NNSLoc.getPrefix()); |
5532 | TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); |
5533 | NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); |
5534 | } else { |
5535 | ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); |
5536 | } |
5537 | break; |
5538 | |
5539 | case NestedNameSpecifier::Namespace: |
5540 | case NestedNameSpecifier::NamespaceAlias: |
5541 | case NestedNameSpecifier::Global: |
5542 | case NestedNameSpecifier::Super: |
5543 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5543); |
5544 | } |
5545 | |
5546 | // Finally fill in MemberPointerLocInfo fields. |
5547 | TL.setStarLoc(Chunk.Loc); |
5548 | TL.setClassTInfo(ClsTInfo); |
5549 | } |
5550 | void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { |
5551 | assert(Chunk.Kind == DeclaratorChunk::Reference)((Chunk.Kind == DeclaratorChunk::Reference) ? static_cast< void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5551, __PRETTY_FUNCTION__)); |
5552 | // 'Amp' is misleading: this might have been originally |
5553 | /// spelled with AmpAmp. |
5554 | TL.setAmpLoc(Chunk.Loc); |
5555 | } |
5556 | void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { |
5557 | assert(Chunk.Kind == DeclaratorChunk::Reference)((Chunk.Kind == DeclaratorChunk::Reference) ? static_cast< void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5557, __PRETTY_FUNCTION__)); |
5558 | assert(!Chunk.Ref.LValueRef)((!Chunk.Ref.LValueRef) ? static_cast<void> (0) : __assert_fail ("!Chunk.Ref.LValueRef", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5558, __PRETTY_FUNCTION__)); |
5559 | TL.setAmpAmpLoc(Chunk.Loc); |
5560 | } |
5561 | void VisitArrayTypeLoc(ArrayTypeLoc TL) { |
5562 | assert(Chunk.Kind == DeclaratorChunk::Array)((Chunk.Kind == DeclaratorChunk::Array) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Array" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5562, __PRETTY_FUNCTION__)); |
5563 | TL.setLBracketLoc(Chunk.Loc); |
5564 | TL.setRBracketLoc(Chunk.EndLoc); |
5565 | TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); |
5566 | } |
5567 | void VisitFunctionTypeLoc(FunctionTypeLoc TL) { |
5568 | assert(Chunk.Kind == DeclaratorChunk::Function)((Chunk.Kind == DeclaratorChunk::Function) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5568, __PRETTY_FUNCTION__)); |
5569 | TL.setLocalRangeBegin(Chunk.Loc); |
5570 | TL.setLocalRangeEnd(Chunk.EndLoc); |
5571 | |
5572 | const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; |
5573 | TL.setLParenLoc(FTI.getLParenLoc()); |
5574 | TL.setRParenLoc(FTI.getRParenLoc()); |
5575 | for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { |
5576 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); |
5577 | TL.setParam(tpi++, Param); |
5578 | } |
5579 | TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); |
5580 | } |
5581 | void VisitParenTypeLoc(ParenTypeLoc TL) { |
5582 | assert(Chunk.Kind == DeclaratorChunk::Paren)((Chunk.Kind == DeclaratorChunk::Paren) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Paren" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5582, __PRETTY_FUNCTION__)); |
5583 | TL.setLParenLoc(Chunk.Loc); |
5584 | TL.setRParenLoc(Chunk.EndLoc); |
5585 | } |
5586 | void VisitPipeTypeLoc(PipeTypeLoc TL) { |
5587 | assert(Chunk.Kind == DeclaratorChunk::Pipe)((Chunk.Kind == DeclaratorChunk::Pipe) ? static_cast<void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pipe", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5587, __PRETTY_FUNCTION__)); |
5588 | TL.setKWLoc(Chunk.Loc); |
5589 | } |
5590 | |
5591 | void VisitTypeLoc(TypeLoc TL) { |
5592 | llvm_unreachable("unsupported TypeLoc kind in declarator!")::llvm::llvm_unreachable_internal("unsupported TypeLoc kind in declarator!" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5592); |
5593 | } |
5594 | }; |
5595 | } // end anonymous namespace |
5596 | |
5597 | static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { |
5598 | SourceLocation Loc; |
5599 | switch (Chunk.Kind) { |
5600 | case DeclaratorChunk::Function: |
5601 | case DeclaratorChunk::Array: |
5602 | case DeclaratorChunk::Paren: |
5603 | case DeclaratorChunk::Pipe: |
5604 | llvm_unreachable("cannot be _Atomic qualified")::llvm::llvm_unreachable_internal("cannot be _Atomic qualified" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5604); |
5605 | |
5606 | case DeclaratorChunk::Pointer: |
5607 | Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); |
5608 | break; |
5609 | |
5610 | case DeclaratorChunk::BlockPointer: |
5611 | case DeclaratorChunk::Reference: |
5612 | case DeclaratorChunk::MemberPointer: |
5613 | // FIXME: Provide a source location for the _Atomic keyword. |
5614 | break; |
5615 | } |
5616 | |
5617 | ATL.setKWLoc(Loc); |
5618 | ATL.setParensRange(SourceRange()); |
5619 | } |
5620 | |
5621 | static void |
5622 | fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, |
5623 | const ParsedAttributesView &Attrs) { |
5624 | for (const ParsedAttr &AL : Attrs) { |
5625 | if (AL.getKind() == ParsedAttr::AT_AddressSpace) { |
5626 | DASTL.setAttrNameLoc(AL.getLoc()); |
5627 | DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); |
5628 | DASTL.setAttrOperandParensRange(SourceRange()); |
5629 | return; |
5630 | } |
5631 | } |
5632 | |
5633 | llvm_unreachable(::llvm::llvm_unreachable_internal("no address_space attribute found at the expected location!" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5634) |
5634 | "no address_space attribute found at the expected location!")::llvm::llvm_unreachable_internal("no address_space attribute found at the expected location!" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5634); |
5635 | } |
5636 | |
5637 | /// Create and instantiate a TypeSourceInfo with type source information. |
5638 | /// |
5639 | /// \param T QualType referring to the type as written in source code. |
5640 | /// |
5641 | /// \param ReturnTypeInfo For declarators whose return type does not show |
5642 | /// up in the normal place in the declaration specifiers (such as a C++ |
5643 | /// conversion function), this pointer will refer to a type source information |
5644 | /// for that return type. |
5645 | static TypeSourceInfo * |
5646 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, |
5647 | QualType T, TypeSourceInfo *ReturnTypeInfo) { |
5648 | Sema &S = State.getSema(); |
5649 | Declarator &D = State.getDeclarator(); |
5650 | |
5651 | TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); |
5652 | UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); |
5653 | |
5654 | // Handle parameter packs whose type is a pack expansion. |
5655 | if (isa<PackExpansionType>(T)) { |
5656 | CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); |
5657 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); |
5658 | } |
5659 | |
5660 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { |
5661 | // An AtomicTypeLoc might be produced by an atomic qualifier in this |
5662 | // declarator chunk. |
5663 | if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { |
5664 | fillAtomicQualLoc(ATL, D.getTypeObject(i)); |
5665 | CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); |
5666 | } |
5667 | |
5668 | while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { |
5669 | fillAttributedTypeLoc(TL, State); |
5670 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); |
5671 | } |
5672 | |
5673 | while (DependentAddressSpaceTypeLoc TL = |
5674 | CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { |
5675 | fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); |
5676 | CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); |
5677 | } |
5678 | |
5679 | // FIXME: Ordering here? |
5680 | while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) |
5681 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); |
5682 | |
5683 | DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); |
5684 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); |
5685 | } |
5686 | |
5687 | // If we have different source information for the return type, use |
5688 | // that. This really only applies to C++ conversion functions. |
5689 | if (ReturnTypeInfo) { |
5690 | TypeLoc TL = ReturnTypeInfo->getTypeLoc(); |
5691 | assert(TL.getFullDataSize() == CurrTL.getFullDataSize())((TL.getFullDataSize() == CurrTL.getFullDataSize()) ? static_cast <void> (0) : __assert_fail ("TL.getFullDataSize() == CurrTL.getFullDataSize()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5691, __PRETTY_FUNCTION__)); |
5692 | memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); |
5693 | } else { |
5694 | TypeSpecLocFiller(S.Context, State, D.getDeclSpec()).Visit(CurrTL); |
5695 | } |
5696 | |
5697 | return TInfo; |
5698 | } |
5699 | |
5700 | /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. |
5701 | ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { |
5702 | // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser |
5703 | // and Sema during declaration parsing. Try deallocating/caching them when |
5704 | // it's appropriate, instead of allocating them and keeping them around. |
5705 | LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), |
5706 | TypeAlignment); |
5707 | new (LocT) LocInfoType(T, TInfo); |
5708 | assert(LocT->getTypeClass() != T->getTypeClass() &&((LocT->getTypeClass() != T->getTypeClass() && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? static_cast<void> (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5709, __PRETTY_FUNCTION__)) |
5709 | "LocInfoType's TypeClass conflicts with an existing Type class")((LocT->getTypeClass() != T->getTypeClass() && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? static_cast<void> (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5709, __PRETTY_FUNCTION__)); |
5710 | return ParsedType::make(QualType(LocT, 0)); |
5711 | } |
5712 | |
5713 | void LocInfoType::getAsStringInternal(std::string &Str, |
5714 | const PrintingPolicy &Policy) const { |
5715 | 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", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5717) |
5716 | " 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", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5717) |
5717 | " GetTypeFromParser")::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*" " was used directly instead of getting the QualType through" " GetTypeFromParser", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5717); |
5718 | } |
5719 | |
5720 | TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { |
5721 | // C99 6.7.6: Type names have no identifier. This is already validated by |
5722 | // the parser. |
5723 | assert(D.getIdentifier() == nullptr &&((D.getIdentifier() == nullptr && "Type name should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5724, __PRETTY_FUNCTION__)) |
5724 | "Type name should have no identifier!")((D.getIdentifier() == nullptr && "Type name should have no identifier!" ) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5724, __PRETTY_FUNCTION__)); |
5725 | |
5726 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
5727 | QualType T = TInfo->getType(); |
5728 | if (D.isInvalidType()) |
5729 | return true; |
5730 | |
5731 | // Make sure there are no unused decl attributes on the declarator. |
5732 | // We don't want to do this for ObjC parameters because we're going |
5733 | // to apply them to the actual parameter declaration. |
5734 | // Likewise, we don't want to do this for alias declarations, because |
5735 | // we are actually going to build a declaration from this eventually. |
5736 | if (D.getContext() != DeclaratorContext::ObjCParameterContext && |
5737 | D.getContext() != DeclaratorContext::AliasDeclContext && |
5738 | D.getContext() != DeclaratorContext::AliasTemplateContext) |
5739 | checkUnusedDeclAttributes(D); |
5740 | |
5741 | if (getLangOpts().CPlusPlus) { |
5742 | // Check that there are no default arguments (C++ only). |
5743 | CheckExtraCXXDefaultArguments(D); |
5744 | } |
5745 | |
5746 | return CreateParsedType(T, TInfo); |
5747 | } |
5748 | |
5749 | ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { |
5750 | QualType T = Context.getObjCInstanceType(); |
5751 | TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); |
5752 | return CreateParsedType(T, TInfo); |
5753 | } |
5754 | |
5755 | //===----------------------------------------------------------------------===// |
5756 | // Type Attribute Processing |
5757 | //===----------------------------------------------------------------------===// |
5758 | |
5759 | /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression |
5760 | /// is uninstantiated. If instantiated it will apply the appropriate address space |
5761 | /// to the type. This function allows dependent template variables to be used in |
5762 | /// conjunction with the address_space attribute |
5763 | QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, |
5764 | SourceLocation AttrLoc) { |
5765 | if (!AddrSpace->isValueDependent()) { |
5766 | |
5767 | llvm::APSInt addrSpace(32); |
5768 | if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) { |
5769 | Diag(AttrLoc, diag::err_attribute_argument_type) |
5770 | << "'address_space'" << AANT_ArgumentIntegerConstant |
5771 | << AddrSpace->getSourceRange(); |
5772 | return QualType(); |
5773 | } |
5774 | |
5775 | // Bounds checking. |
5776 | if (addrSpace.isSigned()) { |
5777 | if (addrSpace.isNegative()) { |
5778 | Diag(AttrLoc, diag::err_attribute_address_space_negative) |
5779 | << AddrSpace->getSourceRange(); |
5780 | return QualType(); |
5781 | } |
5782 | addrSpace.setIsSigned(false); |
5783 | } |
5784 | |
5785 | llvm::APSInt max(addrSpace.getBitWidth()); |
5786 | max = |
5787 | Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; |
5788 | if (addrSpace > max) { |
5789 | Diag(AttrLoc, diag::err_attribute_address_space_too_high) |
5790 | << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); |
5791 | return QualType(); |
5792 | } |
5793 | |
5794 | LangAS ASIdx = |
5795 | getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); |
5796 | |
5797 | // If this type is already address space qualified with a different |
5798 | // address space, reject it. |
5799 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified |
5800 | // by qualifiers for two or more different address spaces." |
5801 | if (T.getAddressSpace() != LangAS::Default) { |
5802 | if (T.getAddressSpace() != ASIdx) { |
5803 | Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); |
5804 | return QualType(); |
5805 | } else |
5806 | // Emit a warning if they are identical; it's likely unintended. |
5807 | Diag(AttrLoc, |
5808 | diag::warn_attribute_address_multiple_identical_qualifiers); |
5809 | } |
5810 | |
5811 | return Context.getAddrSpaceQualType(T, ASIdx); |
5812 | } |
5813 | |
5814 | // A check with similar intentions as checking if a type already has an |
5815 | // address space except for on a dependent types, basically if the |
5816 | // current type is already a DependentAddressSpaceType then its already |
5817 | // lined up to have another address space on it and we can't have |
5818 | // multiple address spaces on the one pointer indirection |
5819 | if (T->getAs<DependentAddressSpaceType>()) { |
5820 | Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); |
5821 | return QualType(); |
5822 | } |
5823 | |
5824 | return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); |
5825 | } |
5826 | |
5827 | /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the |
5828 | /// specified type. The attribute contains 1 argument, the id of the address |
5829 | /// space for the type. |
5830 | static void HandleAddressSpaceTypeAttribute(QualType &Type, |
5831 | const ParsedAttr &Attr, |
5832 | TypeProcessingState &State) { |
5833 | Sema &S = State.getSema(); |
5834 | |
5835 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be |
5836 | // qualified by an address-space qualifier." |
5837 | if (Type->isFunctionType()) { |
5838 | S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); |
5839 | Attr.setInvalid(); |
5840 | return; |
5841 | } |
5842 | |
5843 | LangAS ASIdx; |
5844 | if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { |
5845 | |
5846 | // Check the attribute arguments. |
5847 | if (Attr.getNumArgs() != 1) { |
5848 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr |
5849 | << 1; |
5850 | Attr.setInvalid(); |
5851 | return; |
5852 | } |
5853 | |
5854 | Expr *ASArgExpr; |
5855 | if (Attr.isArgIdent(0)) { |
5856 | // Special case where the argument is a template id. |
5857 | CXXScopeSpec SS; |
5858 | SourceLocation TemplateKWLoc; |
5859 | UnqualifiedId id; |
5860 | id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); |
5861 | |
5862 | ExprResult AddrSpace = S.ActOnIdExpression( |
5863 | S.getCurScope(), SS, TemplateKWLoc, id, false, false); |
5864 | if (AddrSpace.isInvalid()) |
5865 | return; |
5866 | |
5867 | ASArgExpr = static_cast<Expr *>(AddrSpace.get()); |
5868 | } else { |
5869 | ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); |
5870 | } |
5871 | |
5872 | // Create the DependentAddressSpaceType or append an address space onto |
5873 | // the type. |
5874 | QualType T = S.BuildAddressSpaceAttr(Type, ASArgExpr, Attr.getLoc()); |
5875 | |
5876 | if (!T.isNull()) { |
5877 | ASTContext &Ctx = S.Context; |
5878 | auto *ASAttr = ::new (Ctx) AddressSpaceAttr( |
5879 | Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex(), |
5880 | static_cast<unsigned>(T.getQualifiers().getAddressSpace())); |
5881 | Type = State.getAttributedType(ASAttr, T, T); |
5882 | } else { |
5883 | Attr.setInvalid(); |
5884 | } |
5885 | } else { |
5886 | // The keyword-based type attributes imply which address space to use. |
5887 | switch (Attr.getKind()) { |
5888 | case ParsedAttr::AT_OpenCLGlobalAddressSpace: |
5889 | ASIdx = LangAS::opencl_global; break; |
5890 | case ParsedAttr::AT_OpenCLLocalAddressSpace: |
5891 | ASIdx = LangAS::opencl_local; break; |
5892 | case ParsedAttr::AT_OpenCLConstantAddressSpace: |
5893 | ASIdx = LangAS::opencl_constant; break; |
5894 | case ParsedAttr::AT_OpenCLGenericAddressSpace: |
5895 | ASIdx = LangAS::opencl_generic; break; |
5896 | case ParsedAttr::AT_OpenCLPrivateAddressSpace: |
5897 | ASIdx = LangAS::opencl_private; break; |
5898 | default: |
5899 | llvm_unreachable("Invalid address space")::llvm::llvm_unreachable_internal("Invalid address space", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5899); |
5900 | } |
5901 | |
5902 | // If this type is already address space qualified with a different |
5903 | // address space, reject it. |
5904 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by |
5905 | // qualifiers for two or more different address spaces." |
5906 | if (Type.getAddressSpace() != LangAS::Default) { |
5907 | if (Type.getAddressSpace() != ASIdx) { |
5908 | S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); |
5909 | Attr.setInvalid(); |
5910 | return; |
5911 | } else |
5912 | // Emit a warning if they are identical; it's likely unintended. |
5913 | S.Diag(Attr.getLoc(), |
5914 | diag::warn_attribute_address_multiple_identical_qualifiers); |
5915 | } |
5916 | |
5917 | Type = S.Context.getAddrSpaceQualType(Type, ASIdx); |
5918 | } |
5919 | } |
5920 | |
5921 | /// Does this type have a "direct" ownership qualifier? That is, |
5922 | /// is it written like "__strong id", as opposed to something like |
5923 | /// "typeof(foo)", where that happens to be strong? |
5924 | static bool hasDirectOwnershipQualifier(QualType type) { |
5925 | // Fast path: no qualifier at all. |
5926 | assert(type.getQualifiers().hasObjCLifetime())((type.getQualifiers().hasObjCLifetime()) ? static_cast<void > (0) : __assert_fail ("type.getQualifiers().hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 5926, __PRETTY_FUNCTION__)); |
5927 | |
5928 | while (true) { |
5929 | // __strong id |
5930 | if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { |
5931 | if (attr->getAttrKind() == attr::ObjCOwnership) |
5932 | return true; |
5933 | |
5934 | type = attr->getModifiedType(); |
5935 | |
5936 | // X *__strong (...) |
5937 | } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { |
5938 | type = paren->getInnerType(); |
5939 | |
5940 | // That's it for things we want to complain about. In particular, |
5941 | // we do not want to look through typedefs, typeof(expr), |
5942 | // typeof(type), or any other way that the type is somehow |
5943 | // abstracted. |
5944 | } else { |
5945 | |
5946 | return false; |
5947 | } |
5948 | } |
5949 | } |
5950 | |
5951 | /// handleObjCOwnershipTypeAttr - Process an objc_ownership |
5952 | /// attribute on the specified type. |
5953 | /// |
5954 | /// Returns 'true' if the attribute was handled. |
5955 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, |
5956 | ParsedAttr &attr, QualType &type) { |
5957 | bool NonObjCPointer = false; |
5958 | |
5959 | if (!type->isDependentType() && !type->isUndeducedType()) { |
5960 | if (const PointerType *ptr = type->getAs<PointerType>()) { |
5961 | QualType pointee = ptr->getPointeeType(); |
5962 | if (pointee->isObjCRetainableType() || pointee->isPointerType()) |
5963 | return false; |
5964 | // It is important not to lose the source info that there was an attribute |
5965 | // applied to non-objc pointer. We will create an attributed type but |
5966 | // its type will be the same as the original type. |
5967 | NonObjCPointer = true; |
5968 | } else if (!type->isObjCRetainableType()) { |
5969 | return false; |
5970 | } |
5971 | |
5972 | // Don't accept an ownership attribute in the declspec if it would |
5973 | // just be the return type of a block pointer. |
5974 | if (state.isProcessingDeclSpec()) { |
5975 | Declarator &D = state.getDeclarator(); |
5976 | if (maybeMovePastReturnType(D, D.getNumTypeObjects(), |
5977 | /*onlyBlockPointers=*/true)) |
5978 | return false; |
5979 | } |
5980 | } |
5981 | |
5982 | Sema &S = state.getSema(); |
5983 | SourceLocation AttrLoc = attr.getLoc(); |
5984 | if (AttrLoc.isMacroID()) |
5985 | AttrLoc = |
5986 | S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); |
5987 | |
5988 | if (!attr.isArgIdent(0)) { |
5989 | S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr |
5990 | << AANT_ArgumentString; |
5991 | attr.setInvalid(); |
5992 | return true; |
5993 | } |
5994 | |
5995 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; |
5996 | Qualifiers::ObjCLifetime lifetime; |
5997 | if (II->isStr("none")) |
5998 | lifetime = Qualifiers::OCL_ExplicitNone; |
5999 | else if (II->isStr("strong")) |
6000 | lifetime = Qualifiers::OCL_Strong; |
6001 | else if (II->isStr("weak")) |
6002 | lifetime = Qualifiers::OCL_Weak; |
6003 | else if (II->isStr("autoreleasing")) |
6004 | lifetime = Qualifiers::OCL_Autoreleasing; |
6005 | else { |
6006 | S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) |
6007 | << attr.getName() << II; |
6008 | attr.setInvalid(); |
6009 | return true; |
6010 | } |
6011 | |
6012 | // Just ignore lifetime attributes other than __weak and __unsafe_unretained |
6013 | // outside of ARC mode. |
6014 | if (!S.getLangOpts().ObjCAutoRefCount && |
6015 | lifetime != Qualifiers::OCL_Weak && |
6016 | lifetime != Qualifiers::OCL_ExplicitNone) { |
6017 | return true; |
6018 | } |
6019 | |
6020 | SplitQualType underlyingType = type.split(); |
6021 | |
6022 | // Check for redundant/conflicting ownership qualifiers. |
6023 | if (Qualifiers::ObjCLifetime previousLifetime |
6024 | = type.getQualifiers().getObjCLifetime()) { |
6025 | // If it's written directly, that's an error. |
6026 | if (hasDirectOwnershipQualifier(type)) { |
6027 | S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) |
6028 | << type; |
6029 | return true; |
6030 | } |
6031 | |
6032 | // Otherwise, if the qualifiers actually conflict, pull sugar off |
6033 | // and remove the ObjCLifetime qualifiers. |
6034 | if (previousLifetime != lifetime) { |
6035 | // It's possible to have multiple local ObjCLifetime qualifiers. We |
6036 | // can't stop after we reach a type that is directly qualified. |
6037 | const Type *prevTy = nullptr; |
6038 | while (!prevTy || prevTy != underlyingType.Ty) { |
6039 | prevTy = underlyingType.Ty; |
6040 | underlyingType = underlyingType.getSingleStepDesugaredType(); |
6041 | } |
6042 | underlyingType.Quals.removeObjCLifetime(); |
6043 | } |
6044 | } |
6045 | |
6046 | underlyingType.Quals.addObjCLifetime(lifetime); |
6047 | |
6048 | if (NonObjCPointer) { |
6049 | StringRef name = attr.getName()->getName(); |
6050 | switch (lifetime) { |
6051 | case Qualifiers::OCL_None: |
6052 | case Qualifiers::OCL_ExplicitNone: |
6053 | break; |
6054 | case Qualifiers::OCL_Strong: name = "__strong"; break; |
6055 | case Qualifiers::OCL_Weak: name = "__weak"; break; |
6056 | case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; |
6057 | } |
6058 | S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name |
6059 | << TDS_ObjCObjOrBlock << type; |
6060 | } |
6061 | |
6062 | // Don't actually add the __unsafe_unretained qualifier in non-ARC files, |
6063 | // because having both 'T' and '__unsafe_unretained T' exist in the type |
6064 | // system causes unfortunate widespread consistency problems. (For example, |
6065 | // they're not considered compatible types, and we mangle them identicially |
6066 | // as template arguments.) These problems are all individually fixable, |
6067 | // but it's easier to just not add the qualifier and instead sniff it out |
6068 | // in specific places using isObjCInertUnsafeUnretainedType(). |
6069 | // |
6070 | // Doing this does means we miss some trivial consistency checks that |
6071 | // would've triggered in ARC, but that's better than trying to solve all |
6072 | // the coexistence problems with __unsafe_unretained. |
6073 | if (!S.getLangOpts().ObjCAutoRefCount && |
6074 | lifetime == Qualifiers::OCL_ExplicitNone) { |
6075 | type = state.getAttributedType( |
6076 | createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), |
6077 | type, type); |
6078 | return true; |
6079 | } |
6080 | |
6081 | QualType origType = type; |
6082 | if (!NonObjCPointer) |
6083 | type = S.Context.getQualifiedType(underlyingType); |
6084 | |
6085 | // If we have a valid source location for the attribute, use an |
6086 | // AttributedType instead. |
6087 | if (AttrLoc.isValid()) { |
6088 | type = state.getAttributedType(::new (S.Context) ObjCOwnershipAttr( |
6089 | attr.getRange(), S.Context, II, |
6090 | attr.getAttributeSpellingListIndex()), |
6091 | origType, type); |
6092 | } |
6093 | |
6094 | auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, |
6095 | unsigned diagnostic, QualType type) { |
6096 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { |
6097 | S.DelayedDiagnostics.add( |
6098 | sema::DelayedDiagnostic::makeForbiddenType( |
6099 | S.getSourceManager().getExpansionLoc(loc), |
6100 | diagnostic, type, /*ignored*/ 0)); |
6101 | } else { |
6102 | S.Diag(loc, diagnostic); |
6103 | } |
6104 | }; |
6105 | |
6106 | // Sometimes, __weak isn't allowed. |
6107 | if (lifetime == Qualifiers::OCL_Weak && |
6108 | !S.getLangOpts().ObjCWeak && !NonObjCPointer) { |
6109 | |
6110 | // Use a specialized diagnostic if the runtime just doesn't support them. |
6111 | unsigned diagnostic = |
6112 | (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled |
6113 | : diag::err_arc_weak_no_runtime); |
6114 | |
6115 | // In any case, delay the diagnostic until we know what we're parsing. |
6116 | diagnoseOrDelay(S, AttrLoc, diagnostic, type); |
6117 | |
6118 | attr.setInvalid(); |
6119 | return true; |
6120 | } |
6121 | |
6122 | // Forbid __weak for class objects marked as |
6123 | // objc_arc_weak_reference_unavailable |
6124 | if (lifetime == Qualifiers::OCL_Weak) { |
6125 | if (const ObjCObjectPointerType *ObjT = |
6126 | type->getAs<ObjCObjectPointerType>()) { |
6127 | if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { |
6128 | if (Class->isArcWeakrefUnavailable()) { |
6129 | S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); |
6130 | S.Diag(ObjT->getInterfaceDecl()->getLocation(), |
6131 | diag::note_class_declared); |
6132 | } |
6133 | } |
6134 | } |
6135 | } |
6136 | |
6137 | return true; |
6138 | } |
6139 | |
6140 | /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type |
6141 | /// attribute on the specified type. Returns true to indicate that |
6142 | /// the attribute was handled, false to indicate that the type does |
6143 | /// not permit the attribute. |
6144 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, |
6145 | QualType &type) { |
6146 | Sema &S = state.getSema(); |
6147 | |
6148 | // Delay if this isn't some kind of pointer. |
6149 | if (!type->isPointerType() && |
6150 | !type->isObjCObjectPointerType() && |
6151 | !type->isBlockPointerType()) |
6152 | return false; |
6153 | |
6154 | if (type.getObjCGCAttr() != Qualifiers::GCNone) { |
6155 | S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); |
6156 | attr.setInvalid(); |
6157 | return true; |
6158 | } |
6159 | |
6160 | // Check the attribute arguments. |
6161 | if (!attr.isArgIdent(0)) { |
6162 | S.Diag(attr.getLoc(), diag::err_attribute_argument_type) |
6163 | << attr << AANT_ArgumentString; |
6164 | attr.setInvalid(); |
6165 | return true; |
6166 | } |
6167 | Qualifiers::GC GCAttr; |
6168 | if (attr.getNumArgs() > 1) { |
6169 | S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr |
6170 | << 1; |
6171 | attr.setInvalid(); |
6172 | return true; |
6173 | } |
6174 | |
6175 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; |
6176 | if (II->isStr("weak")) |
6177 | GCAttr = Qualifiers::Weak; |
6178 | else if (II->isStr("strong")) |
6179 | GCAttr = Qualifiers::Strong; |
6180 | else { |
6181 | S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) |
6182 | << attr.getName() << II; |
6183 | attr.setInvalid(); |
6184 | return true; |
6185 | } |
6186 | |
6187 | QualType origType = type; |
6188 | type = S.Context.getObjCGCQualType(origType, GCAttr); |
6189 | |
6190 | // Make an attributed type to preserve the source information. |
6191 | if (attr.getLoc().isValid()) |
6192 | type = state.getAttributedType( |
6193 | ::new (S.Context) ObjCGCAttr(attr.getRange(), S.Context, II, |
6194 | attr.getAttributeSpellingListIndex()), |
6195 | origType, type); |
6196 | |
6197 | return true; |
6198 | } |
6199 | |
6200 | namespace { |
6201 | /// A helper class to unwrap a type down to a function for the |
6202 | /// purposes of applying attributes there. |
6203 | /// |
6204 | /// Use: |
6205 | /// FunctionTypeUnwrapper unwrapped(SemaRef, T); |
6206 | /// if (unwrapped.isFunctionType()) { |
6207 | /// const FunctionType *fn = unwrapped.get(); |
6208 | /// // change fn somehow |
6209 | /// T = unwrapped.wrap(fn); |
6210 | /// } |
6211 | struct FunctionTypeUnwrapper { |
6212 | enum WrapKind { |
6213 | Desugar, |
6214 | Attributed, |
6215 | Parens, |
6216 | Pointer, |
6217 | BlockPointer, |
6218 | Reference, |
6219 | MemberPointer |
6220 | }; |
6221 | |
6222 | QualType Original; |
6223 | const FunctionType *Fn; |
6224 | SmallVector<unsigned char /*WrapKind*/, 8> Stack; |
6225 | |
6226 | FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { |
6227 | while (true) { |
6228 | const Type *Ty = T.getTypePtr(); |
6229 | if (isa<FunctionType>(Ty)) { |
6230 | Fn = cast<FunctionType>(Ty); |
6231 | return; |
6232 | } else if (isa<ParenType>(Ty)) { |
6233 | T = cast<ParenType>(Ty)->getInnerType(); |
6234 | Stack.push_back(Parens); |
6235 | } else if (isa<PointerType>(Ty)) { |
6236 | T = cast<PointerType>(Ty)->getPointeeType(); |
6237 | Stack.push_back(Pointer); |
6238 | } else if (isa<BlockPointerType>(Ty)) { |
6239 | T = cast<BlockPointerType>(Ty)->getPointeeType(); |
6240 | Stack.push_back(BlockPointer); |
6241 | } else if (isa<MemberPointerType>(Ty)) { |
6242 | T = cast<MemberPointerType>(Ty)->getPointeeType(); |
6243 | Stack.push_back(MemberPointer); |
6244 | } else if (isa<ReferenceType>(Ty)) { |
6245 | T = cast<ReferenceType>(Ty)->getPointeeType(); |
6246 | Stack.push_back(Reference); |
6247 | } else if (isa<AttributedType>(Ty)) { |
6248 | T = cast<AttributedType>(Ty)->getEquivalentType(); |
6249 | Stack.push_back(Attributed); |
6250 | } else { |
6251 | const Type *DTy = Ty->getUnqualifiedDesugaredType(); |
6252 | if (Ty == DTy) { |
6253 | Fn = nullptr; |
6254 | return; |
6255 | } |
6256 | |
6257 | T = QualType(DTy, 0); |
6258 | Stack.push_back(Desugar); |
6259 | } |
6260 | } |
6261 | } |
6262 | |
6263 | bool isFunctionType() const { return (Fn != nullptr); } |
6264 | const FunctionType *get() const { return Fn; } |
6265 | |
6266 | QualType wrap(Sema &S, const FunctionType *New) { |
6267 | // If T wasn't modified from the unwrapped type, do nothing. |
6268 | if (New == get()) return Original; |
6269 | |
6270 | Fn = New; |
6271 | return wrap(S.Context, Original, 0); |
6272 | } |
6273 | |
6274 | private: |
6275 | QualType wrap(ASTContext &C, QualType Old, unsigned I) { |
6276 | if (I == Stack.size()) |
6277 | return C.getQualifiedType(Fn, Old.getQualifiers()); |
6278 | |
6279 | // Build up the inner type, applying the qualifiers from the old |
6280 | // type to the new type. |
6281 | SplitQualType SplitOld = Old.split(); |
6282 | |
6283 | // As a special case, tail-recurse if there are no qualifiers. |
6284 | if (SplitOld.Quals.empty()) |
6285 | return wrap(C, SplitOld.Ty, I); |
6286 | return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); |
6287 | } |
6288 | |
6289 | QualType wrap(ASTContext &C, const Type *Old, unsigned I) { |
6290 | if (I == Stack.size()) return QualType(Fn, 0); |
6291 | |
6292 | switch (static_cast<WrapKind>(Stack[I++])) { |
6293 | case Desugar: |
6294 | // This is the point at which we potentially lose source |
6295 | // information. |
6296 | return wrap(C, Old->getUnqualifiedDesugaredType(), I); |
6297 | |
6298 | case Attributed: |
6299 | return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); |
6300 | |
6301 | case Parens: { |
6302 | QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); |
6303 | return C.getParenType(New); |
6304 | } |
6305 | |
6306 | case Pointer: { |
6307 | QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); |
6308 | return C.getPointerType(New); |
6309 | } |
6310 | |
6311 | case BlockPointer: { |
6312 | QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); |
6313 | return C.getBlockPointerType(New); |
6314 | } |
6315 | |
6316 | case MemberPointer: { |
6317 | const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); |
6318 | QualType New = wrap(C, OldMPT->getPointeeType(), I); |
6319 | return C.getMemberPointerType(New, OldMPT->getClass()); |
6320 | } |
6321 | |
6322 | case Reference: { |
6323 | const ReferenceType *OldRef = cast<ReferenceType>(Old); |
6324 | QualType New = wrap(C, OldRef->getPointeeType(), I); |
6325 | if (isa<LValueReferenceType>(OldRef)) |
6326 | return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); |
6327 | else |
6328 | return C.getRValueReferenceType(New); |
6329 | } |
6330 | } |
6331 | |
6332 | llvm_unreachable("unknown wrapping kind")::llvm::llvm_unreachable_internal("unknown wrapping kind", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 6332); |
6333 | } |
6334 | }; |
6335 | } // end anonymous namespace |
6336 | |
6337 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, |
6338 | ParsedAttr &PAttr, QualType &Type) { |
6339 | Sema &S = State.getSema(); |
6340 | |
6341 | Attr *A; |
6342 | switch (PAttr.getKind()) { |
6343 | default: llvm_unreachable("Unknown attribute kind")::llvm::llvm_unreachable_internal("Unknown attribute kind", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 6343); |
6344 | case ParsedAttr::AT_Ptr32: |
6345 | A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); |
6346 | break; |
6347 | case ParsedAttr::AT_Ptr64: |
6348 | A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); |
6349 | break; |
6350 | case ParsedAttr::AT_SPtr: |
6351 | A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); |
6352 | break; |
6353 | case ParsedAttr::AT_UPtr: |
6354 | A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); |
6355 | break; |
6356 | } |
6357 | |
6358 | attr::Kind NewAttrKind = A->getKind(); |
6359 | QualType Desugared = Type; |
6360 | const AttributedType *AT = dyn_cast<AttributedType>(Type); |
6361 | while (AT) { |
6362 | attr::Kind CurAttrKind = AT->getAttrKind(); |
6363 | |
6364 | // You cannot specify duplicate type attributes, so if the attribute has |
6365 | // already been applied, flag it. |
6366 | if (NewAttrKind == CurAttrKind) { |
6367 | S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) |
6368 | << PAttr.getName(); |
6369 | return true; |
6370 | } |
6371 | |
6372 | // You cannot have both __sptr and __uptr on the same type, nor can you |
6373 | // have __ptr32 and __ptr64. |
6374 | if ((CurAttrKind == attr::Ptr32 && NewAttrKind == attr::Ptr64) || |
6375 | (CurAttrKind == attr::Ptr64 && NewAttrKind == attr::Ptr32)) { |
6376 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) |
6377 | << "'__ptr32'" << "'__ptr64'"; |
6378 | return true; |
6379 | } else if ((CurAttrKind == attr::SPtr && NewAttrKind == attr::UPtr) || |
6380 | (CurAttrKind == attr::UPtr && NewAttrKind == attr::SPtr)) { |
6381 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) |
6382 | << "'__sptr'" << "'__uptr'"; |
6383 | return true; |
6384 | } |
6385 | |
6386 | Desugared = AT->getEquivalentType(); |
6387 | AT = dyn_cast<AttributedType>(Desugared); |
6388 | } |
6389 | |
6390 | // Pointer type qualifiers can only operate on pointer types, but not |
6391 | // pointer-to-member types. |
6392 | // |
6393 | // FIXME: Should we really be disallowing this attribute if there is any |
6394 | // type sugar between it and the pointer (other than attributes)? Eg, this |
6395 | // disallows the attribute on a parenthesized pointer. |
6396 | // And if so, should we really allow *any* type attribute? |
6397 | if (!isa<PointerType>(Desugared)) { |
6398 | if (Type->isMemberPointerType()) |
6399 | S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; |
6400 | else |
6401 | S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; |
6402 | return true; |
6403 | } |
6404 | |
6405 | Type = State.getAttributedType(A, Type, Type); |
6406 | return false; |
6407 | } |
6408 | |
6409 | /// Map a nullability attribute kind to a nullability kind. |
6410 | static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { |
6411 | switch (kind) { |
6412 | case ParsedAttr::AT_TypeNonNull: |
6413 | return NullabilityKind::NonNull; |
6414 | |
6415 | case ParsedAttr::AT_TypeNullable: |
6416 | return NullabilityKind::Nullable; |
6417 | |
6418 | case ParsedAttr::AT_TypeNullUnspecified: |
6419 | return NullabilityKind::Unspecified; |
6420 | |
6421 | default: |
6422 | llvm_unreachable("not a nullability attribute kind")::llvm::llvm_unreachable_internal("not a nullability attribute kind" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 6422); |
6423 | } |
6424 | } |
6425 | |
6426 | /// Applies a nullability type specifier to the given type, if possible. |
6427 | /// |
6428 | /// \param state The type processing state. |
6429 | /// |
6430 | /// \param type The type to which the nullability specifier will be |
6431 | /// added. On success, this type will be updated appropriately. |
6432 | /// |
6433 | /// \param attr The attribute as written on the type. |
6434 | /// |
6435 | /// \param allowOnArrayType Whether to accept nullability specifiers on an |
6436 | /// array type (e.g., because it will decay to a pointer). |
6437 | /// |
6438 | /// \returns true if a problem has been diagnosed, false on success. |
6439 | static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, |
6440 | QualType &type, |
6441 | ParsedAttr &attr, |
6442 | bool allowOnArrayType) { |
6443 | Sema &S = state.getSema(); |
6444 | |
6445 | NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); |
6446 | SourceLocation nullabilityLoc = attr.getLoc(); |
6447 | bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); |
6448 | |
6449 | recordNullabilitySeen(S, nullabilityLoc); |
6450 | |
6451 | // Check for existing nullability attributes on the type. |
6452 | QualType desugared = type; |
6453 | while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { |
6454 | // Check whether there is already a null |
6455 | if (auto existingNullability = attributed->getImmediateNullability()) { |
6456 | // Duplicated nullability. |
6457 | if (nullability == *existingNullability) { |
6458 | S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) |
6459 | << DiagNullabilityKind(nullability, isContextSensitive) |
6460 | << FixItHint::CreateRemoval(nullabilityLoc); |
6461 | |
6462 | break; |
6463 | } |
6464 | |
6465 | // Conflicting nullability. |
6466 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) |
6467 | << DiagNullabilityKind(nullability, isContextSensitive) |
6468 | << DiagNullabilityKind(*existingNullability, false); |
6469 | return true; |
6470 | } |
6471 | |
6472 | desugared = attributed->getModifiedType(); |
6473 | } |
6474 | |
6475 | // If there is already a different nullability specifier, complain. |
6476 | // This (unlike the code above) looks through typedefs that might |
6477 | // have nullability specifiers on them, which means we cannot |
6478 | // provide a useful Fix-It. |
6479 | if (auto existingNullability = desugared->getNullability(S.Context)) { |
6480 | if (nullability != *existingNullability) { |
6481 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) |
6482 | << DiagNullabilityKind(nullability, isContextSensitive) |
6483 | << DiagNullabilityKind(*existingNullability, false); |
6484 | |
6485 | // Try to find the typedef with the existing nullability specifier. |
6486 | if (auto typedefType = desugared->getAs<TypedefType>()) { |
6487 | TypedefNameDecl *typedefDecl = typedefType->getDecl(); |
6488 | QualType underlyingType = typedefDecl->getUnderlyingType(); |
6489 | if (auto typedefNullability |
6490 | = AttributedType::stripOuterNullability(underlyingType)) { |
6491 | if (*typedefNullability == *existingNullability) { |
6492 | S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) |
6493 | << DiagNullabilityKind(*existingNullability, false); |
6494 | } |
6495 | } |
6496 | } |
6497 | |
6498 | return true; |
6499 | } |
6500 | } |
6501 | |
6502 | // If this definitely isn't a pointer type, reject the specifier. |
6503 | if (!desugared->canHaveNullability() && |
6504 | !(allowOnArrayType && desugared->isArrayType())) { |
6505 | S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) |
6506 | << DiagNullabilityKind(nullability, isContextSensitive) << type; |
6507 | return true; |
6508 | } |
6509 | |
6510 | // For the context-sensitive keywords/Objective-C property |
6511 | // attributes, require that the type be a single-level pointer. |
6512 | if (isContextSensitive) { |
6513 | // Make sure that the pointee isn't itself a pointer type. |
6514 | const Type *pointeeType; |
6515 | if (desugared->isArrayType()) |
6516 | pointeeType = desugared->getArrayElementTypeNoTypeQual(); |
6517 | else |
6518 | pointeeType = desugared->getPointeeType().getTypePtr(); |
6519 | |
6520 | if (pointeeType->isAnyPointerType() || |
6521 | pointeeType->isObjCObjectPointerType() || |
6522 | pointeeType->isMemberPointerType()) { |
6523 | S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) |
6524 | << DiagNullabilityKind(nullability, true) |
6525 | << type; |
6526 | S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) |
6527 | << DiagNullabilityKind(nullability, false) |
6528 | << type |
6529 | << FixItHint::CreateReplacement(nullabilityLoc, |
6530 | getNullabilitySpelling(nullability)); |
6531 | return true; |
6532 | } |
6533 | } |
6534 | |
6535 | // Form the attributed type. |
6536 | type = state.getAttributedType( |
6537 | createNullabilityAttr(S.Context, attr, nullability), type, type); |
6538 | return false; |
6539 | } |
6540 | |
6541 | /// Check the application of the Objective-C '__kindof' qualifier to |
6542 | /// the given type. |
6543 | static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, |
6544 | ParsedAttr &attr) { |
6545 | Sema &S = state.getSema(); |
6546 | |
6547 | if (isa<ObjCTypeParamType>(type)) { |
6548 | // Build the attributed type to record where __kindof occurred. |
6549 | type = state.getAttributedType( |
6550 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); |
6551 | return false; |
6552 | } |
6553 | |
6554 | // Find out if it's an Objective-C object or object pointer type; |
6555 | const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); |
6556 | const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() |
6557 | : type->getAs<ObjCObjectType>(); |
6558 | |
6559 | // If not, we can't apply __kindof. |
6560 | if (!objType) { |
6561 | // FIXME: Handle dependent types that aren't yet object types. |
6562 | S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) |
6563 | << type; |
6564 | return true; |
6565 | } |
6566 | |
6567 | // Rebuild the "equivalent" type, which pushes __kindof down into |
6568 | // the object type. |
6569 | // There is no need to apply kindof on an unqualified id type. |
6570 | QualType equivType = S.Context.getObjCObjectType( |
6571 | objType->getBaseType(), objType->getTypeArgsAsWritten(), |
6572 | objType->getProtocols(), |
6573 | /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); |
6574 | |
6575 | // If we started with an object pointer type, rebuild it. |
6576 | if (ptrType) { |
6577 | equivType = S.Context.getObjCObjectPointerType(equivType); |
6578 | if (auto nullability = type->getNullability(S.Context)) { |
6579 | // We create a nullability attribute from the __kindof attribute. |
6580 | // Make sure that will make sense. |
6581 | assert(attr.getAttributeSpellingListIndex() == 0 &&((attr.getAttributeSpellingListIndex() == 0 && "multiple spellings for __kindof?" ) ? static_cast<void> (0) : __assert_fail ("attr.getAttributeSpellingListIndex() == 0 && \"multiple spellings for __kindof?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 6582, __PRETTY_FUNCTION__)) |
6582 | "multiple spellings for __kindof?")((attr.getAttributeSpellingListIndex() == 0 && "multiple spellings for __kindof?" ) ? static_cast<void> (0) : __assert_fail ("attr.getAttributeSpellingListIndex() == 0 && \"multiple spellings for __kindof?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 6582, __PRETTY_FUNCTION__)); |
6583 | Attr *A = createNullabilityAttr(S.Context, attr, *nullability); |
6584 | A->setImplicit(true); |
6585 | equivType = state.getAttributedType(A, equivType, equivType); |
6586 | } |
6587 | } |
6588 | |
6589 | // Build the attributed type to record where __kindof occurred. |
6590 | type = state.getAttributedType( |
6591 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); |
6592 | return false; |
6593 | } |
6594 | |
6595 | /// Distribute a nullability type attribute that cannot be applied to |
6596 | /// the type specifier to a pointer, block pointer, or member pointer |
6597 | /// declarator, complaining if necessary. |
6598 | /// |
6599 | /// \returns true if the nullability annotation was distributed, false |
6600 | /// otherwise. |
6601 | static bool distributeNullabilityTypeAttr(TypeProcessingState &state, |
6602 | QualType type, ParsedAttr &attr) { |
6603 | Declarator &declarator = state.getDeclarator(); |
6604 | |
6605 | /// Attempt to move the attribute to the specified chunk. |
6606 | auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { |
6607 | // If there is already a nullability attribute there, don't add |
6608 | // one. |
6609 | if (hasNullabilityAttr(chunk.getAttrs())) |
6610 | return false; |
6611 | |
6612 | // Complain about the nullability qualifier being in the wrong |
6613 | // place. |
6614 | enum { |
6615 | PK_Pointer, |
6616 | PK_BlockPointer, |
6617 | PK_MemberPointer, |
6618 | PK_FunctionPointer, |
6619 | PK_MemberFunctionPointer, |
6620 | } pointerKind |
6621 | = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer |
6622 | : PK_Pointer) |
6623 | : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer |
6624 | : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; |
6625 | |
6626 | auto diag = state.getSema().Diag(attr.getLoc(), |
6627 | diag::warn_nullability_declspec) |
6628 | << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), |
6629 | attr.isContextSensitiveKeywordAttribute()) |
6630 | << type |
6631 | << static_cast<unsigned>(pointerKind); |
6632 | |
6633 | // FIXME: MemberPointer chunks don't carry the location of the *. |
6634 | if (chunk.Kind != DeclaratorChunk::MemberPointer) { |
6635 | diag << FixItHint::CreateRemoval(attr.getLoc()) |
6636 | << FixItHint::CreateInsertion( |
6637 | state.getSema().getPreprocessor() |
6638 | .getLocForEndOfToken(chunk.Loc), |
6639 | " " + attr.getName()->getName().str() + " "); |
6640 | } |
6641 | |
6642 | moveAttrFromListToList(attr, state.getCurrentAttributes(), |
6643 | chunk.getAttrs()); |
6644 | return true; |
6645 | }; |
6646 | |
6647 | // Move it to the outermost pointer, member pointer, or block |
6648 | // pointer declarator. |
6649 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { |
6650 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); |
6651 | switch (chunk.Kind) { |
6652 | case DeclaratorChunk::Pointer: |
6653 | case DeclaratorChunk::BlockPointer: |
6654 | case DeclaratorChunk::MemberPointer: |
6655 | return moveToChunk(chunk, false); |
6656 | |
6657 | case DeclaratorChunk::Paren: |
6658 | case DeclaratorChunk::Array: |
6659 | continue; |
6660 | |
6661 | case DeclaratorChunk::Function: |
6662 | // Try to move past the return type to a function/block/member |
6663 | // function pointer. |
6664 | if (DeclaratorChunk *dest = maybeMovePastReturnType( |
6665 | declarator, i, |
6666 | /*onlyBlockPointers=*/false)) { |
6667 | return moveToChunk(*dest, true); |
6668 | } |
6669 | |
6670 | return false; |
6671 | |
6672 | // Don't walk through these. |
6673 | case DeclaratorChunk::Reference: |
6674 | case DeclaratorChunk::Pipe: |
6675 | return false; |
6676 | } |
6677 | } |
6678 | |
6679 | return false; |
6680 | } |
6681 | |
6682 | static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { |
6683 | assert(!Attr.isInvalid())((!Attr.isInvalid()) ? static_cast<void> (0) : __assert_fail ("!Attr.isInvalid()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 6683, __PRETTY_FUNCTION__)); |
6684 | switch (Attr.getKind()) { |
6685 | default: |
6686 | llvm_unreachable("not a calling convention attribute")::llvm::llvm_unreachable_internal("not a calling convention attribute" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 6686); |
6687 | case ParsedAttr::AT_CDecl: |
6688 | return createSimpleAttr<CDeclAttr>(Ctx, Attr); |
6689 | case ParsedAttr::AT_FastCall: |
6690 | return createSimpleAttr<FastCallAttr>(Ctx, Attr); |
6691 | case ParsedAttr::AT_StdCall: |
6692 | return createSimpleAttr<StdCallAttr>(Ctx, Attr); |
6693 | case ParsedAttr::AT_ThisCall: |
6694 | return createSimpleAttr<ThisCallAttr>(Ctx, Attr); |
6695 | case ParsedAttr::AT_RegCall: |
6696 | return createSimpleAttr<RegCallAttr>(Ctx, Attr); |
6697 | case ParsedAttr::AT_Pascal: |
6698 | return createSimpleAttr<PascalAttr>(Ctx, Attr); |
6699 | case ParsedAttr::AT_SwiftCall: |
6700 | return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); |
6701 | case ParsedAttr::AT_VectorCall: |
6702 | return createSimpleAttr<VectorCallAttr>(Ctx, Attr); |
6703 | case ParsedAttr::AT_AArch64VectorPcs: |
6704 | return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); |
6705 | case ParsedAttr::AT_Pcs: { |
6706 | // The attribute may have had a fixit applied where we treated an |
6707 | // identifier as a string literal. The contents of the string are valid, |
6708 | // but the form may not be. |
6709 | StringRef Str; |
6710 | if (Attr.isArgExpr(0)) |
6711 | Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); |
6712 | else |
6713 | Str = Attr.getArgAsIdent(0)->Ident->getName(); |
6714 | PcsAttr::PCSType Type; |
6715 | if (!PcsAttr::ConvertStrToPCSType(Str, Type)) |
6716 | llvm_unreachable("already validated the attribute")::llvm::llvm_unreachable_internal("already validated the attribute" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 6716); |
6717 | return ::new (Ctx) PcsAttr(Attr.getRange(), Ctx, Type, |
6718 | Attr.getAttributeSpellingListIndex()); |
6719 | } |
6720 | case ParsedAttr::AT_IntelOclBicc: |
6721 | return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); |
6722 | case ParsedAttr::AT_MSABI: |
6723 | return createSimpleAttr<MSABIAttr>(Ctx, Attr); |
6724 | case ParsedAttr::AT_SysVABI: |
6725 | return createSimpleAttr<SysVABIAttr>(Ctx, Attr); |
6726 | case ParsedAttr::AT_PreserveMost: |
6727 | return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); |
6728 | case ParsedAttr::AT_PreserveAll: |
6729 | return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); |
6730 | } |
6731 | llvm_unreachable("unexpected attribute kind!")::llvm::llvm_unreachable_internal("unexpected attribute kind!" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 6731); |
6732 | } |
6733 | |
6734 | /// Process an individual function attribute. Returns true to |
6735 | /// indicate that the attribute was handled, false if it wasn't. |
6736 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, |
6737 | QualType &type) { |
6738 | Sema &S = state.getSema(); |
6739 | |
6740 | FunctionTypeUnwrapper unwrapped(S, type); |
6741 | |
6742 | if (attr.getKind() == ParsedAttr::AT_NoReturn) { |
6743 | if (S.CheckAttrNoArgs(attr)) |
6744 | return true; |
6745 | |
6746 | // Delay if this is not a function type. |
6747 | if (!unwrapped.isFunctionType()) |
6748 | return false; |
6749 | |
6750 | // Otherwise we can process right away. |
6751 | FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); |
6752 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); |
6753 | return true; |
6754 | } |
6755 | |
6756 | // ns_returns_retained is not always a type attribute, but if we got |
6757 | // here, we're treating it as one right now. |
6758 | if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { |
6759 | if (attr.getNumArgs()) return true; |
6760 | |
6761 | // Delay if this is not a function type. |
6762 | if (!unwrapped.isFunctionType()) |
6763 | return false; |
6764 | |
6765 | // Check whether the return type is reasonable. |
6766 | if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), |
6767 | unwrapped.get()->getReturnType())) |
6768 | return true; |
6769 | |
6770 | // Only actually change the underlying type in ARC builds. |
6771 | QualType origType = type; |
6772 | if (state.getSema().getLangOpts().ObjCAutoRefCount) { |
6773 | FunctionType::ExtInfo EI |
6774 | = unwrapped.get()->getExtInfo().withProducesResult(true); |
6775 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); |
6776 | } |
6777 | type = state.getAttributedType( |
6778 | createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), |
6779 | origType, type); |
6780 | return true; |
6781 | } |
6782 | |
6783 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { |
6784 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) |
6785 | return true; |
6786 | |
6787 | // Delay if this is not a function type. |
6788 | if (!unwrapped.isFunctionType()) |
6789 | return false; |
6790 | |
6791 | FunctionType::ExtInfo EI = |
6792 | unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); |
6793 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); |
6794 | return true; |
6795 | } |
6796 | |
6797 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { |
6798 | if (!S.getLangOpts().CFProtectionBranch) { |
6799 | S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); |
6800 | attr.setInvalid(); |
6801 | return true; |
6802 | } |
6803 | |
6804 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) |
6805 | return true; |
6806 | |
6807 | // If this is not a function type, warning will be asserted by subject |
6808 | // check. |
6809 | if (!unwrapped.isFunctionType()) |
6810 | return true; |
6811 | |
6812 | FunctionType::ExtInfo EI = |
6813 | unwrapped.get()->getExtInfo().withNoCfCheck(true); |
6814 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); |
6815 | return true; |
6816 | } |
6817 | |
6818 | if (attr.getKind() == ParsedAttr::AT_Regparm) { |
6819 | unsigned value; |
6820 | if (S.CheckRegparmAttr(attr, value)) |
6821 | return true; |
6822 | |
6823 | // Delay if this is not a function type. |
6824 | if (!unwrapped.isFunctionType()) |
6825 | return false; |
6826 | |
6827 | // Diagnose regparm with fastcall. |
6828 | const FunctionType *fn = unwrapped.get(); |
6829 | CallingConv CC = fn->getCallConv(); |
6830 | if (CC == CC_X86FastCall) { |
6831 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) |
6832 | << FunctionType::getNameForCallConv(CC) |
6833 | << "regparm"; |
6834 | attr.setInvalid(); |
6835 | return true; |
6836 | } |
6837 | |
6838 | FunctionType::ExtInfo EI = |
6839 | unwrapped.get()->getExtInfo().withRegParm(value); |
6840 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); |
6841 | return true; |
6842 | } |
6843 | |
6844 | // Delay if the type didn't work out to a function. |
6845 | if (!unwrapped.isFunctionType()) return false; |
6846 | |
6847 | // Otherwise, a calling convention. |
6848 | CallingConv CC; |
6849 | if (S.CheckCallingConvAttr(attr, CC)) |
6850 | return true; |
6851 | |
6852 | const FunctionType *fn = unwrapped.get(); |
6853 | CallingConv CCOld = fn->getCallConv(); |
6854 | Attr *CCAttr = getCCTypeAttr(S.Context, attr); |
6855 | |
6856 | if (CCOld != CC) { |
6857 | // Error out on when there's already an attribute on the type |
6858 | // and the CCs don't match. |
6859 | if (S.getCallingConvAttributedType(type)) { |
6860 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) |
6861 | << FunctionType::getNameForCallConv(CC) |
6862 | << FunctionType::getNameForCallConv(CCOld); |
6863 | attr.setInvalid(); |
6864 | return true; |
6865 | } |
6866 | } |
6867 | |
6868 | // Diagnose use of variadic functions with calling conventions that |
6869 | // don't support them (e.g. because they're callee-cleanup). |
6870 | // We delay warning about this on unprototyped function declarations |
6871 | // until after redeclaration checking, just in case we pick up a |
6872 | // prototype that way. And apparently we also "delay" warning about |
6873 | // unprototyped function types in general, despite not necessarily having |
6874 | // much ability to diagnose it later. |
6875 | if (!supportsVariadicCall(CC)) { |
6876 | const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); |
6877 | if (FnP && FnP->isVariadic()) { |
6878 | unsigned DiagID = diag::err_cconv_varargs; |
6879 | |
6880 | // stdcall and fastcall are ignored with a warning for GCC and MS |
6881 | // compatibility. |
6882 | bool IsInvalid = true; |
6883 | if (CC == CC_X86StdCall || CC == CC_X86FastCall) { |
6884 | DiagID = diag::warn_cconv_varargs; |
6885 | IsInvalid = false; |
6886 | } |
6887 | |
6888 | S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); |
6889 | if (IsInvalid) attr.setInvalid(); |
6890 | return true; |
6891 | } |
6892 | } |
6893 | |
6894 | // Also diagnose fastcall with regparm. |
6895 | if (CC == CC_X86FastCall && fn->getHasRegParm()) { |
6896 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) |
6897 | << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); |
6898 | attr.setInvalid(); |
6899 | return true; |
6900 | } |
6901 | |
6902 | // Modify the CC from the wrapped function type, wrap it all back, and then |
6903 | // wrap the whole thing in an AttributedType as written. The modified type |
6904 | // might have a different CC if we ignored the attribute. |
6905 | QualType Equivalent; |
6906 | if (CCOld == CC) { |
6907 | Equivalent = type; |
6908 | } else { |
6909 | auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); |
6910 | Equivalent = |
6911 | unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); |
6912 | } |
6913 | type = state.getAttributedType(CCAttr, type, Equivalent); |
6914 | return true; |
6915 | } |
6916 | |
6917 | bool Sema::hasExplicitCallingConv(QualType &T) { |
6918 | QualType R = T.IgnoreParens(); |
6919 | while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { |
6920 | if (AT->isCallingConv()) |
6921 | return true; |
6922 | R = AT->getModifiedType().IgnoreParens(); |
6923 | } |
6924 | return false; |
6925 | } |
6926 | |
6927 | void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, |
6928 | SourceLocation Loc) { |
6929 | FunctionTypeUnwrapper Unwrapped(*this, T); |
6930 | const FunctionType *FT = Unwrapped.get(); |
6931 | bool IsVariadic = (isa<FunctionProtoType>(FT) && |
6932 | cast<FunctionProtoType>(FT)->isVariadic()); |
6933 | CallingConv CurCC = FT->getCallConv(); |
6934 | CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); |
6935 | |
6936 | if (CurCC == ToCC) |
6937 | return; |
6938 | |
6939 | // MS compiler ignores explicit calling convention attributes on structors. We |
6940 | // should do the same. |
6941 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { |
6942 | // Issue a warning on ignored calling convention -- except of __stdcall. |
6943 | // Again, this is what MS compiler does. |
6944 | if (CurCC != CC_X86StdCall) |
6945 | Diag(Loc, diag::warn_cconv_structors) |
6946 | << FunctionType::getNameForCallConv(CurCC); |
6947 | // Default adjustment. |
6948 | } else { |
6949 | // Only adjust types with the default convention. For example, on Windows |
6950 | // we should adjust a __cdecl type to __thiscall for instance methods, and a |
6951 | // __thiscall type to __cdecl for static methods. |
6952 | CallingConv DefaultCC = |
6953 | Context.getDefaultCallingConvention(IsVariadic, IsStatic); |
6954 | |
6955 | if (CurCC != DefaultCC || DefaultCC == ToCC) |
6956 | return; |
6957 | |
6958 | if (hasExplicitCallingConv(T)) |
6959 | return; |
6960 | } |
6961 | |
6962 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); |
6963 | QualType Wrapped = Unwrapped.wrap(*this, FT); |
6964 | T = Context.getAdjustedType(T, Wrapped); |
6965 | } |
6966 | |
6967 | /// HandleVectorSizeAttribute - this attribute is only applicable to integral |
6968 | /// and float scalars, although arrays, pointers, and function return values are |
6969 | /// allowed in conjunction with this construct. Aggregates with this attribute |
6970 | /// are invalid, even if they are of the same size as a corresponding scalar. |
6971 | /// The raw attribute should contain precisely 1 argument, the vector size for |
6972 | /// the variable, measured in bytes. If curType and rawAttr are well formed, |
6973 | /// this routine will return a new vector type. |
6974 | static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, |
6975 | Sema &S) { |
6976 | // Check the attribute arguments. |
6977 | if (Attr.getNumArgs() != 1) { |
6978 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr |
6979 | << 1; |
6980 | Attr.setInvalid(); |
6981 | return; |
6982 | } |
6983 | |
6984 | Expr *SizeExpr; |
6985 | // Special case where the argument is a template id. |
6986 | if (Attr.isArgIdent(0)) { |
6987 | CXXScopeSpec SS; |
6988 | SourceLocation TemplateKWLoc; |
6989 | UnqualifiedId Id; |
6990 | Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); |
6991 | |
6992 | ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, |
6993 | Id, false, false); |
6994 | |
6995 | if (Size.isInvalid()) |
6996 | return; |
6997 | SizeExpr = Size.get(); |
6998 | } else { |
6999 | SizeExpr = Attr.getArgAsExpr(0); |
7000 | } |
7001 | |
7002 | QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); |
7003 | if (!T.isNull()) |
7004 | CurType = T; |
7005 | else |
7006 | Attr.setInvalid(); |
7007 | } |
7008 | |
7009 | /// Process the OpenCL-like ext_vector_type attribute when it occurs on |
7010 | /// a type. |
7011 | static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, |
7012 | Sema &S) { |
7013 | // check the attribute arguments. |
7014 | if (Attr.getNumArgs() != 1) { |
7015 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr |
7016 | << 1; |
7017 | return; |
7018 | } |
7019 | |
7020 | Expr *sizeExpr; |
7021 | |
7022 | // Special case where the argument is a template id. |
7023 | if (Attr.isArgIdent(0)) { |
7024 | CXXScopeSpec SS; |
7025 | SourceLocation TemplateKWLoc; |
7026 | UnqualifiedId id; |
7027 | id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); |
7028 | |
7029 | ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, |
7030 | id, false, false); |
7031 | if (Size.isInvalid()) |
7032 | return; |
7033 | |
7034 | sizeExpr = Size.get(); |
7035 | } else { |
7036 | sizeExpr = Attr.getArgAsExpr(0); |
7037 | } |
7038 | |
7039 | // Create the vector type. |
7040 | QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); |
7041 | if (!T.isNull()) |
7042 | CurType = T; |
7043 | } |
7044 | |
7045 | static bool isPermittedNeonBaseType(QualType &Ty, |
7046 | VectorType::VectorKind VecKind, Sema &S) { |
7047 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); |
7048 | if (!BTy) |
7049 | return false; |
7050 | |
7051 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); |
7052 | |
7053 | // Signed poly is mathematically wrong, but has been baked into some ABIs by |
7054 | // now. |
7055 | bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || |
7056 | Triple.getArch() == llvm::Triple::aarch64_be; |
7057 | if (VecKind == VectorType::NeonPolyVector) { |
7058 | if (IsPolyUnsigned) { |
7059 | // AArch64 polynomial vectors are unsigned and support poly64. |
7060 | return BTy->getKind() == BuiltinType::UChar || |
7061 | BTy->getKind() == BuiltinType::UShort || |
7062 | BTy->getKind() == BuiltinType::ULong || |
7063 | BTy->getKind() == BuiltinType::ULongLong; |
7064 | } else { |
7065 | // AArch32 polynomial vector are signed. |
7066 | return BTy->getKind() == BuiltinType::SChar || |
7067 | BTy->getKind() == BuiltinType::Short; |
7068 | } |
7069 | } |
7070 | |
7071 | // Non-polynomial vector types: the usual suspects are allowed, as well as |
7072 | // float64_t on AArch64. |
7073 | bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || |
7074 | Triple.getArch() == llvm::Triple::aarch64_be; |
7075 | |
7076 | if (Is64Bit && BTy->getKind() == BuiltinType::Double) |
7077 | return true; |
7078 | |
7079 | return BTy->getKind() == BuiltinType::SChar || |
7080 | BTy->getKind() == BuiltinType::UChar || |
7081 | BTy->getKind() == BuiltinType::Short || |
7082 | BTy->getKind() == BuiltinType::UShort || |
7083 | BTy->getKind() == BuiltinType::Int || |
7084 | BTy->getKind() == BuiltinType::UInt || |
7085 | BTy->getKind() == BuiltinType::Long || |
7086 | BTy->getKind() == BuiltinType::ULong || |
7087 | BTy->getKind() == BuiltinType::LongLong || |
7088 | BTy->getKind() == BuiltinType::ULongLong || |
7089 | BTy->getKind() == BuiltinType::Float || |
7090 | BTy->getKind() == BuiltinType::Half; |
7091 | } |
7092 | |
7093 | /// HandleNeonVectorTypeAttr - The "neon_vector_type" and |
7094 | /// "neon_polyvector_type" attributes are used to create vector types that |
7095 | /// are mangled according to ARM's ABI. Otherwise, these types are identical |
7096 | /// to those created with the "vector_size" attribute. Unlike "vector_size" |
7097 | /// the argument to these Neon attributes is the number of vector elements, |
7098 | /// not the vector size in bytes. The vector width and element type must |
7099 | /// match one of the standard Neon vector types. |
7100 | static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, |
7101 | Sema &S, VectorType::VectorKind VecKind) { |
7102 | // Target must have NEON |
7103 | if (!S.Context.getTargetInfo().hasFeature("neon")) { |
7104 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr; |
7105 | Attr.setInvalid(); |
7106 | return; |
7107 | } |
7108 | // Check the attribute arguments. |
7109 | if (Attr.getNumArgs() != 1) { |
7110 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr |
7111 | << 1; |
7112 | Attr.setInvalid(); |
7113 | return; |
7114 | } |
7115 | // The number of elements must be an ICE. |
7116 | Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); |
7117 | llvm::APSInt numEltsInt(32); |
7118 | if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || |
7119 | !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { |
7120 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) |
7121 | << Attr << AANT_ArgumentIntegerConstant |
7122 | << numEltsExpr->getSourceRange(); |
7123 | Attr.setInvalid(); |
7124 | return; |
7125 | } |
7126 | // Only certain element types are supported for Neon vectors. |
7127 | if (!isPermittedNeonBaseType(CurType, VecKind, S)) { |
7128 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; |
7129 | Attr.setInvalid(); |
7130 | return; |
7131 | } |
7132 | |
7133 | // The total size of the vector must be 64 or 128 bits. |
7134 | unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); |
7135 | unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); |
7136 | unsigned vecSize = typeSize * numElts; |
7137 | if (vecSize != 64 && vecSize != 128) { |
7138 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; |
7139 | Attr.setInvalid(); |
7140 | return; |
7141 | } |
7142 | |
7143 | CurType = S.Context.getVectorType(CurType, numElts, VecKind); |
7144 | } |
7145 | |
7146 | /// Handle OpenCL Access Qualifier Attribute. |
7147 | static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, |
7148 | Sema &S) { |
7149 | // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. |
7150 | if (!(CurType->isImageType() || CurType->isPipeType())) { |
7151 | S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); |
7152 | Attr.setInvalid(); |
7153 | return; |
7154 | } |
7155 | |
7156 | if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { |
7157 | QualType BaseTy = TypedefTy->desugar(); |
7158 | |
7159 | std::string PrevAccessQual; |
7160 | if (BaseTy->isPipeType()) { |
7161 | if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { |
7162 | OpenCLAccessAttr *Attr = |
7163 | TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); |
7164 | PrevAccessQual = Attr->getSpelling(); |
7165 | } else { |
7166 | PrevAccessQual = "read_only"; |
7167 | } |
7168 | } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { |
7169 | |
7170 | switch (ImgType->getKind()) { |
7171 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
7172 | case BuiltinType::Id: \ |
7173 | PrevAccessQual = #Access; \ |
7174 | break; |
7175 | #include "clang/Basic/OpenCLImageTypes.def" |
7176 | default: |
7177 | llvm_unreachable("Unable to find corresponding image type.")::llvm::llvm_unreachable_internal("Unable to find corresponding image type." , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 7177); |
7178 | } |
7179 | } else { |
7180 | llvm_unreachable("unexpected type")::llvm::llvm_unreachable_internal("unexpected type", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 7180); |
7181 | } |
7182 | StringRef AttrName = Attr.getName()->getName(); |
7183 | if (PrevAccessQual == AttrName.ltrim("_")) { |
7184 | // Duplicated qualifiers |
7185 | S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) |
7186 | << AttrName << Attr.getRange(); |
7187 | } else { |
7188 | // Contradicting qualifiers |
7189 | S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); |
7190 | } |
7191 | |
7192 | S.Diag(TypedefTy->getDecl()->getBeginLoc(), |
7193 | diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; |
7194 | } else if (CurType->isPipeType()) { |
7195 | if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { |
7196 | QualType ElemType = CurType->getAs<PipeType>()->getElementType(); |
7197 | CurType = S.Context.getWritePipeType(ElemType); |
7198 | } |
7199 | } |
7200 | } |
7201 | |
7202 | static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State, |
7203 | QualType &T, TypeAttrLocation TAL) { |
7204 | Declarator &D = State.getDeclarator(); |
7205 | |
7206 | // Handle the cases where address space should not be deduced. |
7207 | // |
7208 | // The pointee type of a pointer type is always deduced since a pointer always |
7209 | // points to some memory location which should has an address space. |
7210 | // |
7211 | // There are situations that at the point of certain declarations, the address |
7212 | // space may be unknown and better to be left as default. For example, when |
7213 | // defining a typedef or struct type, they are not associated with any |
7214 | // specific address space. Later on, they may be used with any address space |
7215 | // to declare a variable. |
7216 | // |
7217 | // The return value of a function is r-value, therefore should not have |
7218 | // address space. |
7219 | // |
7220 | // The void type does not occupy memory, therefore should not have address |
7221 | // space, except when it is used as a pointee type. |
7222 | // |
7223 | // Since LLVM assumes function type is in default address space, it should not |
7224 | // have address space. |
7225 | auto ChunkIndex = State.getCurrentChunkIndex(); |
7226 | bool IsPointee = |
7227 | ChunkIndex > 0 && |
7228 | (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer || |
7229 | D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer || |
7230 | D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference); |
7231 | bool IsFuncReturnType = |
7232 | ChunkIndex > 0 && |
7233 | D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function; |
7234 | bool IsFuncType = |
7235 | ChunkIndex < D.getNumTypeObjects() && |
7236 | D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function; |
7237 | if ( // Do not deduce addr space for function return type and function type, |
7238 | // otherwise it will fail some sema check. |
7239 | IsFuncReturnType || IsFuncType || |
7240 | // Do not deduce addr space for member types of struct, except the pointee |
7241 | // type of a pointer member type. |
7242 | (D.getContext() == DeclaratorContext::MemberContext && !IsPointee) || |
7243 | // Do not deduce addr space for types used to define a typedef and the |
7244 | // typedef itself, except the pointee type of a pointer type which is used |
7245 | // to define the typedef. |
7246 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef && |
7247 | !IsPointee) || |
7248 | // Do not deduce addr space of the void type, e.g. in f(void), otherwise |
7249 | // it will fail some sema check. |
7250 | (T->isVoidType() && !IsPointee) || |
7251 | // Do not deduce address spaces for dependent types because they might end |
7252 | // up instantiating to a type with an explicit address space qualifier. |
7253 | T->isDependentType()) |
7254 | return; |
7255 | |
7256 | LangAS ImpAddr = LangAS::Default; |
7257 | // Put OpenCL automatic variable in private address space. |
7258 | // OpenCL v1.2 s6.5: |
7259 | // The default address space name for arguments to a function in a |
7260 | // program, or local variables of a function is __private. All function |
7261 | // arguments shall be in the __private address space. |
7262 | if (State.getSema().getLangOpts().OpenCLVersion <= 120 && |
7263 | !State.getSema().getLangOpts().OpenCLCPlusPlus) { |
7264 | ImpAddr = LangAS::opencl_private; |
7265 | } else { |
7266 | // If address space is not set, OpenCL 2.0 defines non private default |
7267 | // address spaces for some cases: |
7268 | // OpenCL 2.0, section 6.5: |
7269 | // The address space for a variable at program scope or a static variable |
7270 | // inside a function can either be __global or __constant, but defaults to |
7271 | // __global if not specified. |
7272 | // (...) |
7273 | // Pointers that are declared without pointing to a named address space |
7274 | // point to the generic address space. |
7275 | if (IsPointee) { |
7276 | ImpAddr = LangAS::opencl_generic; |
7277 | } else { |
7278 | if (D.getContext() == DeclaratorContext::TemplateArgContext) { |
7279 | // Do not deduce address space for non-pointee type in template arg. |
7280 | } else if (D.getContext() == DeclaratorContext::FileContext) { |
7281 | ImpAddr = LangAS::opencl_global; |
7282 | } else { |
7283 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || |
7284 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) { |
7285 | ImpAddr = LangAS::opencl_global; |
7286 | } else { |
7287 | ImpAddr = LangAS::opencl_private; |
7288 | } |
7289 | } |
7290 | } |
7291 | } |
7292 | T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr); |
7293 | } |
7294 | |
7295 | static void HandleLifetimeBoundAttr(TypeProcessingState &State, |
7296 | QualType &CurType, |
7297 | ParsedAttr &Attr) { |
7298 | if (State.getDeclarator().isDeclarationOfFunction()) { |
7299 | CurType = State.getAttributedType( |
7300 | createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), |
7301 | CurType, CurType); |
7302 | } else { |
7303 | Attr.diagnoseAppertainsTo(State.getSema(), nullptr); |
7304 | } |
7305 | } |
7306 | |
7307 | |
7308 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, |
7309 | TypeAttrLocation TAL, |
7310 | ParsedAttributesView &attrs) { |
7311 | // Scan through and apply attributes to this type where it makes sense. Some |
7312 | // attributes (such as __address_space__, __vector_size__, etc) apply to the |
7313 | // type, but others can be present in the type specifiers even though they |
7314 | // apply to the decl. Here we apply type attributes and ignore the rest. |
7315 | |
7316 | // This loop modifies the list pretty frequently, but we still need to make |
7317 | // sure we visit every element once. Copy the attributes list, and iterate |
7318 | // over that. |
7319 | ParsedAttributesView AttrsCopy{attrs}; |
7320 | |
7321 | state.setParsedNoDeref(false); |
7322 | |
7323 | for (ParsedAttr &attr : AttrsCopy) { |
7324 | |
7325 | // Skip attributes that were marked to be invalid. |
7326 | if (attr.isInvalid()) |
7327 | continue; |
7328 | |
7329 | if (attr.isCXX11Attribute()) { |
7330 | // [[gnu::...]] attributes are treated as declaration attributes, so may |
7331 | // not appertain to a DeclaratorChunk. If we handle them as type |
7332 | // attributes, accept them in that position and diagnose the GCC |
7333 | // incompatibility. |
7334 | if (attr.isGNUScope()) { |
7335 | bool IsTypeAttr = attr.isTypeAttr(); |
7336 | if (TAL == TAL_DeclChunk) { |
7337 | state.getSema().Diag(attr.getLoc(), |
7338 | IsTypeAttr |
7339 | ? diag::warn_gcc_ignores_type_attr |
7340 | : diag::warn_cxx11_gnu_attribute_on_type) |
7341 | << attr.getName(); |
7342 | if (!IsTypeAttr) |
7343 | continue; |
7344 | } |
7345 | } else if (TAL != TAL_DeclChunk) { |
7346 | // Otherwise, only consider type processing for a C++11 attribute if |
7347 | // it's actually been applied to a type. |
7348 | continue; |
7349 | } |
7350 | } |
7351 | |
7352 | // If this is an attribute we can handle, do so now, |
7353 | // otherwise, add it to the FnAttrs list for rechaining. |
7354 | switch (attr.getKind()) { |
7355 | default: |
7356 | // A C++11 attribute on a declarator chunk must appertain to a type. |
7357 | if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { |
7358 | state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) |
7359 | << attr; |
7360 | attr.setUsedAsTypeAttr(); |
7361 | } |
7362 | break; |
7363 | |
7364 | case ParsedAttr::UnknownAttribute: |
7365 | if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) |
7366 | state.getSema().Diag(attr.getLoc(), |
7367 | diag::warn_unknown_attribute_ignored) |
7368 | << attr.getName(); |
7369 | break; |
7370 | |
7371 | case ParsedAttr::IgnoredAttribute: |
7372 | break; |
7373 | |
7374 | case ParsedAttr::AT_MayAlias: |
7375 | // FIXME: This attribute needs to actually be handled, but if we ignore |
7376 | // it it breaks large amounts of Linux software. |
7377 | attr.setUsedAsTypeAttr(); |
7378 | break; |
7379 | case ParsedAttr::AT_OpenCLPrivateAddressSpace: |
7380 | case ParsedAttr::AT_OpenCLGlobalAddressSpace: |
7381 | case ParsedAttr::AT_OpenCLLocalAddressSpace: |
7382 | case ParsedAttr::AT_OpenCLConstantAddressSpace: |
7383 | case ParsedAttr::AT_OpenCLGenericAddressSpace: |
7384 | case ParsedAttr::AT_AddressSpace: |
7385 | HandleAddressSpaceTypeAttribute(type, attr, state); |
7386 | attr.setUsedAsTypeAttr(); |
7387 | break; |
7388 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: |
7389 | if (!handleObjCPointerTypeAttr(state, attr, type)) |
7390 | distributeObjCPointerTypeAttr(state, attr, type); |
7391 | attr.setUsedAsTypeAttr(); |
7392 | break; |
7393 | case ParsedAttr::AT_VectorSize: |
7394 | HandleVectorSizeAttr(type, attr, state.getSema()); |
7395 | attr.setUsedAsTypeAttr(); |
7396 | break; |
7397 | case ParsedAttr::AT_ExtVectorType: |
7398 | HandleExtVectorTypeAttr(type, attr, state.getSema()); |
7399 | attr.setUsedAsTypeAttr(); |
7400 | break; |
7401 | case ParsedAttr::AT_NeonVectorType: |
7402 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), |
7403 | VectorType::NeonVector); |
7404 | attr.setUsedAsTypeAttr(); |
7405 | break; |
7406 | case ParsedAttr::AT_NeonPolyVectorType: |
7407 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), |
7408 | VectorType::NeonPolyVector); |
7409 | attr.setUsedAsTypeAttr(); |
7410 | break; |
7411 | case ParsedAttr::AT_OpenCLAccess: |
7412 | HandleOpenCLAccessAttr(type, attr, state.getSema()); |
7413 | attr.setUsedAsTypeAttr(); |
7414 | break; |
7415 | case ParsedAttr::AT_LifetimeBound: |
7416 | if (TAL == TAL_DeclChunk) |
7417 | HandleLifetimeBoundAttr(state, type, attr); |
7418 | break; |
7419 | |
7420 | case ParsedAttr::AT_NoDeref: { |
7421 | ASTContext &Ctx = state.getSema().Context; |
7422 | type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), |
7423 | type, type); |
7424 | attr.setUsedAsTypeAttr(); |
7425 | state.setParsedNoDeref(true); |
7426 | break; |
7427 | } |
7428 | |
7429 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: |
7430 | if (!handleMSPointerTypeQualifierAttr(state, attr, type)) |
7431 | attr.setUsedAsTypeAttr(); |
7432 | break; |
7433 | |
7434 | |
7435 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullUnspecified: |
7436 | // Either add nullability here or try to distribute it. We |
7437 | // don't want to distribute the nullability specifier past any |
7438 | // dependent type, because that complicates the user model. |
7439 | if (type->canHaveNullability() || type->isDependentType() || |
7440 | type->isArrayType() || |
7441 | !distributeNullabilityTypeAttr(state, type, attr)) { |
7442 | unsigned endIndex; |
7443 | if (TAL == TAL_DeclChunk) |
7444 | endIndex = state.getCurrentChunkIndex(); |
7445 | else |
7446 | endIndex = state.getDeclarator().getNumTypeObjects(); |
7447 | bool allowOnArrayType = |
7448 | state.getDeclarator().isPrototypeContext() && |
7449 | !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); |
7450 | if (checkNullabilityTypeSpecifier( |
7451 | state, |
7452 | type, |
7453 | attr, |
7454 | allowOnArrayType)) { |
7455 | attr.setInvalid(); |
7456 | } |
7457 | |
7458 | attr.setUsedAsTypeAttr(); |
7459 | } |
7460 | break; |
7461 | |
7462 | case ParsedAttr::AT_ObjCKindOf: |
7463 | // '__kindof' must be part of the decl-specifiers. |
7464 | switch (TAL) { |
7465 | case TAL_DeclSpec: |
7466 | break; |
7467 | |
7468 | case TAL_DeclChunk: |
7469 | case TAL_DeclName: |
7470 | state.getSema().Diag(attr.getLoc(), |
7471 | diag::err_objc_kindof_wrong_position) |
7472 | << FixItHint::CreateRemoval(attr.getLoc()) |
7473 | << FixItHint::CreateInsertion( |
7474 | state.getDeclarator().getDeclSpec().getBeginLoc(), |
7475 | "__kindof "); |
7476 | break; |
7477 | } |
7478 | |
7479 | // Apply it regardless. |
7480 | if (checkObjCKindOfType(state, type, attr)) |
7481 | attr.setInvalid(); |
7482 | break; |
7483 | |
7484 | FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: 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_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: |
7485 | attr.setUsedAsTypeAttr(); |
7486 | |
7487 | // Never process function type attributes as part of the |
7488 | // declaration-specifiers. |
7489 | if (TAL == TAL_DeclSpec) |
7490 | distributeFunctionTypeAttrFromDeclSpec(state, attr, type); |
7491 | |
7492 | // Otherwise, handle the possible delays. |
7493 | else if (!handleFunctionTypeAttr(state, attr, type)) |
7494 | distributeFunctionTypeAttr(state, attr, type); |
7495 | break; |
7496 | } |
7497 | } |
7498 | |
7499 | if (!state.getSema().getLangOpts().OpenCL || |
7500 | type.getAddressSpace() != LangAS::Default) |
7501 | return; |
7502 | |
7503 | deduceOpenCLImplicitAddrSpace(state, type, TAL); |
7504 | } |
7505 | |
7506 | void Sema::completeExprArrayBound(Expr *E) { |
7507 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { |
7508 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { |
7509 | if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { |
7510 | auto *Def = Var->getDefinition(); |
7511 | if (!Def) { |
7512 | SourceLocation PointOfInstantiation = E->getExprLoc(); |
7513 | InstantiateVariableDefinition(PointOfInstantiation, Var); |
7514 | Def = Var->getDefinition(); |
7515 | |
7516 | // If we don't already have a point of instantiation, and we managed |
7517 | // to instantiate a definition, this is the point of instantiation. |
7518 | // Otherwise, we don't request an end-of-TU instantiation, so this is |
7519 | // not a point of instantiation. |
7520 | // FIXME: Is this really the right behavior? |
7521 | if (Var->getPointOfInstantiation().isInvalid() && Def) { |
7522 | assert(Var->getTemplateSpecializationKind() ==((Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? static_cast<void> (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 7524, __PRETTY_FUNCTION__)) |
7523 | TSK_ImplicitInstantiation &&((Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? static_cast<void> (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 7524, __PRETTY_FUNCTION__)) |
7524 | "explicit instantiation with no point of instantiation")((Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? static_cast<void> (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 7524, __PRETTY_FUNCTION__)); |
7525 | Var->setTemplateSpecializationKind( |
7526 | Var->getTemplateSpecializationKind(), PointOfInstantiation); |
7527 | } |
7528 | } |
7529 | |
7530 | // Update the type to the definition's type both here and within the |
7531 | // expression. |
7532 | if (Def) { |
7533 | DRE->setDecl(Def); |
7534 | QualType T = Def->getType(); |
7535 | DRE->setType(T); |
7536 | // FIXME: Update the type on all intervening expressions. |
7537 | E->setType(T); |
7538 | } |
7539 | |
7540 | // We still go on to try to complete the type independently, as it |
7541 | // may also require instantiations or diagnostics if it remains |
7542 | // incomplete. |
7543 | } |
7544 | } |
7545 | } |
7546 | } |
7547 | |
7548 | /// Ensure that the type of the given expression is complete. |
7549 | /// |
7550 | /// This routine checks whether the expression \p E has a complete type. If the |
7551 | /// expression refers to an instantiable construct, that instantiation is |
7552 | /// performed as needed to complete its type. Furthermore |
7553 | /// Sema::RequireCompleteType is called for the expression's type (or in the |
7554 | /// case of a reference type, the referred-to type). |
7555 | /// |
7556 | /// \param E The expression whose type is required to be complete. |
7557 | /// \param Diagnoser The object that will emit a diagnostic if the type is |
7558 | /// incomplete. |
7559 | /// |
7560 | /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false |
7561 | /// otherwise. |
7562 | bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { |
7563 | QualType T = E->getType(); |
7564 | |
7565 | // Incomplete array types may be completed by the initializer attached to |
7566 | // their definitions. For static data members of class templates and for |
7567 | // variable templates, we need to instantiate the definition to get this |
7568 | // initializer and complete the type. |
7569 | if (T->isIncompleteArrayType()) { |
7570 | completeExprArrayBound(E); |
7571 | T = E->getType(); |
7572 | } |
7573 | |
7574 | // FIXME: Are there other cases which require instantiating something other |
7575 | // than the type to complete the type of an expression? |
7576 | |
7577 | return RequireCompleteType(E->getExprLoc(), T, Diagnoser); |
7578 | } |
7579 | |
7580 | bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { |
7581 | BoundTypeDiagnoser<> Diagnoser(DiagID); |
7582 | return RequireCompleteExprType(E, Diagnoser); |
7583 | } |
7584 | |
7585 | /// Ensure that the type T is a complete type. |
7586 | /// |
7587 | /// This routine checks whether the type @p T is complete in any |
7588 | /// context where a complete type is required. If @p T is a complete |
7589 | /// type, returns false. If @p T is a class template specialization, |
7590 | /// this routine then attempts to perform class template |
7591 | /// instantiation. If instantiation fails, or if @p T is incomplete |
7592 | /// and cannot be completed, issues the diagnostic @p diag (giving it |
7593 | /// the type @p T) and returns true. |
7594 | /// |
7595 | /// @param Loc The location in the source that the incomplete type |
7596 | /// diagnostic should refer to. |
7597 | /// |
7598 | /// @param T The type that this routine is examining for completeness. |
7599 | /// |
7600 | /// @returns @c true if @p T is incomplete and a diagnostic was emitted, |
7601 | /// @c false otherwise. |
7602 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, |
7603 | TypeDiagnoser &Diagnoser) { |
7604 | if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) |
7605 | return true; |
7606 | if (const TagType *Tag = T->getAs<TagType>()) { |
7607 | if (!Tag->getDecl()->isCompleteDefinitionRequired()) { |
7608 | Tag->getDecl()->setCompleteDefinitionRequired(); |
7609 | Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); |
7610 | } |
7611 | } |
7612 | return false; |
7613 | } |
7614 | |
7615 | bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { |
7616 | llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; |
7617 | if (!Suggested) |
7618 | return false; |
7619 | |
7620 | // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext |
7621 | // and isolate from other C++ specific checks. |
7622 | StructuralEquivalenceContext Ctx( |
7623 | D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, |
7624 | StructuralEquivalenceKind::Default, |
7625 | false /*StrictTypeSpelling*/, true /*Complain*/, |
7626 | true /*ErrorOnTagTypeMismatch*/); |
7627 | return Ctx.IsEquivalent(D, Suggested); |
7628 | } |
7629 | |
7630 | /// Determine whether there is any declaration of \p D that was ever a |
7631 | /// definition (perhaps before module merging) and is currently visible. |
7632 | /// \param D The definition of the entity. |
7633 | /// \param Suggested Filled in with the declaration that should be made visible |
7634 | /// in order to provide a definition of this entity. |
7635 | /// \param OnlyNeedComplete If \c true, we only need the type to be complete, |
7636 | /// not defined. This only matters for enums with a fixed underlying |
7637 | /// type, since in all other cases, a type is complete if and only if it |
7638 | /// is defined. |
7639 | bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, |
7640 | bool OnlyNeedComplete) { |
7641 | // Easy case: if we don't have modules, all declarations are visible. |
7642 | if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) |
7643 | return true; |
7644 | |
7645 | // If this definition was instantiated from a template, map back to the |
7646 | // pattern from which it was instantiated. |
7647 | if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { |
7648 | // We're in the middle of defining it; this definition should be treated |
7649 | // as visible. |
7650 | return true; |
7651 | } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { |
7652 | if (auto *Pattern = RD->getTemplateInstantiationPattern()) |
7653 | RD = Pattern; |
7654 | D = RD->getDefinition(); |
7655 | } else if (auto *ED = dyn_cast<EnumDecl>(D)) { |
7656 | if (auto *Pattern = ED->getTemplateInstantiationPattern()) |
7657 | ED = Pattern; |
7658 | if (OnlyNeedComplete && ED->isFixed()) { |
7659 | // If the enum has a fixed underlying type, and we're only looking for a |
7660 | // complete type (not a definition), any visible declaration of it will |
7661 | // do. |
7662 | *Suggested = nullptr; |
7663 | for (auto *Redecl : ED->redecls()) { |
7664 | if (isVisible(Redecl)) |
7665 | return true; |
7666 | if (Redecl->isThisDeclarationADefinition() || |
7667 | (Redecl->isCanonicalDecl() && !*Suggested)) |
7668 | *Suggested = Redecl; |
7669 | } |
7670 | return false; |
7671 | } |
7672 | D = ED->getDefinition(); |
7673 | } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { |
7674 | if (auto *Pattern = FD->getTemplateInstantiationPattern()) |
7675 | FD = Pattern; |
7676 | D = FD->getDefinition(); |
7677 | } else if (auto *VD = dyn_cast<VarDecl>(D)) { |
7678 | if (auto *Pattern = VD->getTemplateInstantiationPattern()) |
7679 | VD = Pattern; |
7680 | D = VD->getDefinition(); |
7681 | } |
7682 | assert(D && "missing definition for pattern of instantiated definition")((D && "missing definition for pattern of instantiated definition" ) ? static_cast<void> (0) : __assert_fail ("D && \"missing definition for pattern of instantiated definition\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 7682, __PRETTY_FUNCTION__)); |
7683 | |
7684 | *Suggested = D; |
7685 | |
7686 | auto DefinitionIsVisible = [&] { |
7687 | // The (primary) definition might be in a visible module. |
7688 | if (isVisible(D)) |
7689 | return true; |
7690 | |
7691 | // A visible module might have a merged definition instead. |
7692 | if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) |
7693 | : hasVisibleMergedDefinition(D)) { |
7694 | if (CodeSynthesisContexts.empty() && |
7695 | !getLangOpts().ModulesLocalVisibility) { |
7696 | // Cache the fact that this definition is implicitly visible because |
7697 | // there is a visible merged definition. |
7698 | D->setVisibleDespiteOwningModule(); |
7699 | } |
7700 | return true; |
7701 | } |
7702 | |
7703 | return false; |
7704 | }; |
7705 | |
7706 | if (DefinitionIsVisible()) |
7707 | return true; |
7708 | |
7709 | // The external source may have additional definitions of this entity that are |
7710 | // visible, so complete the redeclaration chain now and ask again. |
7711 | if (auto *Source = Context.getExternalSource()) { |
7712 | Source->CompleteRedeclChain(D); |
7713 | return DefinitionIsVisible(); |
7714 | } |
7715 | |
7716 | return false; |
7717 | } |
7718 | |
7719 | /// Locks in the inheritance model for the given class and all of its bases. |
7720 | static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { |
7721 | RD = RD->getMostRecentNonInjectedDecl(); |
7722 | if (!RD->hasAttr<MSInheritanceAttr>()) { |
7723 | MSInheritanceAttr::Spelling IM; |
7724 | |
7725 | switch (S.MSPointerToMemberRepresentationMethod) { |
7726 | case LangOptions::PPTMK_BestCase: |
7727 | IM = RD->calculateInheritanceModel(); |
7728 | break; |
7729 | case LangOptions::PPTMK_FullGeneralitySingleInheritance: |
7730 | IM = MSInheritanceAttr::Keyword_single_inheritance; |
7731 | break; |
7732 | case LangOptions::PPTMK_FullGeneralityMultipleInheritance: |
7733 | IM = MSInheritanceAttr::Keyword_multiple_inheritance; |
7734 | break; |
7735 | case LangOptions::PPTMK_FullGeneralityVirtualInheritance: |
7736 | IM = MSInheritanceAttr::Keyword_unspecified_inheritance; |
7737 | break; |
7738 | } |
7739 | |
7740 | RD->addAttr(MSInheritanceAttr::CreateImplicit( |
7741 | S.getASTContext(), IM, |
7742 | /*BestCase=*/S.MSPointerToMemberRepresentationMethod == |
7743 | LangOptions::PPTMK_BestCase, |
7744 | S.ImplicitMSInheritanceAttrLoc.isValid() |
7745 | ? S.ImplicitMSInheritanceAttrLoc |
7746 | : RD->getSourceRange())); |
7747 | S.Consumer.AssignInheritanceModel(RD); |
7748 | } |
7749 | } |
7750 | |
7751 | /// The implementation of RequireCompleteType |
7752 | bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, |
7753 | TypeDiagnoser *Diagnoser) { |
7754 | // FIXME: Add this assertion to make sure we always get instantiation points. |
7755 | // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); |
7756 | // FIXME: Add this assertion to help us flush out problems with |
7757 | // checking for dependent types and type-dependent expressions. |
7758 | // |
7759 | // assert(!T->isDependentType() && |
7760 | // "Can't ask whether a dependent type is complete"); |
7761 | |
7762 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { |
7763 | if (!MPTy->getClass()->isDependentType()) { |
7764 | if (getLangOpts().CompleteMemberPointers && |
7765 | !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && |
7766 | RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), |
7767 | diag::err_memptr_incomplete)) |
7768 | return true; |
7769 | |
7770 | // We lock in the inheritance model once somebody has asked us to ensure |
7771 | // that a pointer-to-member type is complete. |
7772 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
7773 | (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); |
7774 | assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); |
7775 | } |
7776 | } |
7777 | } |
7778 | |
7779 | NamedDecl *Def = nullptr; |
7780 | bool Incomplete = T->isIncompleteType(&Def); |
7781 | |
7782 | // Check that any necessary explicit specializations are visible. For an |
7783 | // enum, we just need the declaration, so don't check this. |
7784 | if (Def && !isa<EnumDecl>(Def)) |
7785 | checkSpecializationVisibility(Loc, Def); |
7786 | |
7787 | // If we have a complete type, we're done. |
7788 | if (!Incomplete) { |
7789 | // If we know about the definition but it is not visible, complain. |
7790 | NamedDecl *SuggestedDef = nullptr; |
7791 | if (Def && |
7792 | !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { |
7793 | // If the user is going to see an error here, recover by making the |
7794 | // definition visible. |
7795 | bool TreatAsComplete = Diagnoser && !isSFINAEContext(); |
7796 | if (Diagnoser && SuggestedDef) |
7797 | diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, |
7798 | /*Recover*/TreatAsComplete); |
7799 | return !TreatAsComplete; |
7800 | } else if (Def && !TemplateInstCallbacks.empty()) { |
7801 | CodeSynthesisContext TempInst; |
7802 | TempInst.Kind = CodeSynthesisContext::Memoization; |
7803 | TempInst.Template = Def; |
7804 | TempInst.Entity = Def; |
7805 | TempInst.PointOfInstantiation = Loc; |
7806 | atTemplateBegin(TemplateInstCallbacks, *this, TempInst); |
7807 | atTemplateEnd(TemplateInstCallbacks, *this, TempInst); |
7808 | } |
7809 | |
7810 | return false; |
7811 | } |
7812 | |
7813 | TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); |
7814 | ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); |
7815 | |
7816 | // Give the external source a chance to provide a definition of the type. |
7817 | // This is kept separate from completing the redeclaration chain so that |
7818 | // external sources such as LLDB can avoid synthesizing a type definition |
7819 | // unless it's actually needed. |
7820 | if (Tag || IFace) { |
7821 | // Avoid diagnosing invalid decls as incomplete. |
7822 | if (Def->isInvalidDecl()) |
7823 | return true; |
7824 | |
7825 | // Give the external AST source a chance to complete the type. |
7826 | if (auto *Source = Context.getExternalSource()) { |
7827 | if (Tag && Tag->hasExternalLexicalStorage()) |
7828 | Source->CompleteType(Tag); |
7829 | if (IFace && IFace->hasExternalLexicalStorage()) |
7830 | Source->CompleteType(IFace); |
7831 | // If the external source completed the type, go through the motions |
7832 | // again to ensure we're allowed to use the completed type. |
7833 | if (!T->isIncompleteType()) |
7834 | return RequireCompleteTypeImpl(Loc, T, Diagnoser); |
7835 | } |
7836 | } |
7837 | |
7838 | // If we have a class template specialization or a class member of a |
7839 | // class template specialization, or an array with known size of such, |
7840 | // try to instantiate it. |
7841 | if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { |
7842 | bool Instantiated = false; |
7843 | bool Diagnosed = false; |
7844 | if (RD->isDependentContext()) { |
7845 | // Don't try to instantiate a dependent class (eg, a member template of |
7846 | // an instantiated class template specialization). |
7847 | // FIXME: Can this ever happen? |
7848 | } else if (auto *ClassTemplateSpec = |
7849 | dyn_cast<ClassTemplateSpecializationDecl>(RD)) { |
7850 | if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { |
7851 | Diagnosed = InstantiateClassTemplateSpecialization( |
7852 | Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, |
7853 | /*Complain=*/Diagnoser); |
7854 | Instantiated = true; |
7855 | } |
7856 | } else { |
7857 | CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); |
7858 | if (!RD->isBeingDefined() && Pattern) { |
7859 | MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); |
7860 | assert(MSI && "Missing member specialization information?")((MSI && "Missing member specialization information?" ) ? static_cast<void> (0) : __assert_fail ("MSI && \"Missing member specialization information?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 7860, __PRETTY_FUNCTION__)); |
7861 | // This record was instantiated from a class within a template. |
7862 | if (MSI->getTemplateSpecializationKind() != |
7863 | TSK_ExplicitSpecialization) { |
7864 | Diagnosed = InstantiateClass(Loc, RD, Pattern, |
7865 | getTemplateInstantiationArgs(RD), |
7866 | TSK_ImplicitInstantiation, |
7867 | /*Complain=*/Diagnoser); |
7868 | Instantiated = true; |
7869 | } |
7870 | } |
7871 | } |
7872 | |
7873 | if (Instantiated) { |
7874 | // Instantiate* might have already complained that the template is not |
7875 | // defined, if we asked it to. |
7876 | if (Diagnoser && Diagnosed) |
7877 | return true; |
7878 | // If we instantiated a definition, check that it's usable, even if |
7879 | // instantiation produced an error, so that repeated calls to this |
7880 | // function give consistent answers. |
7881 | if (!T->isIncompleteType()) |
7882 | return RequireCompleteTypeImpl(Loc, T, Diagnoser); |
7883 | } |
7884 | } |
7885 | |
7886 | // FIXME: If we didn't instantiate a definition because of an explicit |
7887 | // specialization declaration, check that it's visible. |
7888 | |
7889 | if (!Diagnoser) |
7890 | return true; |
7891 | |
7892 | Diagnoser->diagnose(*this, Loc, T); |
7893 | |
7894 | // If the type was a forward declaration of a class/struct/union |
7895 | // type, produce a note. |
7896 | if (Tag && !Tag->isInvalidDecl()) |
7897 | Diag(Tag->getLocation(), |
7898 | Tag->isBeingDefined() ? diag::note_type_being_defined |
7899 | : diag::note_forward_declaration) |
7900 | << Context.getTagDeclType(Tag); |
7901 | |
7902 | // If the Objective-C class was a forward declaration, produce a note. |
7903 | if (IFace && !IFace->isInvalidDecl()) |
7904 | Diag(IFace->getLocation(), diag::note_forward_class); |
7905 | |
7906 | // If we have external information that we can use to suggest a fix, |
7907 | // produce a note. |
7908 | if (ExternalSource) |
7909 | ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); |
7910 | |
7911 | return true; |
7912 | } |
7913 | |
7914 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, |
7915 | unsigned DiagID) { |
7916 | BoundTypeDiagnoser<> Diagnoser(DiagID); |
7917 | return RequireCompleteType(Loc, T, Diagnoser); |
7918 | } |
7919 | |
7920 | /// Get diagnostic %select index for tag kind for |
7921 | /// literal type diagnostic message. |
7922 | /// WARNING: Indexes apply to particular diagnostics only! |
7923 | /// |
7924 | /// \returns diagnostic %select index. |
7925 | static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { |
7926 | switch (Tag) { |
7927 | case TTK_Struct: return 0; |
7928 | case TTK_Interface: return 1; |
7929 | case TTK_Class: return 2; |
7930 | default: llvm_unreachable("Invalid tag kind for literal type diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for literal type diagnostic!" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 7930); |
7931 | } |
7932 | } |
7933 | |
7934 | /// Ensure that the type T is a literal type. |
7935 | /// |
7936 | /// This routine checks whether the type @p T is a literal type. If @p T is an |
7937 | /// incomplete type, an attempt is made to complete it. If @p T is a literal |
7938 | /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, |
7939 | /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving |
7940 | /// it the type @p T), along with notes explaining why the type is not a |
7941 | /// literal type, and returns true. |
7942 | /// |
7943 | /// @param Loc The location in the source that the non-literal type |
7944 | /// diagnostic should refer to. |
7945 | /// |
7946 | /// @param T The type that this routine is examining for literalness. |
7947 | /// |
7948 | /// @param Diagnoser Emits a diagnostic if T is not a literal type. |
7949 | /// |
7950 | /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, |
7951 | /// @c false otherwise. |
7952 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, |
7953 | TypeDiagnoser &Diagnoser) { |
7954 | assert(!T->isDependentType() && "type should not be dependent")((!T->isDependentType() && "type should not be dependent" ) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"type should not be dependent\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 7954, __PRETTY_FUNCTION__)); |
7955 | |
7956 | QualType ElemType = Context.getBaseElementType(T); |
7957 | if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && |
7958 | T->isLiteralType(Context)) |
7959 | return false; |
7960 | |
7961 | Diagnoser.diagnose(*this, Loc, T); |
7962 | |
7963 | if (T->isVariableArrayType()) |
7964 | return true; |
7965 | |
7966 | const RecordType *RT = ElemType->getAs<RecordType>(); |
7967 | if (!RT) |
7968 | return true; |
7969 | |
7970 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); |
7971 | |
7972 | // A partially-defined class type can't be a literal type, because a literal |
7973 | // class type must have a trivial destructor (which can't be checked until |
7974 | // the class definition is complete). |
7975 | if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) |
7976 | return true; |
7977 | |
7978 | // [expr.prim.lambda]p3: |
7979 | // This class type is [not] a literal type. |
7980 | if (RD->isLambda() && !getLangOpts().CPlusPlus17) { |
7981 | Diag(RD->getLocation(), diag::note_non_literal_lambda); |
7982 | return true; |
7983 | } |
7984 | |
7985 | // If the class has virtual base classes, then it's not an aggregate, and |
7986 | // cannot have any constexpr constructors or a trivial default constructor, |
7987 | // so is non-literal. This is better to diagnose than the resulting absence |
7988 | // of constexpr constructors. |
7989 | if (RD->getNumVBases()) { |
7990 | Diag(RD->getLocation(), diag::note_non_literal_virtual_base) |
7991 | << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); |
7992 | for (const auto &I : RD->vbases()) |
7993 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) |
7994 | << I.getSourceRange(); |
7995 | } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && |
7996 | !RD->hasTrivialDefaultConstructor()) { |
7997 | Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; |
7998 | } else if (RD->hasNonLiteralTypeFieldsOrBases()) { |
7999 | for (const auto &I : RD->bases()) { |
8000 | if (!I.getType()->isLiteralType(Context)) { |
8001 | Diag(I.getBeginLoc(), diag::note_non_literal_base_class) |
8002 | << RD << I.getType() << I.getSourceRange(); |
8003 | return true; |
8004 | } |
8005 | } |
8006 | for (const auto *I : RD->fields()) { |
8007 | if (!I->getType()->isLiteralType(Context) || |
8008 | I->getType().isVolatileQualified()) { |
8009 | Diag(I->getLocation(), diag::note_non_literal_field) |
8010 | << RD << I << I->getType() |
8011 | << I->getType().isVolatileQualified(); |
8012 | return true; |
8013 | } |
8014 | } |
8015 | } else if (!RD->hasTrivialDestructor()) { |
8016 | // All fields and bases are of literal types, so have trivial destructors. |
8017 | // If this class's destructor is non-trivial it must be user-declared. |
8018 | CXXDestructorDecl *Dtor = RD->getDestructor(); |
8019 | assert(Dtor && "class has literal fields and bases but no dtor?")((Dtor && "class has literal fields and bases but no dtor?" ) ? static_cast<void> (0) : __assert_fail ("Dtor && \"class has literal fields and bases but no dtor?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 8019, __PRETTY_FUNCTION__)); |
8020 | if (!Dtor) |
8021 | return true; |
8022 | |
8023 | Diag(Dtor->getLocation(), Dtor->isUserProvided() ? |
8024 | diag::note_non_literal_user_provided_dtor : |
8025 | diag::note_non_literal_nontrivial_dtor) << RD; |
8026 | if (!Dtor->isUserProvided()) |
8027 | SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, |
8028 | /*Diagnose*/true); |
8029 | } |
8030 | |
8031 | return true; |
8032 | } |
8033 | |
8034 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { |
8035 | BoundTypeDiagnoser<> Diagnoser(DiagID); |
8036 | return RequireLiteralType(Loc, T, Diagnoser); |
8037 | } |
8038 | |
8039 | /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified |
8040 | /// by the nested-name-specifier contained in SS, and that is (re)declared by |
8041 | /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. |
8042 | QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, |
8043 | const CXXScopeSpec &SS, QualType T, |
8044 | TagDecl *OwnedTagDecl) { |
8045 | if (T.isNull()) |
8046 | return T; |
8047 | NestedNameSpecifier *NNS; |
8048 | if (SS.isValid()) |
8049 | NNS = SS.getScopeRep(); |
8050 | else { |
8051 | if (Keyword == ETK_None) |
8052 | return T; |
8053 | NNS = nullptr; |
8054 | } |
8055 | return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl); |
8056 | } |
8057 | |
8058 | QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { |
8059 | ExprResult ER = CheckPlaceholderExpr(E); |
8060 | if (ER.isInvalid()) return QualType(); |
8061 | E = ER.get(); |
8062 | |
8063 | if (!getLangOpts().CPlusPlus && E->refersToBitField()) |
8064 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; |
8065 | |
8066 | if (!E->isTypeDependent()) { |
8067 | QualType T = E->getType(); |
8068 | if (const TagType *TT = T->getAs<TagType>()) |
8069 | DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); |
8070 | } |
8071 | return Context.getTypeOfExprType(E); |
8072 | } |
8073 | |
8074 | /// getDecltypeForExpr - Given an expr, will return the decltype for |
8075 | /// that expression, according to the rules in C++11 |
8076 | /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. |
8077 | static QualType getDecltypeForExpr(Sema &S, Expr *E) { |
8078 | if (E->isTypeDependent()) |
8079 | return S.Context.DependentTy; |
8080 | |
8081 | // C++11 [dcl.type.simple]p4: |
8082 | // The type denoted by decltype(e) is defined as follows: |
8083 | // |
8084 | // - if e is an unparenthesized id-expression or an unparenthesized class |
8085 | // member access (5.2.5), decltype(e) is the type of the entity named |
8086 | // by e. If there is no such entity, or if e names a set of overloaded |
8087 | // functions, the program is ill-formed; |
8088 | // |
8089 | // We apply the same rules for Objective-C ivar and property references. |
8090 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { |
8091 | const ValueDecl *VD = DRE->getDecl(); |
8092 | return VD->getType(); |
8093 | } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { |
8094 | if (const ValueDecl *VD = ME->getMemberDecl()) |
8095 | if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) |
8096 | return VD->getType(); |
8097 | } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { |
8098 | return IR->getDecl()->getType(); |
8099 | } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { |
8100 | if (PR->isExplicitProperty()) |
8101 | return PR->getExplicitProperty()->getType(); |
8102 | } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { |
8103 | return PE->getType(); |
8104 | } |
8105 | |
8106 | // C++11 [expr.lambda.prim]p18: |
8107 | // Every occurrence of decltype((x)) where x is a possibly |
8108 | // parenthesized id-expression that names an entity of automatic |
8109 | // storage duration is treated as if x were transformed into an |
8110 | // access to a corresponding data member of the closure type that |
8111 | // would have been declared if x were an odr-use of the denoted |
8112 | // entity. |
8113 | using namespace sema; |
8114 | if (S.getCurLambda()) { |
8115 | if (isa<ParenExpr>(E)) { |
8116 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { |
8117 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { |
8118 | QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); |
8119 | if (!T.isNull()) |
8120 | return S.Context.getLValueReferenceType(T); |
8121 | } |
8122 | } |
8123 | } |
8124 | } |
8125 | |
8126 | |
8127 | // C++11 [dcl.type.simple]p4: |
8128 | // [...] |
8129 | QualType T = E->getType(); |
8130 | switch (E->getValueKind()) { |
8131 | // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the |
8132 | // type of e; |
8133 | case VK_XValue: T = S.Context.getRValueReferenceType(T); break; |
8134 | // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the |
8135 | // type of e; |
8136 | case VK_LValue: T = S.Context.getLValueReferenceType(T); break; |
8137 | // - otherwise, decltype(e) is the type of e. |
8138 | case VK_RValue: break; |
8139 | } |
8140 | |
8141 | return T; |
8142 | } |
8143 | |
8144 | QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, |
8145 | bool AsUnevaluated) { |
8146 | ExprResult ER = CheckPlaceholderExpr(E); |
8147 | if (ER.isInvalid()) return QualType(); |
8148 | E = ER.get(); |
8149 | |
8150 | if (AsUnevaluated && CodeSynthesisContexts.empty() && |
8151 | E->HasSideEffects(Context, false)) { |
8152 | // The expression operand for decltype is in an unevaluated expression |
8153 | // context, so side effects could result in unintended consequences. |
8154 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); |
8155 | } |
8156 | |
8157 | return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); |
8158 | } |
8159 | |
8160 | QualType Sema::BuildUnaryTransformType(QualType BaseType, |
8161 | UnaryTransformType::UTTKind UKind, |
8162 | SourceLocation Loc) { |
8163 | switch (UKind) { |
8164 | case UnaryTransformType::EnumUnderlyingType: |
8165 | if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { |
8166 | Diag(Loc, diag::err_only_enums_have_underlying_types); |
8167 | return QualType(); |
8168 | } else { |
8169 | QualType Underlying = BaseType; |
8170 | if (!BaseType->isDependentType()) { |
8171 | // The enum could be incomplete if we're parsing its definition or |
8172 | // recovering from an error. |
8173 | NamedDecl *FwdDecl = nullptr; |
8174 | if (BaseType->isIncompleteType(&FwdDecl)) { |
8175 | Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; |
8176 | Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; |
8177 | return QualType(); |
8178 | } |
8179 | |
8180 | EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); |
8181 | assert(ED && "EnumType has no EnumDecl")((ED && "EnumType has no EnumDecl") ? static_cast< void> (0) : __assert_fail ("ED && \"EnumType has no EnumDecl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 8181, __PRETTY_FUNCTION__)); |
8182 | |
8183 | DiagnoseUseOfDecl(ED, Loc); |
8184 | |
8185 | Underlying = ED->getIntegerType(); |
8186 | assert(!Underlying.isNull())((!Underlying.isNull()) ? static_cast<void> (0) : __assert_fail ("!Underlying.isNull()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 8186, __PRETTY_FUNCTION__)); |
8187 | } |
8188 | return Context.getUnaryTransformType(BaseType, Underlying, |
8189 | UnaryTransformType::EnumUnderlyingType); |
8190 | } |
8191 | } |
8192 | llvm_unreachable("unknown unary transform type")::llvm::llvm_unreachable_internal("unknown unary transform type" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaType.cpp" , 8192); |
8193 | } |
8194 | |
8195 | QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { |
8196 | if (!T->isDependentType()) { |
8197 | // FIXME: It isn't entirely clear whether incomplete atomic types |
8198 | // are allowed or not; for simplicity, ban them for the moment. |
8199 | if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) |
8200 | return QualType(); |
8201 | |
8202 | int DisallowedKind = -1; |
8203 | if (T->isArrayType()) |
8204 | DisallowedKind = 1; |
8205 | else if (T->isFunctionType()) |
8206 | DisallowedKind = 2; |
8207 | else if (T->isReferenceType()) |
8208 | DisallowedKind = 3; |
8209 | else if (T->isAtomicType()) |
8210 | DisallowedKind = 4; |
8211 | else if (T.hasQualifiers()) |
8212 | DisallowedKind = 5; |
8213 | else if (!T.isTriviallyCopyableType(Context)) |
8214 | // Some other non-trivially-copyable type (probably a C++ class) |
8215 | DisallowedKind = 6; |
8216 | |
8217 | if (DisallowedKind != -1) { |
8218 | Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; |
8219 | return QualType(); |
8220 | } |
8221 | |
8222 | // FIXME: Do we need any handling for ARC here? |
8223 | } |
8224 | |
8225 | // Build the pointer type. |
8226 | return Context.getAtomicType(T); |
8227 | } |