File: | tools/clang/lib/Sema/SemaType.cpp |
Warning: | line 8023, column 9 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file implements type-related semantic analysis. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "TypeLocBuilder.h" | |||
14 | #include "clang/AST/ASTConsumer.h" | |||
15 | #include "clang/AST/ASTContext.h" | |||
16 | #include "clang/AST/ASTMutationListener.h" | |||
17 | #include "clang/AST/ASTStructuralEquivalence.h" | |||
18 | #include "clang/AST/CXXInheritance.h" | |||
19 | #include "clang/AST/DeclObjC.h" | |||
20 | #include "clang/AST/DeclTemplate.h" | |||
21 | #include "clang/AST/Expr.h" | |||
22 | #include "clang/AST/TypeLoc.h" | |||
23 | #include "clang/AST/TypeLocVisitor.h" | |||
24 | #include "clang/Basic/PartialDiagnostic.h" | |||
25 | #include "clang/Basic/TargetInfo.h" | |||
26 | #include "clang/Lex/Preprocessor.h" | |||
27 | #include "clang/Sema/DeclSpec.h" | |||
28 | #include "clang/Sema/DelayedDiagnostic.h" | |||
29 | #include "clang/Sema/Lookup.h" | |||
30 | #include "clang/Sema/ScopeInfo.h" | |||
31 | #include "clang/Sema/SemaInternal.h" | |||
32 | #include "clang/Sema/Template.h" | |||
33 | #include "clang/Sema/TemplateInstCallback.h" | |||
34 | #include "llvm/ADT/SmallPtrSet.h" | |||
35 | #include "llvm/ADT/SmallString.h" | |||
36 | #include "llvm/ADT/StringSwitch.h" | |||
37 | #include "llvm/Support/ErrorHandling.h" | |||
38 | ||||
39 | using namespace clang; | |||
40 | ||||
41 | enum TypeDiagSelector { | |||
42 | TDS_Function, | |||
43 | TDS_Pointer, | |||
44 | TDS_ObjCObjOrBlock | |||
45 | }; | |||
46 | ||||
47 | /// isOmittedBlockReturnType - Return true if this declarator is missing a | |||
48 | /// return type because this is a omitted return type on a block literal. | |||
49 | static bool isOmittedBlockReturnType(const Declarator &D) { | |||
50 | if (D.getContext() != DeclaratorContext::BlockLiteralContext || | |||
51 | D.getDeclSpec().hasTypeSpecifier()) | |||
52 | return false; | |||
53 | ||||
54 | if (D.getNumTypeObjects() == 0) | |||
55 | return true; // ^{ ... } | |||
56 | ||||
57 | if (D.getNumTypeObjects() == 1 && | |||
58 | D.getTypeObject(0).Kind == DeclaratorChunk::Function) | |||
59 | return true; // ^(int X, float Y) { ... } | |||
60 | ||||
61 | return false; | |||
62 | } | |||
63 | ||||
64 | /// diagnoseBadTypeAttribute - Diagnoses a type attribute which | |||
65 | /// doesn't apply to the given type. | |||
66 | static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, | |||
67 | QualType type) { | |||
68 | TypeDiagSelector WhichType; | |||
69 | bool useExpansionLoc = true; | |||
70 | switch (attr.getKind()) { | |||
71 | case ParsedAttr::AT_ObjCGC: | |||
72 | WhichType = TDS_Pointer; | |||
73 | break; | |||
74 | case ParsedAttr::AT_ObjCOwnership: | |||
75 | WhichType = TDS_ObjCObjOrBlock; | |||
76 | break; | |||
77 | default: | |||
78 | // Assume everything else was a function attribute. | |||
79 | WhichType = TDS_Function; | |||
80 | useExpansionLoc = false; | |||
81 | break; | |||
82 | } | |||
83 | ||||
84 | SourceLocation loc = attr.getLoc(); | |||
85 | StringRef name = attr.getName()->getName(); | |||
86 | ||||
87 | // The GC attributes are usually written with macros; special-case them. | |||
88 | IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident | |||
89 | : nullptr; | |||
90 | if (useExpansionLoc && loc.isMacroID() && II) { | |||
91 | if (II->isStr("strong")) { | |||
92 | if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; | |||
93 | } else if (II->isStr("weak")) { | |||
94 | if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; | |||
95 | } | |||
96 | } | |||
97 | ||||
98 | S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType | |||
99 | << type; | |||
100 | } | |||
101 | ||||
102 | // objc_gc applies to Objective-C pointers or, otherwise, to the | |||
103 | // smallest available pointer type (i.e. 'void*' in 'void**'). | |||
104 | #define OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership \ | |||
105 | case ParsedAttr::AT_ObjCGC: \ | |||
106 | case ParsedAttr::AT_ObjCOwnership | |||
107 | ||||
108 | // Calling convention attributes. | |||
109 | #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 \ | |||
110 | case ParsedAttr::AT_CDecl: \ | |||
111 | case ParsedAttr::AT_FastCall: \ | |||
112 | case ParsedAttr::AT_StdCall: \ | |||
113 | case ParsedAttr::AT_ThisCall: \ | |||
114 | case ParsedAttr::AT_RegCall: \ | |||
115 | case ParsedAttr::AT_Pascal: \ | |||
116 | case ParsedAttr::AT_SwiftCall: \ | |||
117 | case ParsedAttr::AT_VectorCall: \ | |||
118 | case ParsedAttr::AT_AArch64VectorPcs: \ | |||
119 | case ParsedAttr::AT_MSABI: \ | |||
120 | case ParsedAttr::AT_SysVABI: \ | |||
121 | case ParsedAttr::AT_Pcs: \ | |||
122 | case ParsedAttr::AT_IntelOclBicc: \ | |||
123 | case ParsedAttr::AT_PreserveMost: \ | |||
124 | case ParsedAttr::AT_PreserveAll | |||
125 | ||||
126 | // Function type attributes. | |||
127 | #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_NoThrow : 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 \ | |||
128 | case ParsedAttr::AT_NSReturnsRetained: \ | |||
129 | case ParsedAttr::AT_NoReturn: \ | |||
130 | case ParsedAttr::AT_Regparm: \ | |||
131 | case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ | |||
132 | case ParsedAttr::AT_AnyX86NoCfCheck: \ | |||
133 | case ParsedAttr::AT_NoThrow: \ | |||
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 | /// MacroQualifiedTypes mapping to macro expansion locations that will be | |||
187 | /// stored in a MacroQualifiedTypeLoc. | |||
188 | llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros; | |||
189 | ||||
190 | /// Flag to indicate we parsed a noderef attribute. This is used for | |||
191 | /// validating that noderef was used on a pointer or array. | |||
192 | bool parsedNoDeref; | |||
193 | ||||
194 | public: | |||
195 | TypeProcessingState(Sema &sema, Declarator &declarator) | |||
196 | : sema(sema), declarator(declarator), | |||
197 | chunkIndex(declarator.getNumTypeObjects()), trivial(true), | |||
198 | hasSavedAttrs(false), parsedNoDeref(false) {} | |||
199 | ||||
200 | Sema &getSema() const { | |||
201 | return sema; | |||
202 | } | |||
203 | ||||
204 | Declarator &getDeclarator() const { | |||
205 | return declarator; | |||
206 | } | |||
207 | ||||
208 | bool isProcessingDeclSpec() const { | |||
209 | return chunkIndex == declarator.getNumTypeObjects(); | |||
210 | } | |||
211 | ||||
212 | unsigned getCurrentChunkIndex() const { | |||
213 | return chunkIndex; | |||
214 | } | |||
215 | ||||
216 | void setCurrentChunkIndex(unsigned idx) { | |||
217 | assert(idx <= declarator.getNumTypeObjects())((idx <= declarator.getNumTypeObjects()) ? static_cast< void> (0) : __assert_fail ("idx <= declarator.getNumTypeObjects()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 217, __PRETTY_FUNCTION__)); | |||
218 | chunkIndex = idx; | |||
219 | } | |||
220 | ||||
221 | ParsedAttributesView &getCurrentAttributes() const { | |||
222 | if (isProcessingDeclSpec()) | |||
223 | return getMutableDeclSpec().getAttributes(); | |||
224 | return declarator.getTypeObject(chunkIndex).getAttrs(); | |||
225 | } | |||
226 | ||||
227 | /// Save the current set of attributes on the DeclSpec. | |||
228 | void saveDeclSpecAttrs() { | |||
229 | // Don't try to save them multiple times. | |||
230 | if (hasSavedAttrs) return; | |||
231 | ||||
232 | DeclSpec &spec = getMutableDeclSpec(); | |||
233 | for (ParsedAttr &AL : spec.getAttributes()) | |||
234 | savedAttrs.push_back(&AL); | |||
235 | trivial &= savedAttrs.empty(); | |||
236 | hasSavedAttrs = true; | |||
237 | } | |||
238 | ||||
239 | /// Record that we had nowhere to put the given type attribute. | |||
240 | /// We will diagnose such attributes later. | |||
241 | void addIgnoredTypeAttr(ParsedAttr &attr) { | |||
242 | ignoredTypeAttrs.push_back(&attr); | |||
243 | } | |||
244 | ||||
245 | /// Diagnose all the ignored type attributes, given that the | |||
246 | /// declarator worked out to the given type. | |||
247 | void diagnoseIgnoredTypeAttrs(QualType type) const { | |||
248 | for (auto *Attr : ignoredTypeAttrs) | |||
249 | diagnoseBadTypeAttribute(getSema(), *Attr, type); | |||
250 | } | |||
251 | ||||
252 | /// Get an attributed type for the given attribute, and remember the Attr | |||
253 | /// object so that we can attach it to the AttributedTypeLoc. | |||
254 | QualType getAttributedType(Attr *A, QualType ModifiedType, | |||
255 | QualType EquivType) { | |||
256 | QualType T = | |||
257 | sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType); | |||
258 | AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A}); | |||
259 | AttrsForTypesSorted = false; | |||
260 | return T; | |||
261 | } | |||
262 | ||||
263 | /// Completely replace the \c auto in \p TypeWithAuto by | |||
264 | /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if | |||
265 | /// necessary. | |||
266 | QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) { | |||
267 | QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement); | |||
268 | if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) { | |||
269 | // Attributed type still should be an attributed type after replacement. | |||
270 | auto *NewAttrTy = cast<AttributedType>(T.getTypePtr()); | |||
271 | for (TypeAttrPair &A : AttrsForTypes) { | |||
272 | if (A.first == AttrTy) | |||
273 | A.first = NewAttrTy; | |||
274 | } | |||
275 | AttrsForTypesSorted = false; | |||
276 | } | |||
277 | return T; | |||
278 | } | |||
279 | ||||
280 | /// Extract and remove the Attr* for a given attributed type. | |||
281 | const Attr *takeAttrForAttributedType(const AttributedType *AT) { | |||
282 | if (!AttrsForTypesSorted) { | |||
283 | llvm::stable_sort(AttrsForTypes, llvm::less_first()); | |||
284 | AttrsForTypesSorted = true; | |||
285 | } | |||
286 | ||||
287 | // FIXME: This is quadratic if we have lots of reuses of the same | |||
288 | // attributed type. | |||
289 | for (auto It = std::partition_point( | |||
290 | AttrsForTypes.begin(), AttrsForTypes.end(), | |||
291 | [=](const TypeAttrPair &A) { return A.first < AT; }); | |||
292 | It != AttrsForTypes.end() && It->first == AT; ++It) { | |||
293 | if (It->second) { | |||
294 | const Attr *Result = It->second; | |||
295 | It->second = nullptr; | |||
296 | return Result; | |||
297 | } | |||
298 | } | |||
299 | ||||
300 | llvm_unreachable("no Attr* for AttributedType*")::llvm::llvm_unreachable_internal("no Attr* for AttributedType*" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 300); | |||
301 | } | |||
302 | ||||
303 | SourceLocation | |||
304 | getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const { | |||
305 | auto FoundLoc = LocsForMacros.find(MQT); | |||
306 | assert(FoundLoc != LocsForMacros.end() &&((FoundLoc != LocsForMacros.end() && "Unable to find macro expansion location for MacroQualifedType" ) ? static_cast<void> (0) : __assert_fail ("FoundLoc != LocsForMacros.end() && \"Unable to find macro expansion location for MacroQualifedType\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 307, __PRETTY_FUNCTION__)) | |||
307 | "Unable to find macro expansion location for MacroQualifedType")((FoundLoc != LocsForMacros.end() && "Unable to find macro expansion location for MacroQualifedType" ) ? static_cast<void> (0) : __assert_fail ("FoundLoc != LocsForMacros.end() && \"Unable to find macro expansion location for MacroQualifedType\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 307, __PRETTY_FUNCTION__)); | |||
308 | return FoundLoc->second; | |||
309 | } | |||
310 | ||||
311 | void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT, | |||
312 | SourceLocation Loc) { | |||
313 | LocsForMacros[MQT] = Loc; | |||
314 | } | |||
315 | ||||
316 | void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } | |||
317 | ||||
318 | bool didParseNoDeref() const { return parsedNoDeref; } | |||
319 | ||||
320 | ~TypeProcessingState() { | |||
321 | if (trivial) return; | |||
322 | ||||
323 | restoreDeclSpecAttrs(); | |||
324 | } | |||
325 | ||||
326 | private: | |||
327 | DeclSpec &getMutableDeclSpec() const { | |||
328 | return const_cast<DeclSpec&>(declarator.getDeclSpec()); | |||
329 | } | |||
330 | ||||
331 | void restoreDeclSpecAttrs() { | |||
332 | assert(hasSavedAttrs)((hasSavedAttrs) ? static_cast<void> (0) : __assert_fail ("hasSavedAttrs", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 332, __PRETTY_FUNCTION__)); | |||
333 | ||||
334 | getMutableDeclSpec().getAttributes().clearListOnly(); | |||
335 | for (ParsedAttr *AL : savedAttrs) | |||
336 | getMutableDeclSpec().getAttributes().addAtEnd(AL); | |||
337 | } | |||
338 | }; | |||
339 | } // end anonymous namespace | |||
340 | ||||
341 | static void moveAttrFromListToList(ParsedAttr &attr, | |||
342 | ParsedAttributesView &fromList, | |||
343 | ParsedAttributesView &toList) { | |||
344 | fromList.remove(&attr); | |||
345 | toList.addAtEnd(&attr); | |||
346 | } | |||
347 | ||||
348 | /// The location of a type attribute. | |||
349 | enum TypeAttrLocation { | |||
350 | /// The attribute is in the decl-specifier-seq. | |||
351 | TAL_DeclSpec, | |||
352 | /// The attribute is part of a DeclaratorChunk. | |||
353 | TAL_DeclChunk, | |||
354 | /// The attribute is immediately after the declaration's name. | |||
355 | TAL_DeclName | |||
356 | }; | |||
357 | ||||
358 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, | |||
359 | TypeAttrLocation TAL, ParsedAttributesView &attrs); | |||
360 | ||||
361 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
362 | QualType &type); | |||
363 | ||||
364 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, | |||
365 | ParsedAttr &attr, QualType &type); | |||
366 | ||||
367 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
368 | QualType &type); | |||
369 | ||||
370 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | |||
371 | ParsedAttr &attr, QualType &type); | |||
372 | ||||
373 | static bool handleObjCPointerTypeAttr(TypeProcessingState &state, | |||
374 | ParsedAttr &attr, QualType &type) { | |||
375 | if (attr.getKind() == ParsedAttr::AT_ObjCGC) | |||
376 | return handleObjCGCTypeAttr(state, attr, type); | |||
377 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 377, __PRETTY_FUNCTION__)); | |||
378 | return handleObjCOwnershipTypeAttr(state, attr, type); | |||
379 | } | |||
380 | ||||
381 | /// Given the index of a declarator chunk, check whether that chunk | |||
382 | /// directly specifies the return type of a function and, if so, find | |||
383 | /// an appropriate place for it. | |||
384 | /// | |||
385 | /// \param i - a notional index which the search will start | |||
386 | /// immediately inside | |||
387 | /// | |||
388 | /// \param onlyBlockPointers Whether we should only look into block | |||
389 | /// pointer types (vs. all pointer types). | |||
390 | static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, | |||
391 | unsigned i, | |||
392 | bool onlyBlockPointers) { | |||
393 | assert(i <= declarator.getNumTypeObjects())((i <= declarator.getNumTypeObjects()) ? static_cast<void > (0) : __assert_fail ("i <= declarator.getNumTypeObjects()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 393, __PRETTY_FUNCTION__)); | |||
394 | ||||
395 | DeclaratorChunk *result = nullptr; | |||
396 | ||||
397 | // First, look inwards past parens for a function declarator. | |||
398 | for (; i != 0; --i) { | |||
399 | DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); | |||
400 | switch (fnChunk.Kind) { | |||
401 | case DeclaratorChunk::Paren: | |||
402 | continue; | |||
403 | ||||
404 | // If we find anything except a function, bail out. | |||
405 | case DeclaratorChunk::Pointer: | |||
406 | case DeclaratorChunk::BlockPointer: | |||
407 | case DeclaratorChunk::Array: | |||
408 | case DeclaratorChunk::Reference: | |||
409 | case DeclaratorChunk::MemberPointer: | |||
410 | case DeclaratorChunk::Pipe: | |||
411 | return result; | |||
412 | ||||
413 | // If we do find a function declarator, scan inwards from that, | |||
414 | // looking for a (block-)pointer declarator. | |||
415 | case DeclaratorChunk::Function: | |||
416 | for (--i; i != 0; --i) { | |||
417 | DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); | |||
418 | switch (ptrChunk.Kind) { | |||
419 | case DeclaratorChunk::Paren: | |||
420 | case DeclaratorChunk::Array: | |||
421 | case DeclaratorChunk::Function: | |||
422 | case DeclaratorChunk::Reference: | |||
423 | case DeclaratorChunk::Pipe: | |||
424 | continue; | |||
425 | ||||
426 | case DeclaratorChunk::MemberPointer: | |||
427 | case DeclaratorChunk::Pointer: | |||
428 | if (onlyBlockPointers) | |||
429 | continue; | |||
430 | ||||
431 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
432 | ||||
433 | case DeclaratorChunk::BlockPointer: | |||
434 | result = &ptrChunk; | |||
435 | goto continue_outer; | |||
436 | } | |||
437 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 437); | |||
438 | } | |||
439 | ||||
440 | // If we run out of declarators doing that, we're done. | |||
441 | return result; | |||
442 | } | |||
443 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 443); | |||
444 | ||||
445 | // Okay, reconsider from our new point. | |||
446 | continue_outer: ; | |||
447 | } | |||
448 | ||||
449 | // Ran out of chunks, bail out. | |||
450 | return result; | |||
451 | } | |||
452 | ||||
453 | /// Given that an objc_gc attribute was written somewhere on a | |||
454 | /// declaration *other* than on the declarator itself (for which, use | |||
455 | /// distributeObjCPointerTypeAttrFromDeclarator), and given that it | |||
456 | /// didn't apply in whatever position it was written in, try to move | |||
457 | /// it to a more appropriate position. | |||
458 | static void distributeObjCPointerTypeAttr(TypeProcessingState &state, | |||
459 | ParsedAttr &attr, QualType type) { | |||
460 | Declarator &declarator = state.getDeclarator(); | |||
461 | ||||
462 | // Move it to the outermost normal or block pointer declarator. | |||
463 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
464 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
465 | switch (chunk.Kind) { | |||
466 | case DeclaratorChunk::Pointer: | |||
467 | case DeclaratorChunk::BlockPointer: { | |||
468 | // But don't move an ARC ownership attribute to the return type | |||
469 | // of a block. | |||
470 | DeclaratorChunk *destChunk = nullptr; | |||
471 | if (state.isProcessingDeclSpec() && | |||
472 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) | |||
473 | destChunk = maybeMovePastReturnType(declarator, i - 1, | |||
474 | /*onlyBlockPointers=*/true); | |||
475 | if (!destChunk) destChunk = &chunk; | |||
476 | ||||
477 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
478 | destChunk->getAttrs()); | |||
479 | return; | |||
480 | } | |||
481 | ||||
482 | case DeclaratorChunk::Paren: | |||
483 | case DeclaratorChunk::Array: | |||
484 | continue; | |||
485 | ||||
486 | // We may be starting at the return type of a block. | |||
487 | case DeclaratorChunk::Function: | |||
488 | if (state.isProcessingDeclSpec() && | |||
489 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) { | |||
490 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | |||
491 | declarator, i, | |||
492 | /*onlyBlockPointers=*/true)) { | |||
493 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
494 | dest->getAttrs()); | |||
495 | return; | |||
496 | } | |||
497 | } | |||
498 | goto error; | |||
499 | ||||
500 | // Don't walk through these. | |||
501 | case DeclaratorChunk::Reference: | |||
502 | case DeclaratorChunk::MemberPointer: | |||
503 | case DeclaratorChunk::Pipe: | |||
504 | goto error; | |||
505 | } | |||
506 | } | |||
507 | error: | |||
508 | ||||
509 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | |||
510 | } | |||
511 | ||||
512 | /// Distribute an objc_gc type attribute that was written on the | |||
513 | /// declarator. | |||
514 | static void distributeObjCPointerTypeAttrFromDeclarator( | |||
515 | TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { | |||
516 | Declarator &declarator = state.getDeclarator(); | |||
517 | ||||
518 | // objc_gc goes on the innermost pointer to something that's not a | |||
519 | // pointer. | |||
520 | unsigned innermost = -1U; | |||
521 | bool considerDeclSpec = true; | |||
522 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
523 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
524 | switch (chunk.Kind) { | |||
525 | case DeclaratorChunk::Pointer: | |||
526 | case DeclaratorChunk::BlockPointer: | |||
527 | innermost = i; | |||
528 | continue; | |||
529 | ||||
530 | case DeclaratorChunk::Reference: | |||
531 | case DeclaratorChunk::MemberPointer: | |||
532 | case DeclaratorChunk::Paren: | |||
533 | case DeclaratorChunk::Array: | |||
534 | case DeclaratorChunk::Pipe: | |||
535 | continue; | |||
536 | ||||
537 | case DeclaratorChunk::Function: | |||
538 | considerDeclSpec = false; | |||
539 | goto done; | |||
540 | } | |||
541 | } | |||
542 | done: | |||
543 | ||||
544 | // That might actually be the decl spec if we weren't blocked by | |||
545 | // anything in the declarator. | |||
546 | if (considerDeclSpec) { | |||
547 | if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { | |||
548 | // Splice the attribute into the decl spec. Prevents the | |||
549 | // attribute from being applied multiple times and gives | |||
550 | // the source-location-filler something to work with. | |||
551 | state.saveDeclSpecAttrs(); | |||
552 | declarator.getMutableDeclSpec().getAttributes().takeOneFrom( | |||
553 | declarator.getAttributes(), &attr); | |||
554 | return; | |||
555 | } | |||
556 | } | |||
557 | ||||
558 | // Otherwise, if we found an appropriate chunk, splice the attribute | |||
559 | // into it. | |||
560 | if (innermost != -1U) { | |||
561 | moveAttrFromListToList(attr, declarator.getAttributes(), | |||
562 | declarator.getTypeObject(innermost).getAttrs()); | |||
563 | return; | |||
564 | } | |||
565 | ||||
566 | // Otherwise, diagnose when we're done building the type. | |||
567 | declarator.getAttributes().remove(&attr); | |||
568 | state.addIgnoredTypeAttr(attr); | |||
569 | } | |||
570 | ||||
571 | /// A function type attribute was written somewhere in a declaration | |||
572 | /// *other* than on the declarator itself or in the decl spec. Given | |||
573 | /// that it didn't apply in whatever position it was written in, try | |||
574 | /// to move it to a more appropriate position. | |||
575 | static void distributeFunctionTypeAttr(TypeProcessingState &state, | |||
576 | ParsedAttr &attr, QualType type) { | |||
577 | Declarator &declarator = state.getDeclarator(); | |||
578 | ||||
579 | // Try to push the attribute from the return type of a function to | |||
580 | // the function itself. | |||
581 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
582 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
583 | switch (chunk.Kind) { | |||
584 | case DeclaratorChunk::Function: | |||
585 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
586 | chunk.getAttrs()); | |||
587 | return; | |||
588 | ||||
589 | case DeclaratorChunk::Paren: | |||
590 | case DeclaratorChunk::Pointer: | |||
591 | case DeclaratorChunk::BlockPointer: | |||
592 | case DeclaratorChunk::Array: | |||
593 | case DeclaratorChunk::Reference: | |||
594 | case DeclaratorChunk::MemberPointer: | |||
595 | case DeclaratorChunk::Pipe: | |||
596 | continue; | |||
597 | } | |||
598 | } | |||
599 | ||||
600 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | |||
601 | } | |||
602 | ||||
603 | /// Try to distribute a function type attribute to the innermost | |||
604 | /// function chunk or type. Returns true if the attribute was | |||
605 | /// distributed, false if no location was found. | |||
606 | static bool distributeFunctionTypeAttrToInnermost( | |||
607 | TypeProcessingState &state, ParsedAttr &attr, | |||
608 | ParsedAttributesView &attrList, QualType &declSpecType) { | |||
609 | Declarator &declarator = state.getDeclarator(); | |||
610 | ||||
611 | // Put it on the innermost function chunk, if there is one. | |||
612 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
613 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
614 | if (chunk.Kind != DeclaratorChunk::Function) continue; | |||
615 | ||||
616 | moveAttrFromListToList(attr, attrList, chunk.getAttrs()); | |||
617 | return true; | |||
618 | } | |||
619 | ||||
620 | return handleFunctionTypeAttr(state, attr, declSpecType); | |||
621 | } | |||
622 | ||||
623 | /// A function type attribute was written in the decl spec. Try to | |||
624 | /// apply it somewhere. | |||
625 | static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, | |||
626 | ParsedAttr &attr, | |||
627 | QualType &declSpecType) { | |||
628 | state.saveDeclSpecAttrs(); | |||
629 | ||||
630 | // C++11 attributes before the decl specifiers actually appertain to | |||
631 | // the declarators. Move them straight there. We don't support the | |||
632 | // 'put them wherever you like' semantics we allow for GNU attributes. | |||
633 | if (attr.isCXX11Attribute()) { | |||
634 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
635 | state.getDeclarator().getAttributes()); | |||
636 | return; | |||
637 | } | |||
638 | ||||
639 | // Try to distribute to the innermost. | |||
640 | if (distributeFunctionTypeAttrToInnermost( | |||
641 | state, attr, state.getCurrentAttributes(), declSpecType)) | |||
642 | return; | |||
643 | ||||
644 | // If that failed, diagnose the bad attribute when the declarator is | |||
645 | // fully built. | |||
646 | state.addIgnoredTypeAttr(attr); | |||
647 | } | |||
648 | ||||
649 | /// A function type attribute was written on the declarator. Try to | |||
650 | /// apply it somewhere. | |||
651 | static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, | |||
652 | ParsedAttr &attr, | |||
653 | QualType &declSpecType) { | |||
654 | Declarator &declarator = state.getDeclarator(); | |||
655 | ||||
656 | // Try to distribute to the innermost. | |||
657 | if (distributeFunctionTypeAttrToInnermost( | |||
658 | state, attr, declarator.getAttributes(), declSpecType)) | |||
659 | return; | |||
660 | ||||
661 | // If that failed, diagnose the bad attribute when the declarator is | |||
662 | // fully built. | |||
663 | declarator.getAttributes().remove(&attr); | |||
664 | state.addIgnoredTypeAttr(attr); | |||
665 | } | |||
666 | ||||
667 | /// Given that there are attributes written on the declarator | |||
668 | /// itself, try to distribute any type attributes to the appropriate | |||
669 | /// declarator chunk. | |||
670 | /// | |||
671 | /// These are attributes like the following: | |||
672 | /// int f ATTR; | |||
673 | /// int (f ATTR)(); | |||
674 | /// but not necessarily this: | |||
675 | /// int f() ATTR; | |||
676 | static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, | |||
677 | QualType &declSpecType) { | |||
678 | // Collect all the type attributes from the declarator itself. | |||
679 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 680, __PRETTY_FUNCTION__)) | |||
680 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 680, __PRETTY_FUNCTION__)); | |||
681 | // The called functions in this loop actually remove things from the current | |||
682 | // list, so iterating over the existing list isn't possible. Instead, make a | |||
683 | // non-owning copy and iterate over that. | |||
684 | ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; | |||
685 | for (ParsedAttr &attr : AttrsCopy) { | |||
686 | // Do not distribute C++11 attributes. They have strict rules for what | |||
687 | // they appertain to. | |||
688 | if (attr.isCXX11Attribute()) | |||
689 | continue; | |||
690 | ||||
691 | switch (attr.getKind()) { | |||
692 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: | |||
693 | distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); | |||
694 | break; | |||
695 | ||||
696 | 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_NoThrow : 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: | |||
697 | distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType); | |||
698 | break; | |||
699 | ||||
700 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: | |||
701 | // Microsoft type attributes cannot go after the declarator-id. | |||
702 | continue; | |||
703 | ||||
704 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullUnspecified: | |||
705 | // Nullability specifiers cannot go after the declarator-id. | |||
706 | ||||
707 | // Objective-C __kindof does not get distributed. | |||
708 | case ParsedAttr::AT_ObjCKindOf: | |||
709 | continue; | |||
710 | ||||
711 | default: | |||
712 | break; | |||
713 | } | |||
714 | } | |||
715 | } | |||
716 | ||||
717 | /// Add a synthetic '()' to a block-literal declarator if it is | |||
718 | /// required, given the return type. | |||
719 | static void maybeSynthesizeBlockSignature(TypeProcessingState &state, | |||
720 | QualType declSpecType) { | |||
721 | Declarator &declarator = state.getDeclarator(); | |||
722 | ||||
723 | // First, check whether the declarator would produce a function, | |||
724 | // i.e. whether the innermost semantic chunk is a function. | |||
725 | if (declarator.isFunctionDeclarator()) { | |||
726 | // If so, make that declarator a prototyped declarator. | |||
727 | declarator.getFunctionTypeInfo().hasPrototype = true; | |||
728 | return; | |||
729 | } | |||
730 | ||||
731 | // If there are any type objects, the type as written won't name a | |||
732 | // function, regardless of the decl spec type. This is because a | |||
733 | // block signature declarator is always an abstract-declarator, and | |||
734 | // abstract-declarators can't just be parentheses chunks. Therefore | |||
735 | // we need to build a function chunk unless there are no type | |||
736 | // objects and the decl spec type is a function. | |||
737 | if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) | |||
738 | return; | |||
739 | ||||
740 | // Note that there *are* cases with invalid declarators where | |||
741 | // declarators consist solely of parentheses. In general, these | |||
742 | // occur only in failed efforts to make function declarators, so | |||
743 | // faking up the function chunk is still the right thing to do. | |||
744 | ||||
745 | // Otherwise, we need to fake up a function declarator. | |||
746 | SourceLocation loc = declarator.getBeginLoc(); | |||
747 | ||||
748 | // ...and *prepend* it to the declarator. | |||
749 | SourceLocation NoLoc; | |||
750 | declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( | |||
751 | /*HasProto=*/true, | |||
752 | /*IsAmbiguous=*/false, | |||
753 | /*LParenLoc=*/NoLoc, | |||
754 | /*ArgInfo=*/nullptr, | |||
755 | /*NumArgs=*/0, | |||
756 | /*EllipsisLoc=*/NoLoc, | |||
757 | /*RParenLoc=*/NoLoc, | |||
758 | /*RefQualifierIsLvalueRef=*/true, | |||
759 | /*RefQualifierLoc=*/NoLoc, | |||
760 | /*MutableLoc=*/NoLoc, EST_None, | |||
761 | /*ESpecRange=*/SourceRange(), | |||
762 | /*Exceptions=*/nullptr, | |||
763 | /*ExceptionRanges=*/nullptr, | |||
764 | /*NumExceptions=*/0, | |||
765 | /*NoexceptExpr=*/nullptr, | |||
766 | /*ExceptionSpecTokens=*/nullptr, | |||
767 | /*DeclsInPrototype=*/None, loc, loc, declarator)); | |||
768 | ||||
769 | // For consistency, make sure the state still has us as processing | |||
770 | // the decl spec. | |||
771 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 771, __PRETTY_FUNCTION__)); | |||
772 | state.setCurrentChunkIndex(declarator.getNumTypeObjects()); | |||
773 | } | |||
774 | ||||
775 | static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, | |||
776 | unsigned &TypeQuals, | |||
777 | QualType TypeSoFar, | |||
778 | unsigned RemoveTQs, | |||
779 | unsigned DiagID) { | |||
780 | // If this occurs outside a template instantiation, warn the user about | |||
781 | // it; they probably didn't mean to specify a redundant qualifier. | |||
782 | typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; | |||
783 | for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), | |||
784 | QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), | |||
785 | QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), | |||
786 | QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { | |||
787 | if (!(RemoveTQs & Qual.first)) | |||
788 | continue; | |||
789 | ||||
790 | if (!S.inTemplateInstantiation()) { | |||
791 | if (TypeQuals & Qual.first) | |||
792 | S.Diag(Qual.second, DiagID) | |||
793 | << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar | |||
794 | << FixItHint::CreateRemoval(Qual.second); | |||
795 | } | |||
796 | ||||
797 | TypeQuals &= ~Qual.first; | |||
798 | } | |||
799 | } | |||
800 | ||||
801 | /// Return true if this is omitted block return type. Also check type | |||
802 | /// attributes and type qualifiers when returning true. | |||
803 | static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, | |||
804 | QualType Result) { | |||
805 | if (!isOmittedBlockReturnType(declarator)) | |||
806 | return false; | |||
807 | ||||
808 | // Warn if we see type attributes for omitted return type on a block literal. | |||
809 | SmallVector<ParsedAttr *, 2> ToBeRemoved; | |||
810 | for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { | |||
811 | if (AL.isInvalid() || !AL.isTypeAttr()) | |||
812 | continue; | |||
813 | S.Diag(AL.getLoc(), | |||
814 | diag::warn_block_literal_attributes_on_omitted_return_type) | |||
815 | << AL.getName(); | |||
816 | ToBeRemoved.push_back(&AL); | |||
817 | } | |||
818 | // Remove bad attributes from the list. | |||
819 | for (ParsedAttr *AL : ToBeRemoved) | |||
820 | declarator.getMutableDeclSpec().getAttributes().remove(AL); | |||
821 | ||||
822 | // Warn if we see type qualifiers for omitted return type on a block literal. | |||
823 | const DeclSpec &DS = declarator.getDeclSpec(); | |||
824 | unsigned TypeQuals = DS.getTypeQualifiers(); | |||
825 | diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, | |||
826 | diag::warn_block_literal_qualifiers_on_omitted_return_type); | |||
827 | declarator.getMutableDeclSpec().ClearTypeQualifiers(); | |||
828 | ||||
829 | return true; | |||
830 | } | |||
831 | ||||
832 | /// Apply Objective-C type arguments to the given type. | |||
833 | static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, | |||
834 | ArrayRef<TypeSourceInfo *> typeArgs, | |||
835 | SourceRange typeArgsRange, | |||
836 | bool failOnError = false) { | |||
837 | // We can only apply type arguments to an Objective-C class type. | |||
838 | const auto *objcObjectType = type->getAs<ObjCObjectType>(); | |||
839 | if (!objcObjectType || !objcObjectType->getInterface()) { | |||
840 | S.Diag(loc, diag::err_objc_type_args_non_class) | |||
841 | << type | |||
842 | << typeArgsRange; | |||
843 | ||||
844 | if (failOnError) | |||
845 | return QualType(); | |||
846 | return type; | |||
847 | } | |||
848 | ||||
849 | // The class type must be parameterized. | |||
850 | ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); | |||
851 | ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); | |||
852 | if (!typeParams) { | |||
853 | S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) | |||
854 | << objcClass->getDeclName() | |||
855 | << FixItHint::CreateRemoval(typeArgsRange); | |||
856 | ||||
857 | if (failOnError) | |||
858 | return QualType(); | |||
859 | ||||
860 | return type; | |||
861 | } | |||
862 | ||||
863 | // The type must not already be specialized. | |||
864 | if (objcObjectType->isSpecialized()) { | |||
865 | S.Diag(loc, diag::err_objc_type_args_specialized_class) | |||
866 | << type | |||
867 | << FixItHint::CreateRemoval(typeArgsRange); | |||
868 | ||||
869 | if (failOnError) | |||
870 | return QualType(); | |||
871 | ||||
872 | return type; | |||
873 | } | |||
874 | ||||
875 | // Check the type arguments. | |||
876 | SmallVector<QualType, 4> finalTypeArgs; | |||
877 | unsigned numTypeParams = typeParams->size(); | |||
878 | bool anyPackExpansions = false; | |||
879 | for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { | |||
880 | TypeSourceInfo *typeArgInfo = typeArgs[i]; | |||
881 | QualType typeArg = typeArgInfo->getType(); | |||
882 | ||||
883 | // Type arguments cannot have explicit qualifiers or nullability. | |||
884 | // We ignore indirect sources of these, e.g. behind typedefs or | |||
885 | // template arguments. | |||
886 | if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { | |||
887 | bool diagnosed = false; | |||
888 | SourceRange rangeToRemove; | |||
889 | if (auto attr = qual.getAs<AttributedTypeLoc>()) { | |||
890 | rangeToRemove = attr.getLocalSourceRange(); | |||
891 | if (attr.getTypePtr()->getImmediateNullability()) { | |||
892 | typeArg = attr.getTypePtr()->getModifiedType(); | |||
893 | S.Diag(attr.getBeginLoc(), | |||
894 | diag::err_objc_type_arg_explicit_nullability) | |||
895 | << typeArg << FixItHint::CreateRemoval(rangeToRemove); | |||
896 | diagnosed = true; | |||
897 | } | |||
898 | } | |||
899 | ||||
900 | if (!diagnosed) { | |||
901 | S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified) | |||
902 | << typeArg << typeArg.getQualifiers().getAsString() | |||
903 | << FixItHint::CreateRemoval(rangeToRemove); | |||
904 | } | |||
905 | } | |||
906 | ||||
907 | // Remove qualifiers even if they're non-local. | |||
908 | typeArg = typeArg.getUnqualifiedType(); | |||
909 | ||||
910 | finalTypeArgs.push_back(typeArg); | |||
911 | ||||
912 | if (typeArg->getAs<PackExpansionType>()) | |||
913 | anyPackExpansions = true; | |||
914 | ||||
915 | // Find the corresponding type parameter, if there is one. | |||
916 | ObjCTypeParamDecl *typeParam = nullptr; | |||
917 | if (!anyPackExpansions) { | |||
918 | if (i < numTypeParams) { | |||
919 | typeParam = typeParams->begin()[i]; | |||
920 | } else { | |||
921 | // Too many arguments. | |||
922 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | |||
923 | << false | |||
924 | << objcClass->getDeclName() | |||
925 | << (unsigned)typeArgs.size() | |||
926 | << numTypeParams; | |||
927 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | |||
928 | << objcClass; | |||
929 | ||||
930 | if (failOnError) | |||
931 | return QualType(); | |||
932 | ||||
933 | return type; | |||
934 | } | |||
935 | } | |||
936 | ||||
937 | // Objective-C object pointer types must be substitutable for the bounds. | |||
938 | if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { | |||
939 | // If we don't have a type parameter to match against, assume | |||
940 | // everything is fine. There was a prior pack expansion that | |||
941 | // means we won't be able to match anything. | |||
942 | if (!typeParam) { | |||
943 | assert(anyPackExpansions && "Too many arguments?")((anyPackExpansions && "Too many arguments?") ? static_cast <void> (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 943, __PRETTY_FUNCTION__)); | |||
944 | continue; | |||
945 | } | |||
946 | ||||
947 | // Retrieve the bound. | |||
948 | QualType bound = typeParam->getUnderlyingType(); | |||
949 | const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); | |||
950 | ||||
951 | // Determine whether the type argument is substitutable for the bound. | |||
952 | if (typeArgObjC->isObjCIdType()) { | |||
953 | // When the type argument is 'id', the only acceptable type | |||
954 | // parameter bound is 'id'. | |||
955 | if (boundObjC->isObjCIdType()) | |||
956 | continue; | |||
957 | } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { | |||
958 | // Otherwise, we follow the assignability rules. | |||
959 | continue; | |||
960 | } | |||
961 | ||||
962 | // Diagnose the mismatch. | |||
963 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | |||
964 | diag::err_objc_type_arg_does_not_match_bound) | |||
965 | << typeArg << bound << typeParam->getDeclName(); | |||
966 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | |||
967 | << typeParam->getDeclName(); | |||
968 | ||||
969 | if (failOnError) | |||
970 | return QualType(); | |||
971 | ||||
972 | return type; | |||
973 | } | |||
974 | ||||
975 | // Block pointer types are permitted for unqualified 'id' bounds. | |||
976 | if (typeArg->isBlockPointerType()) { | |||
977 | // If we don't have a type parameter to match against, assume | |||
978 | // everything is fine. There was a prior pack expansion that | |||
979 | // means we won't be able to match anything. | |||
980 | if (!typeParam) { | |||
981 | assert(anyPackExpansions && "Too many arguments?")((anyPackExpansions && "Too many arguments?") ? static_cast <void> (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 981, __PRETTY_FUNCTION__)); | |||
982 | continue; | |||
983 | } | |||
984 | ||||
985 | // Retrieve the bound. | |||
986 | QualType bound = typeParam->getUnderlyingType(); | |||
987 | if (bound->isBlockCompatibleObjCPointerType(S.Context)) | |||
988 | continue; | |||
989 | ||||
990 | // Diagnose the mismatch. | |||
991 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | |||
992 | diag::err_objc_type_arg_does_not_match_bound) | |||
993 | << typeArg << bound << typeParam->getDeclName(); | |||
994 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | |||
995 | << typeParam->getDeclName(); | |||
996 | ||||
997 | if (failOnError) | |||
998 | return QualType(); | |||
999 | ||||
1000 | return type; | |||
1001 | } | |||
1002 | ||||
1003 | // Dependent types will be checked at instantiation time. | |||
1004 | if (typeArg->isDependentType()) { | |||
1005 | continue; | |||
1006 | } | |||
1007 | ||||
1008 | // Diagnose non-id-compatible type arguments. | |||
1009 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | |||
1010 | diag::err_objc_type_arg_not_id_compatible) | |||
1011 | << typeArg << typeArgInfo->getTypeLoc().getSourceRange(); | |||
1012 | ||||
1013 | if (failOnError) | |||
1014 | return QualType(); | |||
1015 | ||||
1016 | return type; | |||
1017 | } | |||
1018 | ||||
1019 | // Make sure we didn't have the wrong number of arguments. | |||
1020 | if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { | |||
1021 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | |||
1022 | << (typeArgs.size() < typeParams->size()) | |||
1023 | << objcClass->getDeclName() | |||
1024 | << (unsigned)finalTypeArgs.size() | |||
1025 | << (unsigned)numTypeParams; | |||
1026 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | |||
1027 | << objcClass; | |||
1028 | ||||
1029 | if (failOnError) | |||
1030 | return QualType(); | |||
1031 | ||||
1032 | return type; | |||
1033 | } | |||
1034 | ||||
1035 | // Success. Form the specialized type. | |||
1036 | return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); | |||
1037 | } | |||
1038 | ||||
1039 | QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, | |||
1040 | SourceLocation ProtocolLAngleLoc, | |||
1041 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
1042 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1043 | SourceLocation ProtocolRAngleLoc, | |||
1044 | bool FailOnError) { | |||
1045 | QualType Result = QualType(Decl->getTypeForDecl(), 0); | |||
1046 | if (!Protocols.empty()) { | |||
1047 | bool HasError; | |||
1048 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | |||
1049 | HasError); | |||
1050 | if (HasError) { | |||
1051 | Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) | |||
1052 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | |||
1053 | if (FailOnError) Result = QualType(); | |||
1054 | } | |||
1055 | if (FailOnError && Result.isNull()) | |||
1056 | return QualType(); | |||
1057 | } | |||
1058 | ||||
1059 | return Result; | |||
1060 | } | |||
1061 | ||||
1062 | QualType Sema::BuildObjCObjectType(QualType BaseType, | |||
1063 | SourceLocation Loc, | |||
1064 | SourceLocation TypeArgsLAngleLoc, | |||
1065 | ArrayRef<TypeSourceInfo *> TypeArgs, | |||
1066 | SourceLocation TypeArgsRAngleLoc, | |||
1067 | SourceLocation ProtocolLAngleLoc, | |||
1068 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
1069 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1070 | SourceLocation ProtocolRAngleLoc, | |||
1071 | bool FailOnError) { | |||
1072 | QualType Result = BaseType; | |||
1073 | if (!TypeArgs.empty()) { | |||
1074 | Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, | |||
1075 | SourceRange(TypeArgsLAngleLoc, | |||
1076 | TypeArgsRAngleLoc), | |||
1077 | FailOnError); | |||
1078 | if (FailOnError && Result.isNull()) | |||
1079 | return QualType(); | |||
1080 | } | |||
1081 | ||||
1082 | if (!Protocols.empty()) { | |||
1083 | bool HasError; | |||
1084 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | |||
1085 | HasError); | |||
1086 | if (HasError) { | |||
1087 | Diag(Loc, diag::err_invalid_protocol_qualifiers) | |||
1088 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | |||
1089 | if (FailOnError) Result = QualType(); | |||
1090 | } | |||
1091 | if (FailOnError && Result.isNull()) | |||
1092 | return QualType(); | |||
1093 | } | |||
1094 | ||||
1095 | return Result; | |||
1096 | } | |||
1097 | ||||
1098 | TypeResult Sema::actOnObjCProtocolQualifierType( | |||
1099 | SourceLocation lAngleLoc, | |||
1100 | ArrayRef<Decl *> protocols, | |||
1101 | ArrayRef<SourceLocation> protocolLocs, | |||
1102 | SourceLocation rAngleLoc) { | |||
1103 | // Form id<protocol-list>. | |||
1104 | QualType Result = Context.getObjCObjectType( | |||
1105 | Context.ObjCBuiltinIdTy, { }, | |||
1106 | llvm::makeArrayRef( | |||
1107 | (ObjCProtocolDecl * const *)protocols.data(), | |||
1108 | protocols.size()), | |||
1109 | false); | |||
1110 | Result = Context.getObjCObjectPointerType(Result); | |||
1111 | ||||
1112 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | |||
1113 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | |||
1114 | ||||
1115 | auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); | |||
1116 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit | |||
1117 | ||||
1118 | auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() | |||
1119 | .castAs<ObjCObjectTypeLoc>(); | |||
1120 | ObjCObjectTL.setHasBaseTypeAsWritten(false); | |||
1121 | ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); | |||
1122 | ||||
1123 | // No type arguments. | |||
1124 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | |||
1125 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | |||
1126 | ||||
1127 | // Fill in protocol qualifiers. | |||
1128 | ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); | |||
1129 | ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); | |||
1130 | for (unsigned i = 0, n = protocols.size(); i != n; ++i) | |||
1131 | ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); | |||
1132 | ||||
1133 | // We're done. Return the completed type to the parser. | |||
1134 | return CreateParsedType(Result, ResultTInfo); | |||
1135 | } | |||
1136 | ||||
1137 | TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( | |||
1138 | Scope *S, | |||
1139 | SourceLocation Loc, | |||
1140 | ParsedType BaseType, | |||
1141 | SourceLocation TypeArgsLAngleLoc, | |||
1142 | ArrayRef<ParsedType> TypeArgs, | |||
1143 | SourceLocation TypeArgsRAngleLoc, | |||
1144 | SourceLocation ProtocolLAngleLoc, | |||
1145 | ArrayRef<Decl *> Protocols, | |||
1146 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1147 | SourceLocation ProtocolRAngleLoc) { | |||
1148 | TypeSourceInfo *BaseTypeInfo = nullptr; | |||
1149 | QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); | |||
1150 | if (T.isNull()) | |||
1151 | return true; | |||
1152 | ||||
1153 | // Handle missing type-source info. | |||
1154 | if (!BaseTypeInfo) | |||
1155 | BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
1156 | ||||
1157 | // Extract type arguments. | |||
1158 | SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; | |||
1159 | for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { | |||
1160 | TypeSourceInfo *TypeArgInfo = nullptr; | |||
1161 | QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); | |||
1162 | if (TypeArg.isNull()) { | |||
1163 | ActualTypeArgInfos.clear(); | |||
1164 | break; | |||
1165 | } | |||
1166 | ||||
1167 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1167, __PRETTY_FUNCTION__)); | |||
1168 | ActualTypeArgInfos.push_back(TypeArgInfo); | |||
1169 | } | |||
1170 | ||||
1171 | // Build the object type. | |||
1172 | QualType Result = BuildObjCObjectType( | |||
1173 | T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), | |||
1174 | TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, | |||
1175 | ProtocolLAngleLoc, | |||
1176 | llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), | |||
1177 | Protocols.size()), | |||
1178 | ProtocolLocs, ProtocolRAngleLoc, | |||
1179 | /*FailOnError=*/false); | |||
1180 | ||||
1181 | if (Result == T) | |||
1182 | return BaseType; | |||
1183 | ||||
1184 | // Create source information for this type. | |||
1185 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | |||
1186 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | |||
1187 | ||||
1188 | // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an | |||
1189 | // object pointer type. Fill in source information for it. | |||
1190 | if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { | |||
1191 | // The '*' is implicit. | |||
1192 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); | |||
1193 | ResultTL = ObjCObjectPointerTL.getPointeeLoc(); | |||
1194 | } | |||
1195 | ||||
1196 | if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) { | |||
1197 | // Protocol qualifier information. | |||
1198 | if (OTPTL.getNumProtocols() > 0) { | |||
1199 | assert(OTPTL.getNumProtocols() == Protocols.size())((OTPTL.getNumProtocols() == Protocols.size()) ? static_cast< void> (0) : __assert_fail ("OTPTL.getNumProtocols() == Protocols.size()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1199, __PRETTY_FUNCTION__)); | |||
1200 | OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | |||
1201 | OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | |||
1202 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | |||
1203 | OTPTL.setProtocolLoc(i, ProtocolLocs[i]); | |||
1204 | } | |||
1205 | ||||
1206 | // We're done. Return the completed type to the parser. | |||
1207 | return CreateParsedType(Result, ResultTInfo); | |||
1208 | } | |||
1209 | ||||
1210 | auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); | |||
1211 | ||||
1212 | // Type argument information. | |||
1213 | if (ObjCObjectTL.getNumTypeArgs() > 0) { | |||
1214 | assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size())((ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()) ? static_cast<void> (0) : __assert_fail ("ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1214, __PRETTY_FUNCTION__)); | |||
1215 | ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); | |||
1216 | ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); | |||
1217 | for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) | |||
1218 | ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); | |||
1219 | } else { | |||
1220 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | |||
1221 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | |||
1222 | } | |||
1223 | ||||
1224 | // Protocol qualifier information. | |||
1225 | if (ObjCObjectTL.getNumProtocols() > 0) { | |||
1226 | assert(ObjCObjectTL.getNumProtocols() == Protocols.size())((ObjCObjectTL.getNumProtocols() == Protocols.size()) ? static_cast <void> (0) : __assert_fail ("ObjCObjectTL.getNumProtocols() == Protocols.size()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1226, __PRETTY_FUNCTION__)); | |||
1227 | ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | |||
1228 | ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | |||
1229 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | |||
1230 | ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); | |||
1231 | } else { | |||
1232 | ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); | |||
1233 | ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); | |||
1234 | } | |||
1235 | ||||
1236 | // Base type. | |||
1237 | ObjCObjectTL.setHasBaseTypeAsWritten(true); | |||
1238 | if (ObjCObjectTL.getType() == T) | |||
1239 | ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); | |||
1240 | else | |||
1241 | ObjCObjectTL.getBaseLoc().initialize(Context, Loc); | |||
1242 | ||||
1243 | // We're done. Return the completed type to the parser. | |||
1244 | return CreateParsedType(Result, ResultTInfo); | |||
1245 | } | |||
1246 | ||||
1247 | static OpenCLAccessAttr::Spelling | |||
1248 | getImageAccess(const ParsedAttributesView &Attrs) { | |||
1249 | for (const ParsedAttr &AL : Attrs) | |||
1250 | if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) | |||
1251 | return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); | |||
1252 | return OpenCLAccessAttr::Keyword_read_only; | |||
1253 | } | |||
1254 | ||||
1255 | /// Convert the specified declspec to the appropriate type | |||
1256 | /// object. | |||
1257 | /// \param state Specifies the declarator containing the declaration specifier | |||
1258 | /// to be converted, along with other associated processing state. | |||
1259 | /// \returns The type described by the declaration specifiers. This function | |||
1260 | /// never returns null. | |||
1261 | static QualType ConvertDeclSpecToType(TypeProcessingState &state) { | |||
1262 | // FIXME: Should move the logic from DeclSpec::Finish to here for validity | |||
1263 | // checking. | |||
1264 | ||||
1265 | Sema &S = state.getSema(); | |||
1266 | Declarator &declarator = state.getDeclarator(); | |||
1267 | DeclSpec &DS = declarator.getMutableDeclSpec(); | |||
1268 | SourceLocation DeclLoc = declarator.getIdentifierLoc(); | |||
1269 | if (DeclLoc.isInvalid()) | |||
1270 | DeclLoc = DS.getBeginLoc(); | |||
1271 | ||||
1272 | ASTContext &Context = S.Context; | |||
1273 | ||||
1274 | QualType Result; | |||
1275 | switch (DS.getTypeSpecType()) { | |||
1276 | case DeclSpec::TST_void: | |||
1277 | Result = Context.VoidTy; | |||
1278 | break; | |||
1279 | case DeclSpec::TST_char: | |||
1280 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) | |||
1281 | Result = Context.CharTy; | |||
1282 | else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) | |||
1283 | Result = Context.SignedCharTy; | |||
1284 | else { | |||
1285 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1286, __PRETTY_FUNCTION__)) | |||
1286 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1286, __PRETTY_FUNCTION__)); | |||
1287 | Result = Context.UnsignedCharTy; | |||
1288 | } | |||
1289 | break; | |||
1290 | case DeclSpec::TST_wchar: | |||
1291 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) | |||
1292 | Result = Context.WCharTy; | |||
1293 | else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { | |||
1294 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) | |||
1295 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1296 | Context.getPrintingPolicy()); | |||
1297 | Result = Context.getSignedWCharType(); | |||
1298 | } else { | |||
1299 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1300, __PRETTY_FUNCTION__)) | |||
1300 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1300, __PRETTY_FUNCTION__)); | |||
1301 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) | |||
1302 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1303 | Context.getPrintingPolicy()); | |||
1304 | Result = Context.getUnsignedWCharType(); | |||
1305 | } | |||
1306 | break; | |||
1307 | case DeclSpec::TST_char8: | |||
1308 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1309, __PRETTY_FUNCTION__)) | |||
1309 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1309, __PRETTY_FUNCTION__)); | |||
1310 | Result = Context.Char8Ty; | |||
1311 | break; | |||
1312 | case DeclSpec::TST_char16: | |||
1313 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1314, __PRETTY_FUNCTION__)) | |||
1314 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1314, __PRETTY_FUNCTION__)); | |||
1315 | Result = Context.Char16Ty; | |||
1316 | break; | |||
1317 | case DeclSpec::TST_char32: | |||
1318 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1319, __PRETTY_FUNCTION__)) | |||
1319 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1319, __PRETTY_FUNCTION__)); | |||
1320 | Result = Context.Char32Ty; | |||
1321 | break; | |||
1322 | case DeclSpec::TST_unspecified: | |||
1323 | // If this is a missing declspec in a block literal return context, then it | |||
1324 | // is inferred from the return statements inside the block. | |||
1325 | // The declspec is always missing in a lambda expr context; it is either | |||
1326 | // specified with a trailing return type or inferred. | |||
1327 | if (S.getLangOpts().CPlusPlus14 && | |||
1328 | declarator.getContext() == DeclaratorContext::LambdaExprContext) { | |||
1329 | // In C++1y, a lambda's implicit return type is 'auto'. | |||
1330 | Result = Context.getAutoDeductType(); | |||
1331 | break; | |||
1332 | } else if (declarator.getContext() == | |||
1333 | DeclaratorContext::LambdaExprContext || | |||
1334 | checkOmittedBlockReturnType(S, declarator, | |||
1335 | Context.DependentTy)) { | |||
1336 | Result = Context.DependentTy; | |||
1337 | break; | |||
1338 | } | |||
1339 | ||||
1340 | // Unspecified typespec defaults to int in C90. However, the C90 grammar | |||
1341 | // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, | |||
1342 | // type-qualifier, or storage-class-specifier. If not, emit an extwarn. | |||
1343 | // Note that the one exception to this is function definitions, which are | |||
1344 | // allowed to be completely missing a declspec. This is handled in the | |||
1345 | // parser already though by it pretending to have seen an 'int' in this | |||
1346 | // case. | |||
1347 | if (S.getLangOpts().ImplicitInt) { | |||
1348 | // In C89 mode, we only warn if there is a completely missing declspec | |||
1349 | // when one is not allowed. | |||
1350 | if (DS.isEmpty()) { | |||
1351 | S.Diag(DeclLoc, diag::ext_missing_declspec) | |||
1352 | << DS.getSourceRange() | |||
1353 | << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); | |||
1354 | } | |||
1355 | } else if (!DS.hasTypeSpecifier()) { | |||
1356 | // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: | |||
1357 | // "At least one type specifier shall be given in the declaration | |||
1358 | // specifiers in each declaration, and in the specifier-qualifier list in | |||
1359 | // each struct declaration and type name." | |||
1360 | if (S.getLangOpts().CPlusPlus && !DS.isTypeSpecPipe()) { | |||
1361 | S.Diag(DeclLoc, diag::err_missing_type_specifier) | |||
1362 | << DS.getSourceRange(); | |||
1363 | ||||
1364 | // When this occurs in C++ code, often something is very broken with the | |||
1365 | // value being declared, poison it as invalid so we don't get chains of | |||
1366 | // errors. | |||
1367 | declarator.setInvalidType(true); | |||
1368 | } else if ((S.getLangOpts().OpenCLVersion >= 200 || | |||
1369 | S.getLangOpts().OpenCLCPlusPlus) && | |||
1370 | DS.isTypeSpecPipe()) { | |||
1371 | S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) | |||
1372 | << DS.getSourceRange(); | |||
1373 | declarator.setInvalidType(true); | |||
1374 | } else { | |||
1375 | S.Diag(DeclLoc, diag::ext_missing_type_specifier) | |||
1376 | << DS.getSourceRange(); | |||
1377 | } | |||
1378 | } | |||
1379 | ||||
1380 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
1381 | case DeclSpec::TST_int: { | |||
1382 | if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { | |||
1383 | switch (DS.getTypeSpecWidth()) { | |||
1384 | case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; | |||
1385 | case DeclSpec::TSW_short: Result = Context.ShortTy; break; | |||
1386 | case DeclSpec::TSW_long: Result = Context.LongTy; break; | |||
1387 | case DeclSpec::TSW_longlong: | |||
1388 | Result = Context.LongLongTy; | |||
1389 | ||||
1390 | // 'long long' is a C99 or C++11 feature. | |||
1391 | if (!S.getLangOpts().C99) { | |||
1392 | if (S.getLangOpts().CPlusPlus) | |||
1393 | S.Diag(DS.getTypeSpecWidthLoc(), | |||
1394 | S.getLangOpts().CPlusPlus11 ? | |||
1395 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
1396 | else | |||
1397 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | |||
1398 | } | |||
1399 | break; | |||
1400 | } | |||
1401 | } else { | |||
1402 | switch (DS.getTypeSpecWidth()) { | |||
1403 | case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; | |||
1404 | case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; | |||
1405 | case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; | |||
1406 | case DeclSpec::TSW_longlong: | |||
1407 | Result = Context.UnsignedLongLongTy; | |||
1408 | ||||
1409 | // 'long long' is a C99 or C++11 feature. | |||
1410 | if (!S.getLangOpts().C99) { | |||
1411 | if (S.getLangOpts().CPlusPlus) | |||
1412 | S.Diag(DS.getTypeSpecWidthLoc(), | |||
1413 | S.getLangOpts().CPlusPlus11 ? | |||
1414 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
1415 | else | |||
1416 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | |||
1417 | } | |||
1418 | break; | |||
1419 | } | |||
1420 | } | |||
1421 | break; | |||
1422 | } | |||
1423 | case DeclSpec::TST_accum: { | |||
1424 | switch (DS.getTypeSpecWidth()) { | |||
1425 | case DeclSpec::TSW_short: | |||
1426 | Result = Context.ShortAccumTy; | |||
1427 | break; | |||
1428 | case DeclSpec::TSW_unspecified: | |||
1429 | Result = Context.AccumTy; | |||
1430 | break; | |||
1431 | case DeclSpec::TSW_long: | |||
1432 | Result = Context.LongAccumTy; | |||
1433 | break; | |||
1434 | case DeclSpec::TSW_longlong: | |||
1435 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1435); | |||
1436 | } | |||
1437 | ||||
1438 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) | |||
1439 | Result = Context.getCorrespondingUnsignedType(Result); | |||
1440 | ||||
1441 | if (DS.isTypeSpecSat()) | |||
1442 | Result = Context.getCorrespondingSaturatedType(Result); | |||
1443 | ||||
1444 | break; | |||
1445 | } | |||
1446 | case DeclSpec::TST_fract: { | |||
1447 | switch (DS.getTypeSpecWidth()) { | |||
1448 | case DeclSpec::TSW_short: | |||
1449 | Result = Context.ShortFractTy; | |||
1450 | break; | |||
1451 | case DeclSpec::TSW_unspecified: | |||
1452 | Result = Context.FractTy; | |||
1453 | break; | |||
1454 | case DeclSpec::TSW_long: | |||
1455 | Result = Context.LongFractTy; | |||
1456 | break; | |||
1457 | case DeclSpec::TSW_longlong: | |||
1458 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1458); | |||
1459 | } | |||
1460 | ||||
1461 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) | |||
1462 | Result = Context.getCorrespondingUnsignedType(Result); | |||
1463 | ||||
1464 | if (DS.isTypeSpecSat()) | |||
1465 | Result = Context.getCorrespondingSaturatedType(Result); | |||
1466 | ||||
1467 | break; | |||
1468 | } | |||
1469 | case DeclSpec::TST_int128: | |||
1470 | if (!S.Context.getTargetInfo().hasInt128Type() && | |||
1471 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | |||
1472 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1473 | << "__int128"; | |||
1474 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) | |||
1475 | Result = Context.UnsignedInt128Ty; | |||
1476 | else | |||
1477 | Result = Context.Int128Ty; | |||
1478 | break; | |||
1479 | case DeclSpec::TST_float16: | |||
1480 | // CUDA host and device may have different _Float16 support, therefore | |||
1481 | // do not diagnose _Float16 usage to avoid false alarm. | |||
1482 | // ToDo: more precise diagnostics for CUDA. | |||
1483 | if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA && | |||
1484 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | |||
1485 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1486 | << "_Float16"; | |||
1487 | Result = Context.Float16Ty; | |||
1488 | break; | |||
1489 | case DeclSpec::TST_half: Result = Context.HalfTy; break; | |||
1490 | case DeclSpec::TST_float: Result = Context.FloatTy; break; | |||
1491 | case DeclSpec::TST_double: | |||
1492 | if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) | |||
1493 | Result = Context.LongDoubleTy; | |||
1494 | else | |||
1495 | Result = Context.DoubleTy; | |||
1496 | break; | |||
1497 | case DeclSpec::TST_float128: | |||
1498 | if (!S.Context.getTargetInfo().hasFloat128Type() && | |||
1499 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | |||
1500 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1501 | << "__float128"; | |||
1502 | Result = Context.Float128Ty; | |||
1503 | break; | |||
1504 | case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool | |||
1505 | break; | |||
1506 | case DeclSpec::TST_decimal32: // _Decimal32 | |||
1507 | case DeclSpec::TST_decimal64: // _Decimal64 | |||
1508 | case DeclSpec::TST_decimal128: // _Decimal128 | |||
1509 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); | |||
1510 | Result = Context.IntTy; | |||
1511 | declarator.setInvalidType(true); | |||
1512 | break; | |||
1513 | case DeclSpec::TST_class: | |||
1514 | case DeclSpec::TST_enum: | |||
1515 | case DeclSpec::TST_union: | |||
1516 | case DeclSpec::TST_struct: | |||
1517 | case DeclSpec::TST_interface: { | |||
1518 | TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()); | |||
1519 | if (!D) { | |||
1520 | // This can happen in C++ with ambiguous lookups. | |||
1521 | Result = Context.IntTy; | |||
1522 | declarator.setInvalidType(true); | |||
1523 | break; | |||
1524 | } | |||
1525 | ||||
1526 | // If the type is deprecated or unavailable, diagnose it. | |||
1527 | S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); | |||
1528 | ||||
1529 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1530, __PRETTY_FUNCTION__)) | |||
1530 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1530, __PRETTY_FUNCTION__)); | |||
1531 | ||||
1532 | // TypeQuals handled by caller. | |||
1533 | Result = Context.getTypeDeclType(D); | |||
1534 | ||||
1535 | // In both C and C++, make an ElaboratedType. | |||
1536 | ElaboratedTypeKeyword Keyword | |||
1537 | = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); | |||
1538 | Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result, | |||
1539 | DS.isTypeSpecOwned() ? D : nullptr); | |||
1540 | break; | |||
1541 | } | |||
1542 | case DeclSpec::TST_typename: { | |||
1543 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1545, __PRETTY_FUNCTION__)) | |||
1544 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1545, __PRETTY_FUNCTION__)) | |||
1545 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1545, __PRETTY_FUNCTION__)); | |||
1546 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1547 | if (Result.isNull()) { | |||
1548 | declarator.setInvalidType(true); | |||
1549 | } | |||
1550 | ||||
1551 | // TypeQuals handled by caller. | |||
1552 | break; | |||
1553 | } | |||
1554 | case DeclSpec::TST_typeofType: | |||
1555 | // FIXME: Preserve type source info. | |||
1556 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1557 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1557, __PRETTY_FUNCTION__)); | |||
1558 | if (!Result->isDependentType()) | |||
1559 | if (const TagType *TT = Result->getAs<TagType>()) | |||
1560 | S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); | |||
1561 | // TypeQuals handled by caller. | |||
1562 | Result = Context.getTypeOfType(Result); | |||
1563 | break; | |||
1564 | case DeclSpec::TST_typeofExpr: { | |||
1565 | Expr *E = DS.getRepAsExpr(); | |||
1566 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1566, __PRETTY_FUNCTION__)); | |||
1567 | // TypeQuals handled by caller. | |||
1568 | Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); | |||
1569 | if (Result.isNull()) { | |||
1570 | Result = Context.IntTy; | |||
1571 | declarator.setInvalidType(true); | |||
1572 | } | |||
1573 | break; | |||
1574 | } | |||
1575 | case DeclSpec::TST_decltype: { | |||
1576 | Expr *E = DS.getRepAsExpr(); | |||
1577 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1577, __PRETTY_FUNCTION__)); | |||
1578 | // TypeQuals handled by caller. | |||
1579 | Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); | |||
1580 | if (Result.isNull()) { | |||
1581 | Result = Context.IntTy; | |||
1582 | declarator.setInvalidType(true); | |||
1583 | } | |||
1584 | break; | |||
1585 | } | |||
1586 | case DeclSpec::TST_underlyingType: | |||
1587 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1588 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1588, __PRETTY_FUNCTION__)); | |||
1589 | Result = S.BuildUnaryTransformType(Result, | |||
1590 | UnaryTransformType::EnumUnderlyingType, | |||
1591 | DS.getTypeSpecTypeLoc()); | |||
1592 | if (Result.isNull()) { | |||
1593 | Result = Context.IntTy; | |||
1594 | declarator.setInvalidType(true); | |||
1595 | } | |||
1596 | break; | |||
1597 | ||||
1598 | case DeclSpec::TST_auto: | |||
1599 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false); | |||
1600 | break; | |||
1601 | ||||
1602 | case DeclSpec::TST_auto_type: | |||
1603 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); | |||
1604 | break; | |||
1605 | ||||
1606 | case DeclSpec::TST_decltype_auto: | |||
1607 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto, | |||
1608 | /*IsDependent*/ false); | |||
1609 | break; | |||
1610 | ||||
1611 | case DeclSpec::TST_unknown_anytype: | |||
1612 | Result = Context.UnknownAnyTy; | |||
1613 | break; | |||
1614 | ||||
1615 | case DeclSpec::TST_atomic: | |||
1616 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1617 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1617, __PRETTY_FUNCTION__)); | |||
1618 | Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); | |||
1619 | if (Result.isNull()) { | |||
1620 | Result = Context.IntTy; | |||
1621 | declarator.setInvalidType(true); | |||
1622 | } | |||
1623 | break; | |||
1624 | ||||
1625 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ | |||
1626 | case DeclSpec::TST_##ImgType##_t: \ | |||
1627 | switch (getImageAccess(DS.getAttributes())) { \ | |||
1628 | case OpenCLAccessAttr::Keyword_write_only: \ | |||
1629 | Result = Context.Id##WOTy; \ | |||
1630 | break; \ | |||
1631 | case OpenCLAccessAttr::Keyword_read_write: \ | |||
1632 | Result = Context.Id##RWTy; \ | |||
1633 | break; \ | |||
1634 | case OpenCLAccessAttr::Keyword_read_only: \ | |||
1635 | Result = Context.Id##ROTy; \ | |||
1636 | break; \ | |||
1637 | } \ | |||
1638 | break; | |||
1639 | #include "clang/Basic/OpenCLImageTypes.def" | |||
1640 | ||||
1641 | case DeclSpec::TST_error: | |||
1642 | Result = Context.IntTy; | |||
1643 | declarator.setInvalidType(true); | |||
1644 | break; | |||
1645 | } | |||
1646 | ||||
1647 | if (S.getLangOpts().OpenCL && | |||
1648 | S.checkOpenCLDisabledTypeDeclSpec(DS, Result)) | |||
1649 | declarator.setInvalidType(true); | |||
1650 | ||||
1651 | bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum || | |||
1652 | DS.getTypeSpecType() == DeclSpec::TST_fract; | |||
1653 | ||||
1654 | // Only fixed point types can be saturated | |||
1655 | if (DS.isTypeSpecSat() && !IsFixedPointType) | |||
1656 | S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec) | |||
1657 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1658 | Context.getPrintingPolicy()); | |||
1659 | ||||
1660 | // Handle complex types. | |||
1661 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { | |||
1662 | if (S.getLangOpts().Freestanding) | |||
1663 | S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); | |||
1664 | Result = Context.getComplexType(Result); | |||
1665 | } else if (DS.isTypeAltiVecVector()) { | |||
1666 | unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); | |||
1667 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1667, __PRETTY_FUNCTION__)); | |||
1668 | VectorType::VectorKind VecKind = VectorType::AltiVecVector; | |||
1669 | if (DS.isTypeAltiVecPixel()) | |||
1670 | VecKind = VectorType::AltiVecPixel; | |||
1671 | else if (DS.isTypeAltiVecBool()) | |||
1672 | VecKind = VectorType::AltiVecBool; | |||
1673 | Result = Context.getVectorType(Result, 128/typeSize, VecKind); | |||
1674 | } | |||
1675 | ||||
1676 | // FIXME: Imaginary. | |||
1677 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) | |||
1678 | S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); | |||
1679 | ||||
1680 | // Before we process any type attributes, synthesize a block literal | |||
1681 | // function declarator if necessary. | |||
1682 | if (declarator.getContext() == DeclaratorContext::BlockLiteralContext) | |||
1683 | maybeSynthesizeBlockSignature(state, Result); | |||
1684 | ||||
1685 | // Apply any type attributes from the decl spec. This may cause the | |||
1686 | // list of type attributes to be temporarily saved while the type | |||
1687 | // attributes are pushed around. | |||
1688 | // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) | |||
1689 | if (!DS.isTypeSpecPipe()) | |||
1690 | processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes()); | |||
1691 | ||||
1692 | // Apply const/volatile/restrict qualifiers to T. | |||
1693 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | |||
1694 | // Warn about CV qualifiers on function types. | |||
1695 | // C99 6.7.3p8: | |||
1696 | // If the specification of a function type includes any type qualifiers, | |||
1697 | // the behavior is undefined. | |||
1698 | // C++11 [dcl.fct]p7: | |||
1699 | // The effect of a cv-qualifier-seq in a function declarator is not the | |||
1700 | // same as adding cv-qualification on top of the function type. In the | |||
1701 | // latter case, the cv-qualifiers are ignored. | |||
1702 | if (TypeQuals && Result->isFunctionType()) { | |||
1703 | diagnoseAndRemoveTypeQualifiers( | |||
1704 | S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, | |||
1705 | S.getLangOpts().CPlusPlus | |||
1706 | ? diag::warn_typecheck_function_qualifiers_ignored | |||
1707 | : diag::warn_typecheck_function_qualifiers_unspecified); | |||
1708 | // No diagnostic for 'restrict' or '_Atomic' applied to a | |||
1709 | // function type; we'll diagnose those later, in BuildQualifiedType. | |||
1710 | } | |||
1711 | ||||
1712 | // C++11 [dcl.ref]p1: | |||
1713 | // Cv-qualified references are ill-formed except when the | |||
1714 | // cv-qualifiers are introduced through the use of a typedef-name | |||
1715 | // or decltype-specifier, in which case the cv-qualifiers are ignored. | |||
1716 | // | |||
1717 | // There don't appear to be any other contexts in which a cv-qualified | |||
1718 | // reference type could be formed, so the 'ill-formed' clause here appears | |||
1719 | // to never happen. | |||
1720 | if (TypeQuals && Result->isReferenceType()) { | |||
1721 | diagnoseAndRemoveTypeQualifiers( | |||
1722 | S, DS, TypeQuals, Result, | |||
1723 | DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, | |||
1724 | diag::warn_typecheck_reference_qualifiers); | |||
1725 | } | |||
1726 | ||||
1727 | // C90 6.5.3 constraints: "The same type qualifier shall not appear more | |||
1728 | // than once in the same specifier-list or qualifier-list, either directly | |||
1729 | // or via one or more typedefs." | |||
1730 | if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus | |||
1731 | && TypeQuals & Result.getCVRQualifiers()) { | |||
1732 | if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { | |||
1733 | S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) | |||
1734 | << "const"; | |||
1735 | } | |||
1736 | ||||
1737 | if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { | |||
1738 | S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) | |||
1739 | << "volatile"; | |||
1740 | } | |||
1741 | ||||
1742 | // C90 doesn't have restrict nor _Atomic, so it doesn't force us to | |||
1743 | // produce a warning in this case. | |||
1744 | } | |||
1745 | ||||
1746 | QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); | |||
1747 | ||||
1748 | // If adding qualifiers fails, just use the unqualified type. | |||
1749 | if (Qualified.isNull()) | |||
1750 | declarator.setInvalidType(true); | |||
1751 | else | |||
1752 | Result = Qualified; | |||
1753 | } | |||
1754 | ||||
1755 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1755, __PRETTY_FUNCTION__)); | |||
1756 | return Result; | |||
1757 | } | |||
1758 | ||||
1759 | static std::string getPrintableNameForEntity(DeclarationName Entity) { | |||
1760 | if (Entity) | |||
1761 | return Entity.getAsString(); | |||
1762 | ||||
1763 | return "type name"; | |||
1764 | } | |||
1765 | ||||
1766 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | |||
1767 | Qualifiers Qs, const DeclSpec *DS) { | |||
1768 | if (T.isNull()) | |||
1769 | return QualType(); | |||
1770 | ||||
1771 | // Ignore any attempt to form a cv-qualified reference. | |||
1772 | if (T->isReferenceType()) { | |||
1773 | Qs.removeConst(); | |||
1774 | Qs.removeVolatile(); | |||
1775 | } | |||
1776 | ||||
1777 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from | |||
1778 | // object or incomplete types shall not be restrict-qualified." | |||
1779 | if (Qs.hasRestrict()) { | |||
1780 | unsigned DiagID = 0; | |||
1781 | QualType ProblemTy; | |||
1782 | ||||
1783 | if (T->isAnyPointerType() || T->isReferenceType() || | |||
1784 | T->isMemberPointerType()) { | |||
1785 | QualType EltTy; | |||
1786 | if (T->isObjCObjectPointerType()) | |||
1787 | EltTy = T; | |||
1788 | else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) | |||
1789 | EltTy = PTy->getPointeeType(); | |||
1790 | else | |||
1791 | EltTy = T->getPointeeType(); | |||
1792 | ||||
1793 | // If we have a pointer or reference, the pointee must have an object | |||
1794 | // incomplete type. | |||
1795 | if (!EltTy->isIncompleteOrObjectType()) { | |||
1796 | DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; | |||
1797 | ProblemTy = EltTy; | |||
1798 | } | |||
1799 | } else if (!T->isDependentType()) { | |||
1800 | DiagID = diag::err_typecheck_invalid_restrict_not_pointer; | |||
1801 | ProblemTy = T; | |||
1802 | } | |||
1803 | ||||
1804 | if (DiagID) { | |||
1805 | Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; | |||
1806 | Qs.removeRestrict(); | |||
1807 | } | |||
1808 | } | |||
1809 | ||||
1810 | return Context.getQualifiedType(T, Qs); | |||
1811 | } | |||
1812 | ||||
1813 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | |||
1814 | unsigned CVRAU, const DeclSpec *DS) { | |||
1815 | if (T.isNull()) | |||
1816 | return QualType(); | |||
1817 | ||||
1818 | // Ignore any attempt to form a cv-qualified reference. | |||
1819 | if (T->isReferenceType()) | |||
1820 | CVRAU &= | |||
1821 | ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); | |||
1822 | ||||
1823 | // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and | |||
1824 | // TQ_unaligned; | |||
1825 | unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); | |||
1826 | ||||
1827 | // C11 6.7.3/5: | |||
1828 | // If the same qualifier appears more than once in the same | |||
1829 | // specifier-qualifier-list, either directly or via one or more typedefs, | |||
1830 | // the behavior is the same as if it appeared only once. | |||
1831 | // | |||
1832 | // It's not specified what happens when the _Atomic qualifier is applied to | |||
1833 | // a type specified with the _Atomic specifier, but we assume that this | |||
1834 | // should be treated as if the _Atomic qualifier appeared multiple times. | |||
1835 | if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { | |||
1836 | // C11 6.7.3/5: | |||
1837 | // If other qualifiers appear along with the _Atomic qualifier in a | |||
1838 | // specifier-qualifier-list, the resulting type is the so-qualified | |||
1839 | // atomic type. | |||
1840 | // | |||
1841 | // Don't need to worry about array types here, since _Atomic can't be | |||
1842 | // applied to such types. | |||
1843 | SplitQualType Split = T.getSplitUnqualifiedType(); | |||
1844 | T = BuildAtomicType(QualType(Split.Ty, 0), | |||
1845 | DS ? DS->getAtomicSpecLoc() : Loc); | |||
1846 | if (T.isNull()) | |||
1847 | return T; | |||
1848 | Split.Quals.addCVRQualifiers(CVR); | |||
1849 | return BuildQualifiedType(T, Loc, Split.Quals); | |||
1850 | } | |||
1851 | ||||
1852 | Qualifiers Q = Qualifiers::fromCVRMask(CVR); | |||
1853 | Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); | |||
1854 | return BuildQualifiedType(T, Loc, Q, DS); | |||
1855 | } | |||
1856 | ||||
1857 | /// Build a paren type including \p T. | |||
1858 | QualType Sema::BuildParenType(QualType T) { | |||
1859 | return Context.getParenType(T); | |||
1860 | } | |||
1861 | ||||
1862 | /// Given that we're building a pointer or reference to the given | |||
1863 | static QualType inferARCLifetimeForPointee(Sema &S, QualType type, | |||
1864 | SourceLocation loc, | |||
1865 | bool isReference) { | |||
1866 | // Bail out if retention is unrequired or already specified. | |||
1867 | if (!type->isObjCLifetimeType() || | |||
1868 | type.getObjCLifetime() != Qualifiers::OCL_None) | |||
1869 | return type; | |||
1870 | ||||
1871 | Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; | |||
1872 | ||||
1873 | // If the object type is const-qualified, we can safely use | |||
1874 | // __unsafe_unretained. This is safe (because there are no read | |||
1875 | // barriers), and it'll be safe to coerce anything but __weak* to | |||
1876 | // the resulting type. | |||
1877 | if (type.isConstQualified()) { | |||
1878 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | |||
1879 | ||||
1880 | // Otherwise, check whether the static type does not require | |||
1881 | // retaining. This currently only triggers for Class (possibly | |||
1882 | // protocol-qualifed, and arrays thereof). | |||
1883 | } else if (type->isObjCARCImplicitlyUnretainedType()) { | |||
1884 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | |||
1885 | ||||
1886 | // If we are in an unevaluated context, like sizeof, skip adding a | |||
1887 | // qualification. | |||
1888 | } else if (S.isUnevaluatedContext()) { | |||
1889 | return type; | |||
1890 | ||||
1891 | // If that failed, give an error and recover using __strong. __strong | |||
1892 | // is the option most likely to prevent spurious second-order diagnostics, | |||
1893 | // like when binding a reference to a field. | |||
1894 | } else { | |||
1895 | // These types can show up in private ivars in system headers, so | |||
1896 | // we need this to not be an error in those cases. Instead we | |||
1897 | // want to delay. | |||
1898 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | |||
1899 | S.DelayedDiagnostics.add( | |||
1900 | sema::DelayedDiagnostic::makeForbiddenType(loc, | |||
1901 | diag::err_arc_indirect_no_ownership, type, isReference)); | |||
1902 | } else { | |||
1903 | S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; | |||
1904 | } | |||
1905 | implicitLifetime = Qualifiers::OCL_Strong; | |||
1906 | } | |||
1907 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1907, __PRETTY_FUNCTION__)); | |||
1908 | ||||
1909 | Qualifiers qs; | |||
1910 | qs.addObjCLifetime(implicitLifetime); | |||
1911 | return S.Context.getQualifiedType(type, qs); | |||
1912 | } | |||
1913 | ||||
1914 | static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ | |||
1915 | std::string Quals = FnTy->getMethodQuals().getAsString(); | |||
1916 | ||||
1917 | switch (FnTy->getRefQualifier()) { | |||
1918 | case RQ_None: | |||
1919 | break; | |||
1920 | ||||
1921 | case RQ_LValue: | |||
1922 | if (!Quals.empty()) | |||
1923 | Quals += ' '; | |||
1924 | Quals += '&'; | |||
1925 | break; | |||
1926 | ||||
1927 | case RQ_RValue: | |||
1928 | if (!Quals.empty()) | |||
1929 | Quals += ' '; | |||
1930 | Quals += "&&"; | |||
1931 | break; | |||
1932 | } | |||
1933 | ||||
1934 | return Quals; | |||
1935 | } | |||
1936 | ||||
1937 | namespace { | |||
1938 | /// Kinds of declarator that cannot contain a qualified function type. | |||
1939 | /// | |||
1940 | /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: | |||
1941 | /// a function type with a cv-qualifier or a ref-qualifier can only appear | |||
1942 | /// at the topmost level of a type. | |||
1943 | /// | |||
1944 | /// Parens and member pointers are permitted. We don't diagnose array and | |||
1945 | /// function declarators, because they don't allow function types at all. | |||
1946 | /// | |||
1947 | /// The values of this enum are used in diagnostics. | |||
1948 | enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; | |||
1949 | } // end anonymous namespace | |||
1950 | ||||
1951 | /// Check whether the type T is a qualified function type, and if it is, | |||
1952 | /// diagnose that it cannot be contained within the given kind of declarator. | |||
1953 | static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, | |||
1954 | QualifiedFunctionKind QFK) { | |||
1955 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | |||
1956 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); | |||
1957 | if (!FPT || (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) | |||
1958 | return false; | |||
1959 | ||||
1960 | S.Diag(Loc, diag::err_compound_qualified_function_type) | |||
1961 | << QFK << isa<FunctionType>(T.IgnoreParens()) << T | |||
1962 | << getFunctionQualifiersAsString(FPT); | |||
1963 | return true; | |||
1964 | } | |||
1965 | ||||
1966 | /// Build a pointer type. | |||
1967 | /// | |||
1968 | /// \param T The type to which we'll be building a pointer. | |||
1969 | /// | |||
1970 | /// \param Loc The location of the entity whose type involves this | |||
1971 | /// pointer type or, if there is no such entity, the location of the | |||
1972 | /// type that will have pointer type. | |||
1973 | /// | |||
1974 | /// \param Entity The name of the entity that involves the pointer | |||
1975 | /// type, if known. | |||
1976 | /// | |||
1977 | /// \returns A suitable pointer type, if there are no | |||
1978 | /// errors. Otherwise, returns a NULL type. | |||
1979 | QualType Sema::BuildPointerType(QualType T, | |||
1980 | SourceLocation Loc, DeclarationName Entity) { | |||
1981 | if (T->isReferenceType()) { | |||
1982 | // C++ 8.3.2p4: There shall be no ... pointers to references ... | |||
1983 | Diag(Loc, diag::err_illegal_decl_pointer_to_reference) | |||
1984 | << getPrintableNameForEntity(Entity) << T; | |||
1985 | return QualType(); | |||
1986 | } | |||
1987 | ||||
1988 | if (T->isFunctionType() && getLangOpts().OpenCL) { | |||
1989 | Diag(Loc, diag::err_opencl_function_pointer); | |||
1990 | return QualType(); | |||
1991 | } | |||
1992 | ||||
1993 | if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) | |||
1994 | return QualType(); | |||
1995 | ||||
1996 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 1996, __PRETTY_FUNCTION__)); | |||
1997 | ||||
1998 | // In ARC, it is forbidden to build pointers to unqualified pointers. | |||
1999 | if (getLangOpts().ObjCAutoRefCount) | |||
2000 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); | |||
2001 | ||||
2002 | // Build the pointer type. | |||
2003 | return Context.getPointerType(T); | |||
2004 | } | |||
2005 | ||||
2006 | /// Build a reference type. | |||
2007 | /// | |||
2008 | /// \param T The type to which we'll be building a reference. | |||
2009 | /// | |||
2010 | /// \param Loc The location of the entity whose type involves this | |||
2011 | /// reference type or, if there is no such entity, the location of the | |||
2012 | /// type that will have reference type. | |||
2013 | /// | |||
2014 | /// \param Entity The name of the entity that involves the reference | |||
2015 | /// type, if known. | |||
2016 | /// | |||
2017 | /// \returns A suitable reference type, if there are no | |||
2018 | /// errors. Otherwise, returns a NULL type. | |||
2019 | QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, | |||
2020 | SourceLocation Loc, | |||
2021 | DeclarationName Entity) { | |||
2022 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 2023, __PRETTY_FUNCTION__)) | |||
2023 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 2023, __PRETTY_FUNCTION__)); | |||
2024 | ||||
2025 | // C++0x [dcl.ref]p6: | |||
2026 | // If a typedef (7.1.3), a type template-parameter (14.3.1), or a | |||
2027 | // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a | |||
2028 | // type T, an attempt to create the type "lvalue reference to cv TR" creates | |||
2029 | // the type "lvalue reference to T", while an attempt to create the type | |||
2030 | // "rvalue reference to cv TR" creates the type TR. | |||
2031 | bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); | |||
2032 | ||||
2033 | // C++ [dcl.ref]p4: There shall be no references to references. | |||
2034 | // | |||
2035 | // According to C++ DR 106, references to references are only | |||
2036 | // diagnosed when they are written directly (e.g., "int & &"), | |||
2037 | // but not when they happen via a typedef: | |||
2038 | // | |||
2039 | // typedef int& intref; | |||
2040 | // typedef intref& intref2; | |||
2041 | // | |||
2042 | // Parser::ParseDeclaratorInternal diagnoses the case where | |||
2043 | // references are written directly; here, we handle the | |||
2044 | // collapsing of references-to-references as described in C++0x. | |||
2045 | // DR 106 and 540 introduce reference-collapsing into C++98/03. | |||
2046 | ||||
2047 | // C++ [dcl.ref]p1: | |||
2048 | // A declarator that specifies the type "reference to cv void" | |||
2049 | // is ill-formed. | |||
2050 | if (T->isVoidType()) { | |||
2051 | Diag(Loc, diag::err_reference_to_void); | |||
2052 | return QualType(); | |||
2053 | } | |||
2054 | ||||
2055 | if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) | |||
2056 | return QualType(); | |||
2057 | ||||
2058 | // In ARC, it is forbidden to build references to unqualified pointers. | |||
2059 | if (getLangOpts().ObjCAutoRefCount) | |||
2060 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); | |||
2061 | ||||
2062 | // Handle restrict on references. | |||
2063 | if (LValueRef) | |||
2064 | return Context.getLValueReferenceType(T, SpelledAsLValue); | |||
2065 | return Context.getRValueReferenceType(T); | |||
2066 | } | |||
2067 | ||||
2068 | /// Build a Read-only Pipe type. | |||
2069 | /// | |||
2070 | /// \param T The type to which we'll be building a Pipe. | |||
2071 | /// | |||
2072 | /// \param Loc We do not use it for now. | |||
2073 | /// | |||
2074 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | |||
2075 | /// NULL type. | |||
2076 | QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { | |||
2077 | return Context.getReadPipeType(T); | |||
2078 | } | |||
2079 | ||||
2080 | /// Build a Write-only Pipe type. | |||
2081 | /// | |||
2082 | /// \param T The type to which we'll be building a Pipe. | |||
2083 | /// | |||
2084 | /// \param Loc We do not use it for now. | |||
2085 | /// | |||
2086 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | |||
2087 | /// NULL type. | |||
2088 | QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { | |||
2089 | return Context.getWritePipeType(T); | |||
2090 | } | |||
2091 | ||||
2092 | /// Check whether the specified array size makes the array type a VLA. If so, | |||
2093 | /// return true, if not, return the size of the array in SizeVal. | |||
2094 | static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { | |||
2095 | // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode | |||
2096 | // (like gnu99, but not c99) accept any evaluatable value as an extension. | |||
2097 | class VLADiagnoser : public Sema::VerifyICEDiagnoser { | |||
2098 | public: | |||
2099 | VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} | |||
2100 | ||||
2101 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { | |||
2102 | } | |||
2103 | ||||
2104 | void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override { | |||
2105 | S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; | |||
2106 | } | |||
2107 | } Diagnoser; | |||
2108 | ||||
2109 | return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, | |||
2110 | S.LangOpts.GNUMode || | |||
2111 | S.LangOpts.OpenCL).isInvalid(); | |||
2112 | } | |||
2113 | ||||
2114 | /// Build an array type. | |||
2115 | /// | |||
2116 | /// \param T The type of each element in the array. | |||
2117 | /// | |||
2118 | /// \param ASM C99 array size modifier (e.g., '*', 'static'). | |||
2119 | /// | |||
2120 | /// \param ArraySize Expression describing the size of the array. | |||
2121 | /// | |||
2122 | /// \param Brackets The range from the opening '[' to the closing ']'. | |||
2123 | /// | |||
2124 | /// \param Entity The name of the entity that involves the array | |||
2125 | /// type, if known. | |||
2126 | /// | |||
2127 | /// \returns A suitable array type, if there are no errors. Otherwise, | |||
2128 | /// returns a NULL type. | |||
2129 | QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, | |||
2130 | Expr *ArraySize, unsigned Quals, | |||
2131 | SourceRange Brackets, DeclarationName Entity) { | |||
2132 | ||||
2133 | SourceLocation Loc = Brackets.getBegin(); | |||
2134 | if (getLangOpts().CPlusPlus) { | |||
2135 | // C++ [dcl.array]p1: | |||
2136 | // T is called the array element type; this type shall not be a reference | |||
2137 | // type, the (possibly cv-qualified) type void, a function type or an | |||
2138 | // abstract class type. | |||
2139 | // | |||
2140 | // C++ [dcl.array]p3: | |||
2141 | // When several "array of" specifications are adjacent, [...] only the | |||
2142 | // first of the constant expressions that specify the bounds of the arrays | |||
2143 | // may be omitted. | |||
2144 | // | |||
2145 | // Note: function types are handled in the common path with C. | |||
2146 | if (T->isReferenceType()) { | |||
2147 | Diag(Loc, diag::err_illegal_decl_array_of_references) | |||
2148 | << getPrintableNameForEntity(Entity) << T; | |||
2149 | return QualType(); | |||
2150 | } | |||
2151 | ||||
2152 | if (T->isVoidType() || T->isIncompleteArrayType()) { | |||
2153 | Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; | |||
2154 | return QualType(); | |||
2155 | } | |||
2156 | ||||
2157 | if (RequireNonAbstractType(Brackets.getBegin(), T, | |||
2158 | diag::err_array_of_abstract_type)) | |||
2159 | return QualType(); | |||
2160 | ||||
2161 | // Mentioning a member pointer type for an array type causes us to lock in | |||
2162 | // an inheritance model, even if it's inside an unused typedef. | |||
2163 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
2164 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) | |||
2165 | if (!MPTy->getClass()->isDependentType()) | |||
2166 | (void)isCompleteType(Loc, T); | |||
2167 | ||||
2168 | } else { | |||
2169 | // C99 6.7.5.2p1: If the element type is an incomplete or function type, | |||
2170 | // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) | |||
2171 | if (RequireCompleteType(Loc, T, | |||
2172 | diag::err_illegal_decl_array_incomplete_type)) | |||
2173 | return QualType(); | |||
2174 | } | |||
2175 | ||||
2176 | if (T->isFunctionType()) { | |||
2177 | Diag(Loc, diag::err_illegal_decl_array_of_functions) | |||
2178 | << getPrintableNameForEntity(Entity) << T; | |||
2179 | return QualType(); | |||
2180 | } | |||
2181 | ||||
2182 | if (const RecordType *EltTy = T->getAs<RecordType>()) { | |||
2183 | // If the element type is a struct or union that contains a variadic | |||
2184 | // array, accept it as a GNU extension: C99 6.7.2.1p2. | |||
2185 | if (EltTy->getDecl()->hasFlexibleArrayMember()) | |||
2186 | Diag(Loc, diag::ext_flexible_array_in_array) << T; | |||
2187 | } else if (T->isObjCObjectType()) { | |||
2188 | Diag(Loc, diag::err_objc_array_of_interfaces) << T; | |||
2189 | return QualType(); | |||
2190 | } | |||
2191 | ||||
2192 | // Do placeholder conversions on the array size expression. | |||
2193 | if (ArraySize && ArraySize->hasPlaceholderType()) { | |||
2194 | ExprResult Result = CheckPlaceholderExpr(ArraySize); | |||
2195 | if (Result.isInvalid()) return QualType(); | |||
2196 | ArraySize = Result.get(); | |||
2197 | } | |||
2198 | ||||
2199 | // Do lvalue-to-rvalue conversions on the array size expression. | |||
2200 | if (ArraySize && !ArraySize->isRValue()) { | |||
2201 | ExprResult Result = DefaultLvalueConversion(ArraySize); | |||
2202 | if (Result.isInvalid()) | |||
2203 | return QualType(); | |||
2204 | ||||
2205 | ArraySize = Result.get(); | |||
2206 | } | |||
2207 | ||||
2208 | // C99 6.7.5.2p1: The size expression shall have integer type. | |||
2209 | // C++11 allows contextual conversions to such types. | |||
2210 | if (!getLangOpts().CPlusPlus11 && | |||
2211 | ArraySize && !ArraySize->isTypeDependent() && | |||
2212 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
2213 | Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) | |||
2214 | << ArraySize->getType() << ArraySize->getSourceRange(); | |||
2215 | return QualType(); | |||
2216 | } | |||
2217 | ||||
2218 | llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); | |||
2219 | if (!ArraySize) { | |||
2220 | if (ASM == ArrayType::Star) | |||
2221 | T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); | |||
2222 | else | |||
2223 | T = Context.getIncompleteArrayType(T, ASM, Quals); | |||
2224 | } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { | |||
2225 | T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2226 | } else if ((!T->isDependentType() && !T->isIncompleteType() && | |||
2227 | !T->isConstantSizeType()) || | |||
2228 | isArraySizeVLA(*this, ArraySize, ConstVal)) { | |||
2229 | // Even in C++11, don't allow contextual conversions in the array bound | |||
2230 | // of a VLA. | |||
2231 | if (getLangOpts().CPlusPlus11 && | |||
2232 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
2233 | Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) | |||
2234 | << ArraySize->getType() << ArraySize->getSourceRange(); | |||
2235 | return QualType(); | |||
2236 | } | |||
2237 | ||||
2238 | // C99: an array with an element type that has a non-constant-size is a VLA. | |||
2239 | // C99: an array with a non-ICE size is a VLA. We accept any expression | |||
2240 | // that we can fold to a non-zero positive value as an extension. | |||
2241 | T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2242 | } else { | |||
2243 | // C99 6.7.5.2p1: If the expression is a constant expression, it shall | |||
2244 | // have a value greater than zero. | |||
2245 | if (ConstVal.isSigned() && ConstVal.isNegative()) { | |||
2246 | if (Entity) | |||
2247 | Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size) | |||
2248 | << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); | |||
2249 | else | |||
2250 | Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size) | |||
2251 | << ArraySize->getSourceRange(); | |||
2252 | return QualType(); | |||
2253 | } | |||
2254 | if (ConstVal == 0) { | |||
2255 | // GCC accepts zero sized static arrays. We allow them when | |||
2256 | // we're not in a SFINAE context. | |||
2257 | Diag(ArraySize->getBeginLoc(), isSFINAEContext() | |||
2258 | ? diag::err_typecheck_zero_array_size | |||
2259 | : diag::ext_typecheck_zero_array_size) | |||
2260 | << ArraySize->getSourceRange(); | |||
2261 | ||||
2262 | if (ASM == ArrayType::Static) { | |||
2263 | Diag(ArraySize->getBeginLoc(), | |||
2264 | diag::warn_typecheck_zero_static_array_size) | |||
2265 | << ArraySize->getSourceRange(); | |||
2266 | ASM = ArrayType::Normal; | |||
2267 | } | |||
2268 | } else if (!T->isDependentType() && !T->isVariablyModifiedType() && | |||
2269 | !T->isIncompleteType() && !T->isUndeducedType()) { | |||
2270 | // Is the array too large? | |||
2271 | unsigned ActiveSizeBits | |||
2272 | = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); | |||
2273 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | |||
2274 | Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) | |||
2275 | << ConstVal.toString(10) << ArraySize->getSourceRange(); | |||
2276 | return QualType(); | |||
2277 | } | |||
2278 | } | |||
2279 | ||||
2280 | T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); | |||
2281 | } | |||
2282 | ||||
2283 | // OpenCL v1.2 s6.9.d: variable length arrays are not supported. | |||
2284 | if (getLangOpts().OpenCL && T->isVariableArrayType()) { | |||
2285 | Diag(Loc, diag::err_opencl_vla); | |||
2286 | return QualType(); | |||
2287 | } | |||
2288 | ||||
2289 | if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) { | |||
2290 | // CUDA device code and some other targets don't support VLAs. | |||
2291 | targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) | |||
2292 | ? diag::err_cuda_vla | |||
2293 | : diag::err_vla_unsupported) | |||
2294 | << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice) | |||
2295 | ? CurrentCUDATarget() | |||
2296 | : CFT_InvalidTarget); | |||
2297 | } | |||
2298 | ||||
2299 | // If this is not C99, extwarn about VLA's and C99 array size modifiers. | |||
2300 | if (!getLangOpts().C99) { | |||
2301 | if (T->isVariableArrayType()) { | |||
2302 | // Prohibit the use of VLAs during template argument deduction. | |||
2303 | if (isSFINAEContext()) { | |||
2304 | Diag(Loc, diag::err_vla_in_sfinae); | |||
2305 | return QualType(); | |||
2306 | } | |||
2307 | // Just extwarn about VLAs. | |||
2308 | else | |||
2309 | Diag(Loc, diag::ext_vla); | |||
2310 | } else if (ASM != ArrayType::Normal || Quals != 0) | |||
2311 | Diag(Loc, | |||
2312 | getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx | |||
2313 | : diag::ext_c99_array_usage) << ASM; | |||
2314 | } | |||
2315 | ||||
2316 | if (T->isVariableArrayType()) { | |||
2317 | // Warn about VLAs for -Wvla. | |||
2318 | Diag(Loc, diag::warn_vla_used); | |||
2319 | } | |||
2320 | ||||
2321 | // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. | |||
2322 | // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. | |||
2323 | // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. | |||
2324 | if (getLangOpts().OpenCL) { | |||
2325 | const QualType ArrType = Context.getBaseElementType(T); | |||
2326 | if (ArrType->isBlockPointerType() || ArrType->isPipeType() || | |||
2327 | ArrType->isSamplerT() || ArrType->isImageType()) { | |||
2328 | Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; | |||
2329 | return QualType(); | |||
2330 | } | |||
2331 | } | |||
2332 | ||||
2333 | return T; | |||
2334 | } | |||
2335 | ||||
2336 | QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, | |||
2337 | SourceLocation AttrLoc) { | |||
2338 | // The base type must be integer (not Boolean or enumeration) or float, and | |||
2339 | // can't already be a vector. | |||
2340 | if (!CurType->isDependentType() && | |||
2341 | (!CurType->isBuiltinType() || CurType->isBooleanType() || | |||
2342 | (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) { | |||
2343 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType; | |||
2344 | return QualType(); | |||
2345 | } | |||
2346 | ||||
2347 | if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent()) | |||
2348 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, | |||
2349 | VectorType::GenericVector); | |||
2350 | ||||
2351 | llvm::APSInt VecSize(32); | |||
2352 | if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) { | |||
2353 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2354 | << "vector_size" << AANT_ArgumentIntegerConstant | |||
2355 | << SizeExpr->getSourceRange(); | |||
2356 | return QualType(); | |||
2357 | } | |||
2358 | ||||
2359 | if (CurType->isDependentType()) | |||
2360 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, | |||
2361 | VectorType::GenericVector); | |||
2362 | ||||
2363 | unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8); | |||
2364 | unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType)); | |||
2365 | ||||
2366 | if (VectorSize == 0) { | |||
2367 | Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange(); | |||
2368 | return QualType(); | |||
2369 | } | |||
2370 | ||||
2371 | // vecSize is specified in bytes - convert to bits. | |||
2372 | if (VectorSize % TypeSize) { | |||
2373 | Diag(AttrLoc, diag::err_attribute_invalid_size) | |||
2374 | << SizeExpr->getSourceRange(); | |||
2375 | return QualType(); | |||
2376 | } | |||
2377 | ||||
2378 | if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) { | |||
2379 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2380 | << SizeExpr->getSourceRange(); | |||
2381 | return QualType(); | |||
2382 | } | |||
2383 | ||||
2384 | return Context.getVectorType(CurType, VectorSize / TypeSize, | |||
2385 | VectorType::GenericVector); | |||
2386 | } | |||
2387 | ||||
2388 | /// Build an ext-vector type. | |||
2389 | /// | |||
2390 | /// Run the required checks for the extended vector type. | |||
2391 | QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, | |||
2392 | SourceLocation AttrLoc) { | |||
2393 | // Unlike gcc's vector_size attribute, we do not allow vectors to be defined | |||
2394 | // in conjunction with complex types (pointers, arrays, functions, etc.). | |||
2395 | // | |||
2396 | // Additionally, OpenCL prohibits vectors of booleans (they're considered a | |||
2397 | // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects | |||
2398 | // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors | |||
2399 | // of bool aren't allowed. | |||
2400 | if ((!T->isDependentType() && !T->isIntegerType() && | |||
2401 | !T->isRealFloatingType()) || | |||
2402 | T->isBooleanType()) { | |||
2403 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; | |||
2404 | return QualType(); | |||
2405 | } | |||
2406 | ||||
2407 | if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { | |||
2408 | llvm::APSInt vecSize(32); | |||
2409 | if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { | |||
2410 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2411 | << "ext_vector_type" << AANT_ArgumentIntegerConstant | |||
2412 | << ArraySize->getSourceRange(); | |||
2413 | return QualType(); | |||
2414 | } | |||
2415 | ||||
2416 | // Unlike gcc's vector_size attribute, the size is specified as the | |||
2417 | // number of elements, not the number of bytes. | |||
2418 | unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); | |||
2419 | ||||
2420 | if (vectorSize == 0) { | |||
2421 | Diag(AttrLoc, diag::err_attribute_zero_size) | |||
2422 | << ArraySize->getSourceRange(); | |||
2423 | return QualType(); | |||
2424 | } | |||
2425 | ||||
2426 | if (VectorType::isVectorSizeTooLarge(vectorSize)) { | |||
2427 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2428 | << ArraySize->getSourceRange(); | |||
2429 | return QualType(); | |||
2430 | } | |||
2431 | ||||
2432 | return Context.getExtVectorType(T, vectorSize); | |||
2433 | } | |||
2434 | ||||
2435 | return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); | |||
2436 | } | |||
2437 | ||||
2438 | bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { | |||
2439 | if (T->isArrayType() || T->isFunctionType()) { | |||
2440 | Diag(Loc, diag::err_func_returning_array_function) | |||
2441 | << T->isFunctionType() << T; | |||
2442 | return true; | |||
2443 | } | |||
2444 | ||||
2445 | // Functions cannot return half FP. | |||
2446 | if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { | |||
2447 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << | |||
2448 | FixItHint::CreateInsertion(Loc, "*"); | |||
2449 | return true; | |||
2450 | } | |||
2451 | ||||
2452 | // Methods cannot return interface types. All ObjC objects are | |||
2453 | // passed by reference. | |||
2454 | if (T->isObjCObjectType()) { | |||
2455 | Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) | |||
2456 | << 0 << T << FixItHint::CreateInsertion(Loc, "*"); | |||
2457 | return true; | |||
2458 | } | |||
2459 | ||||
2460 | return false; | |||
2461 | } | |||
2462 | ||||
2463 | /// Check the extended parameter information. Most of the necessary | |||
2464 | /// checking should occur when applying the parameter attribute; the | |||
2465 | /// only other checks required are positional restrictions. | |||
2466 | static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, | |||
2467 | const FunctionProtoType::ExtProtoInfo &EPI, | |||
2468 | llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { | |||
2469 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 2469, __PRETTY_FUNCTION__)); | |||
2470 | ||||
2471 | bool hasCheckedSwiftCall = false; | |||
2472 | auto checkForSwiftCC = [&](unsigned paramIndex) { | |||
2473 | // Only do this once. | |||
2474 | if (hasCheckedSwiftCall) return; | |||
2475 | hasCheckedSwiftCall = true; | |||
2476 | if (EPI.ExtInfo.getCC() == CC_Swift) return; | |||
2477 | S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) | |||
2478 | << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()); | |||
2479 | }; | |||
2480 | ||||
2481 | for (size_t paramIndex = 0, numParams = paramTypes.size(); | |||
2482 | paramIndex != numParams; ++paramIndex) { | |||
2483 | switch (EPI.ExtParameterInfos[paramIndex].getABI()) { | |||
2484 | // Nothing interesting to check for orindary-ABI parameters. | |||
2485 | case ParameterABI::Ordinary: | |||
2486 | continue; | |||
2487 | ||||
2488 | // swift_indirect_result parameters must be a prefix of the function | |||
2489 | // arguments. | |||
2490 | case ParameterABI::SwiftIndirectResult: | |||
2491 | checkForSwiftCC(paramIndex); | |||
2492 | if (paramIndex != 0 && | |||
2493 | EPI.ExtParameterInfos[paramIndex - 1].getABI() | |||
2494 | != ParameterABI::SwiftIndirectResult) { | |||
2495 | S.Diag(getParamLoc(paramIndex), | |||
2496 | diag::err_swift_indirect_result_not_first); | |||
2497 | } | |||
2498 | continue; | |||
2499 | ||||
2500 | case ParameterABI::SwiftContext: | |||
2501 | checkForSwiftCC(paramIndex); | |||
2502 | continue; | |||
2503 | ||||
2504 | // swift_error parameters must be preceded by a swift_context parameter. | |||
2505 | case ParameterABI::SwiftErrorResult: | |||
2506 | checkForSwiftCC(paramIndex); | |||
2507 | if (paramIndex == 0 || | |||
2508 | EPI.ExtParameterInfos[paramIndex - 1].getABI() != | |||
2509 | ParameterABI::SwiftContext) { | |||
2510 | S.Diag(getParamLoc(paramIndex), | |||
2511 | diag::err_swift_error_result_not_after_swift_context); | |||
2512 | } | |||
2513 | continue; | |||
2514 | } | |||
2515 | llvm_unreachable("bad ABI kind")::llvm::llvm_unreachable_internal("bad ABI kind", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 2515); | |||
2516 | } | |||
2517 | } | |||
2518 | ||||
2519 | QualType Sema::BuildFunctionType(QualType T, | |||
2520 | MutableArrayRef<QualType> ParamTypes, | |||
2521 | SourceLocation Loc, DeclarationName Entity, | |||
2522 | const FunctionProtoType::ExtProtoInfo &EPI) { | |||
2523 | bool Invalid = false; | |||
2524 | ||||
2525 | Invalid |= CheckFunctionReturnType(T, Loc); | |||
2526 | ||||
2527 | for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { | |||
2528 | // FIXME: Loc is too inprecise here, should use proper locations for args. | |||
2529 | QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); | |||
2530 | if (ParamType->isVoidType()) { | |||
2531 | Diag(Loc, diag::err_param_with_void_type); | |||
2532 | Invalid = true; | |||
2533 | } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { | |||
2534 | // Disallow half FP arguments. | |||
2535 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << | |||
2536 | FixItHint::CreateInsertion(Loc, "*"); | |||
2537 | Invalid = true; | |||
2538 | } | |||
2539 | ||||
2540 | ParamTypes[Idx] = ParamType; | |||
2541 | } | |||
2542 | ||||
2543 | if (EPI.ExtParameterInfos) { | |||
2544 | checkExtParameterInfos(*this, ParamTypes, EPI, | |||
2545 | [=](unsigned i) { return Loc; }); | |||
2546 | } | |||
2547 | ||||
2548 | if (EPI.ExtInfo.getProducesResult()) { | |||
2549 | // This is just a warning, so we can't fail to build if we see it. | |||
2550 | checkNSReturnsRetainedReturnType(Loc, T); | |||
2551 | } | |||
2552 | ||||
2553 | if (Invalid) | |||
2554 | return QualType(); | |||
2555 | ||||
2556 | return Context.getFunctionType(T, ParamTypes, EPI); | |||
2557 | } | |||
2558 | ||||
2559 | /// Build a member pointer type \c T Class::*. | |||
2560 | /// | |||
2561 | /// \param T the type to which the member pointer refers. | |||
2562 | /// \param Class the class type into which the member pointer points. | |||
2563 | /// \param Loc the location where this type begins | |||
2564 | /// \param Entity the name of the entity that will have this member pointer type | |||
2565 | /// | |||
2566 | /// \returns a member pointer type, if successful, or a NULL type if there was | |||
2567 | /// an error. | |||
2568 | QualType Sema::BuildMemberPointerType(QualType T, QualType Class, | |||
2569 | SourceLocation Loc, | |||
2570 | DeclarationName Entity) { | |||
2571 | // Verify that we're not building a pointer to pointer to function with | |||
2572 | // exception specification. | |||
2573 | if (CheckDistantExceptionSpec(T)) { | |||
2574 | Diag(Loc, diag::err_distant_exception_spec); | |||
2575 | return QualType(); | |||
2576 | } | |||
2577 | ||||
2578 | // C++ 8.3.3p3: A pointer to member shall not point to ... a member | |||
2579 | // with reference type, or "cv void." | |||
2580 | if (T->isReferenceType()) { | |||
2581 | Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) | |||
2582 | << getPrintableNameForEntity(Entity) << T; | |||
2583 | return QualType(); | |||
2584 | } | |||
2585 | ||||
2586 | if (T->isVoidType()) { | |||
2587 | Diag(Loc, diag::err_illegal_decl_mempointer_to_void) | |||
2588 | << getPrintableNameForEntity(Entity); | |||
2589 | return QualType(); | |||
2590 | } | |||
2591 | ||||
2592 | if (!Class->isDependentType() && !Class->isRecordType()) { | |||
2593 | Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; | |||
2594 | return QualType(); | |||
2595 | } | |||
2596 | ||||
2597 | // Adjust the default free function calling convention to the default method | |||
2598 | // calling convention. | |||
2599 | bool IsCtorOrDtor = | |||
2600 | (Entity.getNameKind() == DeclarationName::CXXConstructorName) || | |||
2601 | (Entity.getNameKind() == DeclarationName::CXXDestructorName); | |||
2602 | if (T->isFunctionType()) | |||
2603 | adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); | |||
2604 | ||||
2605 | return Context.getMemberPointerType(T, Class.getTypePtr()); | |||
2606 | } | |||
2607 | ||||
2608 | /// Build a block pointer type. | |||
2609 | /// | |||
2610 | /// \param T The type to which we'll be building a block pointer. | |||
2611 | /// | |||
2612 | /// \param Loc The source location, used for diagnostics. | |||
2613 | /// | |||
2614 | /// \param Entity The name of the entity that involves the block pointer | |||
2615 | /// type, if known. | |||
2616 | /// | |||
2617 | /// \returns A suitable block pointer type, if there are no | |||
2618 | /// errors. Otherwise, returns a NULL type. | |||
2619 | QualType Sema::BuildBlockPointerType(QualType T, | |||
2620 | SourceLocation Loc, | |||
2621 | DeclarationName Entity) { | |||
2622 | if (!T->isFunctionType()) { | |||
2623 | Diag(Loc, diag::err_nonfunction_block_type); | |||
2624 | return QualType(); | |||
2625 | } | |||
2626 | ||||
2627 | if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) | |||
2628 | return QualType(); | |||
2629 | ||||
2630 | return Context.getBlockPointerType(T); | |||
2631 | } | |||
2632 | ||||
2633 | QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { | |||
2634 | QualType QT = Ty.get(); | |||
2635 | if (QT.isNull()) { | |||
2636 | if (TInfo) *TInfo = nullptr; | |||
2637 | return QualType(); | |||
2638 | } | |||
2639 | ||||
2640 | TypeSourceInfo *DI = nullptr; | |||
2641 | if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { | |||
2642 | QT = LIT->getType(); | |||
2643 | DI = LIT->getTypeSourceInfo(); | |||
2644 | } | |||
2645 | ||||
2646 | if (TInfo) *TInfo = DI; | |||
2647 | return QT; | |||
2648 | } | |||
2649 | ||||
2650 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | |||
2651 | Qualifiers::ObjCLifetime ownership, | |||
2652 | unsigned chunkIndex); | |||
2653 | ||||
2654 | /// Given that this is the declaration of a parameter under ARC, | |||
2655 | /// attempt to infer attributes and such for pointer-to-whatever | |||
2656 | /// types. | |||
2657 | static void inferARCWriteback(TypeProcessingState &state, | |||
2658 | QualType &declSpecType) { | |||
2659 | Sema &S = state.getSema(); | |||
2660 | Declarator &declarator = state.getDeclarator(); | |||
2661 | ||||
2662 | // TODO: should we care about decl qualifiers? | |||
2663 | ||||
2664 | // Check whether the declarator has the expected form. We walk | |||
2665 | // from the inside out in order to make the block logic work. | |||
2666 | unsigned outermostPointerIndex = 0; | |||
2667 | bool isBlockPointer = false; | |||
2668 | unsigned numPointers = 0; | |||
2669 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
2670 | unsigned chunkIndex = i; | |||
2671 | DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); | |||
2672 | switch (chunk.Kind) { | |||
2673 | case DeclaratorChunk::Paren: | |||
2674 | // Ignore parens. | |||
2675 | break; | |||
2676 | ||||
2677 | case DeclaratorChunk::Reference: | |||
2678 | case DeclaratorChunk::Pointer: | |||
2679 | // Count the number of pointers. Treat references | |||
2680 | // interchangeably as pointers; if they're mis-ordered, normal | |||
2681 | // type building will discover that. | |||
2682 | outermostPointerIndex = chunkIndex; | |||
2683 | numPointers++; | |||
2684 | break; | |||
2685 | ||||
2686 | case DeclaratorChunk::BlockPointer: | |||
2687 | // If we have a pointer to block pointer, that's an acceptable | |||
2688 | // indirect reference; anything else is not an application of | |||
2689 | // the rules. | |||
2690 | if (numPointers != 1) return; | |||
2691 | numPointers++; | |||
2692 | outermostPointerIndex = chunkIndex; | |||
2693 | isBlockPointer = true; | |||
2694 | ||||
2695 | // We don't care about pointer structure in return values here. | |||
2696 | goto done; | |||
2697 | ||||
2698 | case DeclaratorChunk::Array: // suppress if written (id[])? | |||
2699 | case DeclaratorChunk::Function: | |||
2700 | case DeclaratorChunk::MemberPointer: | |||
2701 | case DeclaratorChunk::Pipe: | |||
2702 | return; | |||
2703 | } | |||
2704 | } | |||
2705 | done: | |||
2706 | ||||
2707 | // If we have *one* pointer, then we want to throw the qualifier on | |||
2708 | // the declaration-specifiers, which means that it needs to be a | |||
2709 | // retainable object type. | |||
2710 | if (numPointers == 1) { | |||
2711 | // If it's not a retainable object type, the rule doesn't apply. | |||
2712 | if (!declSpecType->isObjCRetainableType()) return; | |||
2713 | ||||
2714 | // If it already has lifetime, don't do anything. | |||
2715 | if (declSpecType.getObjCLifetime()) return; | |||
2716 | ||||
2717 | // Otherwise, modify the type in-place. | |||
2718 | Qualifiers qs; | |||
2719 | ||||
2720 | if (declSpecType->isObjCARCImplicitlyUnretainedType()) | |||
2721 | qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); | |||
2722 | else | |||
2723 | qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); | |||
2724 | declSpecType = S.Context.getQualifiedType(declSpecType, qs); | |||
2725 | ||||
2726 | // If we have *two* pointers, then we want to throw the qualifier on | |||
2727 | // the outermost pointer. | |||
2728 | } else if (numPointers == 2) { | |||
2729 | // If we don't have a block pointer, we need to check whether the | |||
2730 | // declaration-specifiers gave us something that will turn into a | |||
2731 | // retainable object pointer after we slap the first pointer on it. | |||
2732 | if (!isBlockPointer && !declSpecType->isObjCObjectType()) | |||
2733 | return; | |||
2734 | ||||
2735 | // Look for an explicit lifetime attribute there. | |||
2736 | DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); | |||
2737 | if (chunk.Kind != DeclaratorChunk::Pointer && | |||
2738 | chunk.Kind != DeclaratorChunk::BlockPointer) | |||
2739 | return; | |||
2740 | for (const ParsedAttr &AL : chunk.getAttrs()) | |||
2741 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) | |||
2742 | return; | |||
2743 | ||||
2744 | transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, | |||
2745 | outermostPointerIndex); | |||
2746 | ||||
2747 | // Any other number of pointers/references does not trigger the rule. | |||
2748 | } else return; | |||
2749 | ||||
2750 | // TODO: mark whether we did this inference? | |||
2751 | } | |||
2752 | ||||
2753 | void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, | |||
2754 | SourceLocation FallbackLoc, | |||
2755 | SourceLocation ConstQualLoc, | |||
2756 | SourceLocation VolatileQualLoc, | |||
2757 | SourceLocation RestrictQualLoc, | |||
2758 | SourceLocation AtomicQualLoc, | |||
2759 | SourceLocation UnalignedQualLoc) { | |||
2760 | if (!Quals) | |||
2761 | return; | |||
2762 | ||||
2763 | struct Qual { | |||
2764 | const char *Name; | |||
2765 | unsigned Mask; | |||
2766 | SourceLocation Loc; | |||
2767 | } const QualKinds[5] = { | |||
2768 | { "const", DeclSpec::TQ_const, ConstQualLoc }, | |||
2769 | { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, | |||
2770 | { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, | |||
2771 | { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc }, | |||
2772 | { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } | |||
2773 | }; | |||
2774 | ||||
2775 | SmallString<32> QualStr; | |||
2776 | unsigned NumQuals = 0; | |||
2777 | SourceLocation Loc; | |||
2778 | FixItHint FixIts[5]; | |||
2779 | ||||
2780 | // Build a string naming the redundant qualifiers. | |||
2781 | for (auto &E : QualKinds) { | |||
2782 | if (Quals & E.Mask) { | |||
2783 | if (!QualStr.empty()) QualStr += ' '; | |||
2784 | QualStr += E.Name; | |||
2785 | ||||
2786 | // If we have a location for the qualifier, offer a fixit. | |||
2787 | SourceLocation QualLoc = E.Loc; | |||
2788 | if (QualLoc.isValid()) { | |||
2789 | FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); | |||
2790 | if (Loc.isInvalid() || | |||
2791 | getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) | |||
2792 | Loc = QualLoc; | |||
2793 | } | |||
2794 | ||||
2795 | ++NumQuals; | |||
2796 | } | |||
2797 | } | |||
2798 | ||||
2799 | Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) | |||
2800 | << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; | |||
2801 | } | |||
2802 | ||||
2803 | // Diagnose pointless type qualifiers on the return type of a function. | |||
2804 | static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, | |||
2805 | Declarator &D, | |||
2806 | unsigned FunctionChunkIndex) { | |||
2807 | if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { | |||
2808 | // FIXME: TypeSourceInfo doesn't preserve location information for | |||
2809 | // qualifiers. | |||
2810 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
2811 | RetTy.getLocalCVRQualifiers(), | |||
2812 | D.getIdentifierLoc()); | |||
2813 | return; | |||
2814 | } | |||
2815 | ||||
2816 | for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, | |||
2817 | End = D.getNumTypeObjects(); | |||
2818 | OuterChunkIndex != End; ++OuterChunkIndex) { | |||
2819 | DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); | |||
2820 | switch (OuterChunk.Kind) { | |||
2821 | case DeclaratorChunk::Paren: | |||
2822 | continue; | |||
2823 | ||||
2824 | case DeclaratorChunk::Pointer: { | |||
2825 | DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; | |||
2826 | S.diagnoseIgnoredQualifiers( | |||
2827 | diag::warn_qual_return_type, | |||
2828 | PTI.TypeQuals, | |||
2829 | SourceLocation(), | |||
2830 | SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), | |||
2831 | SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), | |||
2832 | SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), | |||
2833 | SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc), | |||
2834 | SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc)); | |||
2835 | return; | |||
2836 | } | |||
2837 | ||||
2838 | case DeclaratorChunk::Function: | |||
2839 | case DeclaratorChunk::BlockPointer: | |||
2840 | case DeclaratorChunk::Reference: | |||
2841 | case DeclaratorChunk::Array: | |||
2842 | case DeclaratorChunk::MemberPointer: | |||
2843 | case DeclaratorChunk::Pipe: | |||
2844 | // FIXME: We can't currently provide an accurate source location and a | |||
2845 | // fix-it hint for these. | |||
2846 | unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; | |||
2847 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
2848 | RetTy.getCVRQualifiers() | AtomicQual, | |||
2849 | D.getIdentifierLoc()); | |||
2850 | return; | |||
2851 | } | |||
2852 | ||||
2853 | llvm_unreachable("unknown declarator chunk kind")::llvm::llvm_unreachable_internal("unknown declarator chunk kind" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 2853); | |||
2854 | } | |||
2855 | ||||
2856 | // If the qualifiers come from a conversion function type, don't diagnose | |||
2857 | // them -- they're not necessarily redundant, since such a conversion | |||
2858 | // operator can be explicitly called as "x.operator const int()". | |||
2859 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | |||
2860 | return; | |||
2861 | ||||
2862 | // Just parens all the way out to the decl specifiers. Diagnose any qualifiers | |||
2863 | // which are present there. | |||
2864 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
2865 | D.getDeclSpec().getTypeQualifiers(), | |||
2866 | D.getIdentifierLoc(), | |||
2867 | D.getDeclSpec().getConstSpecLoc(), | |||
2868 | D.getDeclSpec().getVolatileSpecLoc(), | |||
2869 | D.getDeclSpec().getRestrictSpecLoc(), | |||
2870 | D.getDeclSpec().getAtomicSpecLoc(), | |||
2871 | D.getDeclSpec().getUnalignedSpecLoc()); | |||
2872 | } | |||
2873 | ||||
2874 | static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, | |||
2875 | TypeSourceInfo *&ReturnTypeInfo) { | |||
2876 | Sema &SemaRef = state.getSema(); | |||
2877 | Declarator &D = state.getDeclarator(); | |||
2878 | QualType T; | |||
2879 | ReturnTypeInfo = nullptr; | |||
2880 | ||||
2881 | // The TagDecl owned by the DeclSpec. | |||
2882 | TagDecl *OwnedTagDecl = nullptr; | |||
2883 | ||||
2884 | switch (D.getName().getKind()) { | |||
2885 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
2886 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
2887 | case UnqualifiedIdKind::IK_Identifier: | |||
2888 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
2889 | case UnqualifiedIdKind::IK_TemplateId: | |||
2890 | T = ConvertDeclSpecToType(state); | |||
2891 | ||||
2892 | if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { | |||
2893 | OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
2894 | // Owned declaration is embedded in declarator. | |||
2895 | OwnedTagDecl->setEmbeddedInDeclarator(true); | |||
2896 | } | |||
2897 | break; | |||
2898 | ||||
2899 | case UnqualifiedIdKind::IK_ConstructorName: | |||
2900 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
2901 | case UnqualifiedIdKind::IK_DestructorName: | |||
2902 | // Constructors and destructors don't have return types. Use | |||
2903 | // "void" instead. | |||
2904 | T = SemaRef.Context.VoidTy; | |||
2905 | processTypeAttrs(state, T, TAL_DeclSpec, | |||
2906 | D.getMutableDeclSpec().getAttributes()); | |||
2907 | break; | |||
2908 | ||||
2909 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
2910 | // Deduction guides have a trailing return type and no type in their | |||
2911 | // decl-specifier sequence. Use a placeholder return type for now. | |||
2912 | T = SemaRef.Context.DependentTy; | |||
2913 | break; | |||
2914 | ||||
2915 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
2916 | // The result type of a conversion function is the type that it | |||
2917 | // converts to. | |||
2918 | T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, | |||
2919 | &ReturnTypeInfo); | |||
2920 | break; | |||
2921 | } | |||
2922 | ||||
2923 | if (!D.getAttributes().empty()) | |||
2924 | distributeTypeAttrsFromDeclarator(state, T); | |||
2925 | ||||
2926 | // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. | |||
2927 | if (DeducedType *Deduced = T->getContainedDeducedType()) { | |||
2928 | AutoType *Auto = dyn_cast<AutoType>(Deduced); | |||
2929 | int Error = -1; | |||
2930 | ||||
2931 | // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or | |||
2932 | // class template argument deduction)? | |||
2933 | bool IsCXXAutoType = | |||
2934 | (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); | |||
2935 | bool IsDeducedReturnType = false; | |||
2936 | ||||
2937 | switch (D.getContext()) { | |||
2938 | case DeclaratorContext::LambdaExprContext: | |||
2939 | // Declared return type of a lambda-declarator is implicit and is always | |||
2940 | // 'auto'. | |||
2941 | break; | |||
2942 | case DeclaratorContext::ObjCParameterContext: | |||
2943 | case DeclaratorContext::ObjCResultContext: | |||
2944 | case DeclaratorContext::PrototypeContext: | |||
2945 | Error = 0; | |||
2946 | break; | |||
2947 | case DeclaratorContext::LambdaExprParameterContext: | |||
2948 | // In C++14, generic lambdas allow 'auto' in their parameters. | |||
2949 | if (!SemaRef.getLangOpts().CPlusPlus14 || | |||
2950 | !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) | |||
2951 | Error = 16; | |||
2952 | else { | |||
2953 | // If auto is mentioned in a lambda parameter context, convert it to a | |||
2954 | // template parameter type. | |||
2955 | sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda(); | |||
2956 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 2956, __PRETTY_FUNCTION__)); | |||
2957 | const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth; | |||
2958 | const unsigned AutoParameterPosition = LSI->TemplateParams.size(); | |||
2959 | const bool IsParameterPack = D.hasEllipsis(); | |||
2960 | ||||
2961 | // Create the TemplateTypeParmDecl here to retrieve the corresponding | |||
2962 | // template parameter type. Template parameters are temporarily added | |||
2963 | // to the TU until the associated TemplateDecl is created. | |||
2964 | TemplateTypeParmDecl *CorrespondingTemplateParam = | |||
2965 | TemplateTypeParmDecl::Create( | |||
2966 | SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(), | |||
2967 | /*KeyLoc*/ SourceLocation(), /*NameLoc*/ D.getBeginLoc(), | |||
2968 | TemplateParameterDepth, AutoParameterPosition, | |||
2969 | /*Identifier*/ nullptr, false, IsParameterPack); | |||
2970 | CorrespondingTemplateParam->setImplicit(); | |||
2971 | LSI->TemplateParams.push_back(CorrespondingTemplateParam); | |||
2972 | // Replace the 'auto' in the function parameter with this invented | |||
2973 | // template type parameter. | |||
2974 | // FIXME: Retain some type sugar to indicate that this was written | |||
2975 | // as 'auto'. | |||
2976 | T = state.ReplaceAutoType( | |||
2977 | T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0)); | |||
2978 | } | |||
2979 | break; | |||
2980 | case DeclaratorContext::MemberContext: { | |||
2981 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || | |||
2982 | D.isFunctionDeclarator()) | |||
2983 | break; | |||
2984 | bool Cxx = SemaRef.getLangOpts().CPlusPlus; | |||
2985 | switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { | |||
2986 | case TTK_Enum: llvm_unreachable("unhandled tag kind")::llvm::llvm_unreachable_internal("unhandled tag kind", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 2986); | |||
2987 | case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; | |||
2988 | case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; | |||
2989 | case TTK_Class: Error = 5; /* Class member */ break; | |||
2990 | case TTK_Interface: Error = 6; /* Interface member */ break; | |||
2991 | } | |||
2992 | if (D.getDeclSpec().isFriendSpecified()) | |||
2993 | Error = 20; // Friend type | |||
2994 | break; | |||
2995 | } | |||
2996 | case DeclaratorContext::CXXCatchContext: | |||
2997 | case DeclaratorContext::ObjCCatchContext: | |||
2998 | Error = 7; // Exception declaration | |||
2999 | break; | |||
3000 | case DeclaratorContext::TemplateParamContext: | |||
3001 | if (isa<DeducedTemplateSpecializationType>(Deduced)) | |||
3002 | Error = 19; // Template parameter | |||
3003 | else if (!SemaRef.getLangOpts().CPlusPlus17) | |||
3004 | Error = 8; // Template parameter (until C++17) | |||
3005 | break; | |||
3006 | case DeclaratorContext::BlockLiteralContext: | |||
3007 | Error = 9; // Block literal | |||
3008 | break; | |||
3009 | case DeclaratorContext::TemplateArgContext: | |||
3010 | // Within a template argument list, a deduced template specialization | |||
3011 | // type will be reinterpreted as a template template argument. | |||
3012 | if (isa<DeducedTemplateSpecializationType>(Deduced) && | |||
3013 | !D.getNumTypeObjects() && | |||
3014 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) | |||
3015 | break; | |||
3016 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
3017 | case DeclaratorContext::TemplateTypeArgContext: | |||
3018 | Error = 10; // Template type argument | |||
3019 | break; | |||
3020 | case DeclaratorContext::AliasDeclContext: | |||
3021 | case DeclaratorContext::AliasTemplateContext: | |||
3022 | Error = 12; // Type alias | |||
3023 | break; | |||
3024 | case DeclaratorContext::TrailingReturnContext: | |||
3025 | case DeclaratorContext::TrailingReturnVarContext: | |||
3026 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | |||
3027 | Error = 13; // Function return type | |||
3028 | IsDeducedReturnType = true; | |||
3029 | break; | |||
3030 | case DeclaratorContext::ConversionIdContext: | |||
3031 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | |||
3032 | Error = 14; // conversion-type-id | |||
3033 | IsDeducedReturnType = true; | |||
3034 | break; | |||
3035 | case DeclaratorContext::FunctionalCastContext: | |||
3036 | if (isa<DeducedTemplateSpecializationType>(Deduced)) | |||
3037 | break; | |||
3038 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
3039 | case DeclaratorContext::TypeNameContext: | |||
3040 | Error = 15; // Generic | |||
3041 | break; | |||
3042 | case DeclaratorContext::FileContext: | |||
3043 | case DeclaratorContext::BlockContext: | |||
3044 | case DeclaratorContext::ForContext: | |||
3045 | case DeclaratorContext::InitStmtContext: | |||
3046 | case DeclaratorContext::ConditionContext: | |||
3047 | // FIXME: P0091R3 (erroneously) does not permit class template argument | |||
3048 | // deduction in conditions, for-init-statements, and other declarations | |||
3049 | // that are not simple-declarations. | |||
3050 | break; | |||
3051 | case DeclaratorContext::CXXNewContext: | |||
3052 | // FIXME: P0091R3 does not permit class template argument deduction here, | |||
3053 | // but we follow GCC and allow it anyway. | |||
3054 | if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) | |||
3055 | Error = 17; // 'new' type | |||
3056 | break; | |||
3057 | case DeclaratorContext::KNRTypeListContext: | |||
3058 | Error = 18; // K&R function parameter | |||
3059 | break; | |||
3060 | } | |||
3061 | ||||
3062 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
3063 | Error = 11; | |||
3064 | ||||
3065 | // In Objective-C it is an error to use 'auto' on a function declarator | |||
3066 | // (and everywhere for '__auto_type'). | |||
3067 | if (D.isFunctionDeclarator() && | |||
3068 | (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) | |||
3069 | Error = 13; | |||
3070 | ||||
3071 | bool HaveTrailing = false; | |||
3072 | ||||
3073 | // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator | |||
3074 | // contains a trailing return type. That is only legal at the outermost | |||
3075 | // level. Check all declarator chunks (outermost first) anyway, to give | |||
3076 | // better diagnostics. | |||
3077 | // We don't support '__auto_type' with trailing return types. | |||
3078 | // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'? | |||
3079 | if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType && | |||
3080 | D.hasTrailingReturnType()) { | |||
3081 | HaveTrailing = true; | |||
3082 | Error = -1; | |||
3083 | } | |||
3084 | ||||
3085 | SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); | |||
3086 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | |||
3087 | AutoRange = D.getName().getSourceRange(); | |||
3088 | ||||
3089 | if (Error != -1) { | |||
3090 | unsigned Kind; | |||
3091 | if (Auto) { | |||
3092 | switch (Auto->getKeyword()) { | |||
3093 | case AutoTypeKeyword::Auto: Kind = 0; break; | |||
3094 | case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; | |||
3095 | case AutoTypeKeyword::GNUAutoType: Kind = 2; break; | |||
3096 | } | |||
3097 | } else { | |||
3098 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3099, __PRETTY_FUNCTION__)) | |||
3099 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3099, __PRETTY_FUNCTION__)); | |||
3100 | Kind = 3; | |||
3101 | } | |||
3102 | ||||
3103 | auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); | |||
3104 | TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); | |||
3105 | ||||
3106 | SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) | |||
3107 | << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) | |||
3108 | << QualType(Deduced, 0) << AutoRange; | |||
3109 | if (auto *TD = TN.getAsTemplateDecl()) | |||
3110 | SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here); | |||
3111 | ||||
3112 | T = SemaRef.Context.IntTy; | |||
3113 | D.setInvalidType(true); | |||
3114 | } else if (!HaveTrailing && | |||
3115 | D.getContext() != DeclaratorContext::LambdaExprContext) { | |||
3116 | // If there was a trailing return type, we already got | |||
3117 | // warn_cxx98_compat_trailing_return_type in the parser. | |||
3118 | SemaRef.Diag(AutoRange.getBegin(), | |||
3119 | D.getContext() == | |||
3120 | DeclaratorContext::LambdaExprParameterContext | |||
3121 | ? diag::warn_cxx11_compat_generic_lambda | |||
3122 | : IsDeducedReturnType | |||
3123 | ? diag::warn_cxx11_compat_deduced_return_type | |||
3124 | : diag::warn_cxx98_compat_auto_type_specifier) | |||
3125 | << AutoRange; | |||
3126 | } | |||
3127 | } | |||
3128 | ||||
3129 | if (SemaRef.getLangOpts().CPlusPlus && | |||
3130 | OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { | |||
3131 | // Check the contexts where C++ forbids the declaration of a new class | |||
3132 | // or enumeration in a type-specifier-seq. | |||
3133 | unsigned DiagID = 0; | |||
3134 | switch (D.getContext()) { | |||
3135 | case DeclaratorContext::TrailingReturnContext: | |||
3136 | case DeclaratorContext::TrailingReturnVarContext: | |||
3137 | // Class and enumeration definitions are syntactically not allowed in | |||
3138 | // trailing return types. | |||
3139 | llvm_unreachable("parser should not have allowed this")::llvm::llvm_unreachable_internal("parser should not have allowed this" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3139); | |||
3140 | break; | |||
3141 | case DeclaratorContext::FileContext: | |||
3142 | case DeclaratorContext::MemberContext: | |||
3143 | case DeclaratorContext::BlockContext: | |||
3144 | case DeclaratorContext::ForContext: | |||
3145 | case DeclaratorContext::InitStmtContext: | |||
3146 | case DeclaratorContext::BlockLiteralContext: | |||
3147 | case DeclaratorContext::LambdaExprContext: | |||
3148 | // C++11 [dcl.type]p3: | |||
3149 | // A type-specifier-seq shall not define a class or enumeration unless | |||
3150 | // it appears in the type-id of an alias-declaration (7.1.3) that is not | |||
3151 | // the declaration of a template-declaration. | |||
3152 | case DeclaratorContext::AliasDeclContext: | |||
3153 | break; | |||
3154 | case DeclaratorContext::AliasTemplateContext: | |||
3155 | DiagID = diag::err_type_defined_in_alias_template; | |||
3156 | break; | |||
3157 | case DeclaratorContext::TypeNameContext: | |||
3158 | case DeclaratorContext::FunctionalCastContext: | |||
3159 | case DeclaratorContext::ConversionIdContext: | |||
3160 | case DeclaratorContext::TemplateParamContext: | |||
3161 | case DeclaratorContext::CXXNewContext: | |||
3162 | case DeclaratorContext::CXXCatchContext: | |||
3163 | case DeclaratorContext::ObjCCatchContext: | |||
3164 | case DeclaratorContext::TemplateArgContext: | |||
3165 | case DeclaratorContext::TemplateTypeArgContext: | |||
3166 | DiagID = diag::err_type_defined_in_type_specifier; | |||
3167 | break; | |||
3168 | case DeclaratorContext::PrototypeContext: | |||
3169 | case DeclaratorContext::LambdaExprParameterContext: | |||
3170 | case DeclaratorContext::ObjCParameterContext: | |||
3171 | case DeclaratorContext::ObjCResultContext: | |||
3172 | case DeclaratorContext::KNRTypeListContext: | |||
3173 | // C++ [dcl.fct]p6: | |||
3174 | // Types shall not be defined in return or parameter types. | |||
3175 | DiagID = diag::err_type_defined_in_param_type; | |||
3176 | break; | |||
3177 | case DeclaratorContext::ConditionContext: | |||
3178 | // C++ 6.4p2: | |||
3179 | // The type-specifier-seq shall not contain typedef and shall not declare | |||
3180 | // a new class or enumeration. | |||
3181 | DiagID = diag::err_type_defined_in_condition; | |||
3182 | break; | |||
3183 | } | |||
3184 | ||||
3185 | if (DiagID != 0) { | |||
3186 | SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) | |||
3187 | << SemaRef.Context.getTypeDeclType(OwnedTagDecl); | |||
3188 | D.setInvalidType(true); | |||
3189 | } | |||
3190 | } | |||
3191 | ||||
3192 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3192, __PRETTY_FUNCTION__)); | |||
3193 | return T; | |||
3194 | } | |||
3195 | ||||
3196 | /// Produce an appropriate diagnostic for an ambiguity between a function | |||
3197 | /// declarator and a C++ direct-initializer. | |||
3198 | static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, | |||
3199 | DeclaratorChunk &DeclType, QualType RT) { | |||
3200 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
3201 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3201, __PRETTY_FUNCTION__)); | |||
3202 | ||||
3203 | // If the return type is void there is no ambiguity. | |||
3204 | if (RT->isVoidType()) | |||
3205 | return; | |||
3206 | ||||
3207 | // An initializer for a non-class type can have at most one argument. | |||
3208 | if (!RT->isRecordType() && FTI.NumParams > 1) | |||
3209 | return; | |||
3210 | ||||
3211 | // An initializer for a reference must have exactly one argument. | |||
3212 | if (RT->isReferenceType() && FTI.NumParams != 1) | |||
3213 | return; | |||
3214 | ||||
3215 | // Only warn if this declarator is declaring a function at block scope, and | |||
3216 | // doesn't have a storage class (such as 'extern') specified. | |||
3217 | if (!D.isFunctionDeclarator() || | |||
3218 | D.getFunctionDefinitionKind() != FDK_Declaration || | |||
3219 | !S.CurContext->isFunctionOrMethod() || | |||
3220 | D.getDeclSpec().getStorageClassSpec() | |||
3221 | != DeclSpec::SCS_unspecified) | |||
3222 | return; | |||
3223 | ||||
3224 | // Inside a condition, a direct initializer is not permitted. We allow one to | |||
3225 | // be parsed in order to give better diagnostics in condition parsing. | |||
3226 | if (D.getContext() == DeclaratorContext::ConditionContext) | |||
3227 | return; | |||
3228 | ||||
3229 | SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); | |||
3230 | ||||
3231 | S.Diag(DeclType.Loc, | |||
3232 | FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration | |||
3233 | : diag::warn_empty_parens_are_function_decl) | |||
3234 | << ParenRange; | |||
3235 | ||||
3236 | // If the declaration looks like: | |||
3237 | // T var1, | |||
3238 | // f(); | |||
3239 | // and name lookup finds a function named 'f', then the ',' was | |||
3240 | // probably intended to be a ';'. | |||
3241 | if (!D.isFirstDeclarator() && D.getIdentifier()) { | |||
3242 | FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); | |||
3243 | FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); | |||
3244 | if (Comma.getFileID() != Name.getFileID() || | |||
3245 | Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { | |||
3246 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | |||
3247 | Sema::LookupOrdinaryName); | |||
3248 | if (S.LookupName(Result, S.getCurScope())) | |||
3249 | S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) | |||
3250 | << FixItHint::CreateReplacement(D.getCommaLoc(), ";") | |||
3251 | << D.getIdentifier(); | |||
3252 | Result.suppressDiagnostics(); | |||
3253 | } | |||
3254 | } | |||
3255 | ||||
3256 | if (FTI.NumParams > 0) { | |||
3257 | // For a declaration with parameters, eg. "T var(T());", suggest adding | |||
3258 | // parens around the first parameter to turn the declaration into a | |||
3259 | // variable declaration. | |||
3260 | SourceRange Range = FTI.Params[0].Param->getSourceRange(); | |||
3261 | SourceLocation B = Range.getBegin(); | |||
3262 | SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); | |||
3263 | // FIXME: Maybe we should suggest adding braces instead of parens | |||
3264 | // in C++11 for classes that don't have an initializer_list constructor. | |||
3265 | S.Diag(B, diag::note_additional_parens_for_variable_declaration) | |||
3266 | << FixItHint::CreateInsertion(B, "(") | |||
3267 | << FixItHint::CreateInsertion(E, ")"); | |||
3268 | } else { | |||
3269 | // For a declaration without parameters, eg. "T var();", suggest replacing | |||
3270 | // the parens with an initializer to turn the declaration into a variable | |||
3271 | // declaration. | |||
3272 | const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); | |||
3273 | ||||
3274 | // Empty parens mean value-initialization, and no parens mean | |||
3275 | // default initialization. These are equivalent if the default | |||
3276 | // constructor is user-provided or if zero-initialization is a | |||
3277 | // no-op. | |||
3278 | if (RD && RD->hasDefinition() && | |||
3279 | (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) | |||
3280 | S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) | |||
3281 | << FixItHint::CreateRemoval(ParenRange); | |||
3282 | else { | |||
3283 | std::string Init = | |||
3284 | S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); | |||
3285 | if (Init.empty() && S.LangOpts.CPlusPlus11) | |||
3286 | Init = "{}"; | |||
3287 | if (!Init.empty()) | |||
3288 | S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) | |||
3289 | << FixItHint::CreateReplacement(ParenRange, Init); | |||
3290 | } | |||
3291 | } | |||
3292 | } | |||
3293 | ||||
3294 | /// Produce an appropriate diagnostic for a declarator with top-level | |||
3295 | /// parentheses. | |||
3296 | static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { | |||
3297 | DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); | |||
3298 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3299, __PRETTY_FUNCTION__)) | |||
3299 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3299, __PRETTY_FUNCTION__)); | |||
3300 | ||||
3301 | // This is a syntactic check; we're not interested in cases that arise | |||
3302 | // during template instantiation. | |||
3303 | if (S.inTemplateInstantiation()) | |||
3304 | return; | |||
3305 | ||||
3306 | // Check whether this could be intended to be a construction of a temporary | |||
3307 | // object in C++ via a function-style cast. | |||
3308 | bool CouldBeTemporaryObject = | |||
3309 | S.getLangOpts().CPlusPlus && D.isExpressionContext() && | |||
3310 | !D.isInvalidType() && D.getIdentifier() && | |||
3311 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && | |||
3312 | (T->isRecordType() || T->isDependentType()) && | |||
3313 | D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); | |||
3314 | ||||
3315 | bool StartsWithDeclaratorId = true; | |||
3316 | for (auto &C : D.type_objects()) { | |||
3317 | switch (C.Kind) { | |||
3318 | case DeclaratorChunk::Paren: | |||
3319 | if (&C == &Paren) | |||
3320 | continue; | |||
3321 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
3322 | case DeclaratorChunk::Pointer: | |||
3323 | StartsWithDeclaratorId = false; | |||
3324 | continue; | |||
3325 | ||||
3326 | case DeclaratorChunk::Array: | |||
3327 | if (!C.Arr.NumElts) | |||
3328 | CouldBeTemporaryObject = false; | |||
3329 | continue; | |||
3330 | ||||
3331 | case DeclaratorChunk::Reference: | |||
3332 | // FIXME: Suppress the warning here if there is no initializer; we're | |||
3333 | // going to give an error anyway. | |||
3334 | // We assume that something like 'T (&x) = y;' is highly likely to not | |||
3335 | // be intended to be a temporary object. | |||
3336 | CouldBeTemporaryObject = false; | |||
3337 | StartsWithDeclaratorId = false; | |||
3338 | continue; | |||
3339 | ||||
3340 | case DeclaratorChunk::Function: | |||
3341 | // In a new-type-id, function chunks require parentheses. | |||
3342 | if (D.getContext() == DeclaratorContext::CXXNewContext) | |||
3343 | return; | |||
3344 | // FIXME: "A(f())" deserves a vexing-parse warning, not just a | |||
3345 | // redundant-parens warning, but we don't know whether the function | |||
3346 | // chunk was syntactically valid as an expression here. | |||
3347 | CouldBeTemporaryObject = false; | |||
3348 | continue; | |||
3349 | ||||
3350 | case DeclaratorChunk::BlockPointer: | |||
3351 | case DeclaratorChunk::MemberPointer: | |||
3352 | case DeclaratorChunk::Pipe: | |||
3353 | // These cannot appear in expressions. | |||
3354 | CouldBeTemporaryObject = false; | |||
3355 | StartsWithDeclaratorId = false; | |||
3356 | continue; | |||
3357 | } | |||
3358 | } | |||
3359 | ||||
3360 | // FIXME: If there is an initializer, assume that this is not intended to be | |||
3361 | // a construction of a temporary object. | |||
3362 | ||||
3363 | // Check whether the name has already been declared; if not, this is not a | |||
3364 | // function-style cast. | |||
3365 | if (CouldBeTemporaryObject) { | |||
3366 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | |||
3367 | Sema::LookupOrdinaryName); | |||
3368 | if (!S.LookupName(Result, S.getCurScope())) | |||
3369 | CouldBeTemporaryObject = false; | |||
3370 | Result.suppressDiagnostics(); | |||
3371 | } | |||
3372 | ||||
3373 | SourceRange ParenRange(Paren.Loc, Paren.EndLoc); | |||
3374 | ||||
3375 | if (!CouldBeTemporaryObject) { | |||
3376 | // If we have A (::B), the parentheses affect the meaning of the program. | |||
3377 | // Suppress the warning in that case. Don't bother looking at the DeclSpec | |||
3378 | // here: even (e.g.) "int ::x" is visually ambiguous even though it's | |||
3379 | // formally unambiguous. | |||
3380 | if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { | |||
3381 | for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; | |||
3382 | NNS = NNS->getPrefix()) { | |||
3383 | if (NNS->getKind() == NestedNameSpecifier::Global) | |||
3384 | return; | |||
3385 | } | |||
3386 | } | |||
3387 | ||||
3388 | S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) | |||
3389 | << ParenRange << FixItHint::CreateRemoval(Paren.Loc) | |||
3390 | << FixItHint::CreateRemoval(Paren.EndLoc); | |||
3391 | return; | |||
3392 | } | |||
3393 | ||||
3394 | S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) | |||
3395 | << ParenRange << D.getIdentifier(); | |||
3396 | auto *RD = T->getAsCXXRecordDecl(); | |||
3397 | if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) | |||
3398 | S.Diag(Paren.Loc, diag::note_raii_guard_add_name) | |||
3399 | << FixItHint::CreateInsertion(Paren.Loc, " varname") << T | |||
3400 | << D.getIdentifier(); | |||
3401 | // FIXME: A cast to void is probably a better suggestion in cases where it's | |||
3402 | // valid (when there is no initializer and we're not in a condition). | |||
3403 | S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) | |||
3404 | << FixItHint::CreateInsertion(D.getBeginLoc(), "(") | |||
3405 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")"); | |||
3406 | S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) | |||
3407 | << FixItHint::CreateRemoval(Paren.Loc) | |||
3408 | << FixItHint::CreateRemoval(Paren.EndLoc); | |||
3409 | } | |||
3410 | ||||
3411 | /// Helper for figuring out the default CC for a function declarator type. If | |||
3412 | /// this is the outermost chunk, then we can determine the CC from the | |||
3413 | /// declarator context. If not, then this could be either a member function | |||
3414 | /// type or normal function type. | |||
3415 | static CallingConv getCCForDeclaratorChunk( | |||
3416 | Sema &S, Declarator &D, const ParsedAttributesView &AttrList, | |||
3417 | const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { | |||
3418 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3418, __PRETTY_FUNCTION__)); | |||
3419 | ||||
3420 | // Check for an explicit CC attribute. | |||
3421 | for (const ParsedAttr &AL : AttrList) { | |||
3422 | switch (AL.getKind()) { | |||
3423 | 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 : { | |||
3424 | // Ignore attributes that don't validate or can't apply to the | |||
3425 | // function type. We'll diagnose the failure to apply them in | |||
3426 | // handleFunctionTypeAttr. | |||
3427 | CallingConv CC; | |||
3428 | if (!S.CheckCallingConvAttr(AL, CC) && | |||
3429 | (!FTI.isVariadic || supportsVariadicCall(CC))) { | |||
3430 | return CC; | |||
3431 | } | |||
3432 | break; | |||
3433 | } | |||
3434 | ||||
3435 | default: | |||
3436 | break; | |||
3437 | } | |||
3438 | } | |||
3439 | ||||
3440 | bool IsCXXInstanceMethod = false; | |||
3441 | ||||
3442 | if (S.getLangOpts().CPlusPlus) { | |||
3443 | // Look inwards through parentheses to see if this chunk will form a | |||
3444 | // member pointer type or if we're the declarator. Any type attributes | |||
3445 | // between here and there will override the CC we choose here. | |||
3446 | unsigned I = ChunkIndex; | |||
3447 | bool FoundNonParen = false; | |||
3448 | while (I && !FoundNonParen) { | |||
3449 | --I; | |||
3450 | if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) | |||
3451 | FoundNonParen = true; | |||
3452 | } | |||
3453 | ||||
3454 | if (FoundNonParen) { | |||
3455 | // If we're not the declarator, we're a regular function type unless we're | |||
3456 | // in a member pointer. | |||
3457 | IsCXXInstanceMethod = | |||
3458 | D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; | |||
3459 | } else if (D.getContext() == DeclaratorContext::LambdaExprContext) { | |||
3460 | // This can only be a call operator for a lambda, which is an instance | |||
3461 | // method. | |||
3462 | IsCXXInstanceMethod = true; | |||
3463 | } else { | |||
3464 | // We're the innermost decl chunk, so must be a function declarator. | |||
3465 | assert(D.isFunctionDeclarator())((D.isFunctionDeclarator()) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3465, __PRETTY_FUNCTION__)); | |||
3466 | ||||
3467 | // If we're inside a record, we're declaring a method, but it could be | |||
3468 | // explicitly or implicitly static. | |||
3469 | IsCXXInstanceMethod = | |||
3470 | D.isFirstDeclarationOfMember() && | |||
3471 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | |||
3472 | !D.isStaticMember(); | |||
3473 | } | |||
3474 | } | |||
3475 | ||||
3476 | CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, | |||
3477 | IsCXXInstanceMethod); | |||
3478 | ||||
3479 | // Attribute AT_OpenCLKernel affects the calling convention for SPIR | |||
3480 | // and AMDGPU targets, hence it cannot be treated as a calling | |||
3481 | // convention attribute. This is the simplest place to infer | |||
3482 | // calling convention for OpenCL kernels. | |||
3483 | if (S.getLangOpts().OpenCL) { | |||
3484 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | |||
3485 | if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { | |||
3486 | CC = CC_OpenCLKernel; | |||
3487 | break; | |||
3488 | } | |||
3489 | } | |||
3490 | } | |||
3491 | ||||
3492 | return CC; | |||
3493 | } | |||
3494 | ||||
3495 | namespace { | |||
3496 | /// A simple notion of pointer kinds, which matches up with the various | |||
3497 | /// pointer declarators. | |||
3498 | enum class SimplePointerKind { | |||
3499 | Pointer, | |||
3500 | BlockPointer, | |||
3501 | MemberPointer, | |||
3502 | Array, | |||
3503 | }; | |||
3504 | } // end anonymous namespace | |||
3505 | ||||
3506 | IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { | |||
3507 | switch (nullability) { | |||
3508 | case NullabilityKind::NonNull: | |||
3509 | if (!Ident__Nonnull) | |||
3510 | Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); | |||
3511 | return Ident__Nonnull; | |||
3512 | ||||
3513 | case NullabilityKind::Nullable: | |||
3514 | if (!Ident__Nullable) | |||
3515 | Ident__Nullable = PP.getIdentifierInfo("_Nullable"); | |||
3516 | return Ident__Nullable; | |||
3517 | ||||
3518 | case NullabilityKind::Unspecified: | |||
3519 | if (!Ident__Null_unspecified) | |||
3520 | Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); | |||
3521 | return Ident__Null_unspecified; | |||
3522 | } | |||
3523 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3523); | |||
3524 | } | |||
3525 | ||||
3526 | /// Retrieve the identifier "NSError". | |||
3527 | IdentifierInfo *Sema::getNSErrorIdent() { | |||
3528 | if (!Ident_NSError) | |||
3529 | Ident_NSError = PP.getIdentifierInfo("NSError"); | |||
3530 | ||||
3531 | return Ident_NSError; | |||
3532 | } | |||
3533 | ||||
3534 | /// Check whether there is a nullability attribute of any kind in the given | |||
3535 | /// attribute list. | |||
3536 | static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { | |||
3537 | for (const ParsedAttr &AL : attrs) { | |||
3538 | if (AL.getKind() == ParsedAttr::AT_TypeNonNull || | |||
3539 | AL.getKind() == ParsedAttr::AT_TypeNullable || | |||
3540 | AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) | |||
3541 | return true; | |||
3542 | } | |||
3543 | ||||
3544 | return false; | |||
3545 | } | |||
3546 | ||||
3547 | namespace { | |||
3548 | /// Describes the kind of a pointer a declarator describes. | |||
3549 | enum class PointerDeclaratorKind { | |||
3550 | // Not a pointer. | |||
3551 | NonPointer, | |||
3552 | // Single-level pointer. | |||
3553 | SingleLevelPointer, | |||
3554 | // Multi-level pointer (of any pointer kind). | |||
3555 | MultiLevelPointer, | |||
3556 | // CFFooRef* | |||
3557 | MaybePointerToCFRef, | |||
3558 | // CFErrorRef* | |||
3559 | CFErrorRefPointer, | |||
3560 | // NSError** | |||
3561 | NSErrorPointerPointer, | |||
3562 | }; | |||
3563 | ||||
3564 | /// Describes a declarator chunk wrapping a pointer that marks inference as | |||
3565 | /// unexpected. | |||
3566 | // These values must be kept in sync with diagnostics. | |||
3567 | enum class PointerWrappingDeclaratorKind { | |||
3568 | /// Pointer is top-level. | |||
3569 | None = -1, | |||
3570 | /// Pointer is an array element. | |||
3571 | Array = 0, | |||
3572 | /// Pointer is the referent type of a C++ reference. | |||
3573 | Reference = 1 | |||
3574 | }; | |||
3575 | } // end anonymous namespace | |||
3576 | ||||
3577 | /// Classify the given declarator, whose type-specified is \c type, based on | |||
3578 | /// what kind of pointer it refers to. | |||
3579 | /// | |||
3580 | /// This is used to determine the default nullability. | |||
3581 | static PointerDeclaratorKind | |||
3582 | classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, | |||
3583 | PointerWrappingDeclaratorKind &wrappingKind) { | |||
3584 | unsigned numNormalPointers = 0; | |||
3585 | ||||
3586 | // For any dependent type, we consider it a non-pointer. | |||
3587 | if (type->isDependentType()) | |||
3588 | return PointerDeclaratorKind::NonPointer; | |||
3589 | ||||
3590 | // Look through the declarator chunks to identify pointers. | |||
3591 | for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { | |||
3592 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
3593 | switch (chunk.Kind) { | |||
3594 | case DeclaratorChunk::Array: | |||
3595 | if (numNormalPointers == 0) | |||
3596 | wrappingKind = PointerWrappingDeclaratorKind::Array; | |||
3597 | break; | |||
3598 | ||||
3599 | case DeclaratorChunk::Function: | |||
3600 | case DeclaratorChunk::Pipe: | |||
3601 | break; | |||
3602 | ||||
3603 | case DeclaratorChunk::BlockPointer: | |||
3604 | case DeclaratorChunk::MemberPointer: | |||
3605 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
3606 | : PointerDeclaratorKind::SingleLevelPointer; | |||
3607 | ||||
3608 | case DeclaratorChunk::Paren: | |||
3609 | break; | |||
3610 | ||||
3611 | case DeclaratorChunk::Reference: | |||
3612 | if (numNormalPointers == 0) | |||
3613 | wrappingKind = PointerWrappingDeclaratorKind::Reference; | |||
3614 | break; | |||
3615 | ||||
3616 | case DeclaratorChunk::Pointer: | |||
3617 | ++numNormalPointers; | |||
3618 | if (numNormalPointers > 2) | |||
3619 | return PointerDeclaratorKind::MultiLevelPointer; | |||
3620 | break; | |||
3621 | } | |||
3622 | } | |||
3623 | ||||
3624 | // Then, dig into the type specifier itself. | |||
3625 | unsigned numTypeSpecifierPointers = 0; | |||
3626 | do { | |||
3627 | // Decompose normal pointers. | |||
3628 | if (auto ptrType = type->getAs<PointerType>()) { | |||
3629 | ++numNormalPointers; | |||
3630 | ||||
3631 | if (numNormalPointers > 2) | |||
3632 | return PointerDeclaratorKind::MultiLevelPointer; | |||
3633 | ||||
3634 | type = ptrType->getPointeeType(); | |||
3635 | ++numTypeSpecifierPointers; | |||
3636 | continue; | |||
3637 | } | |||
3638 | ||||
3639 | // Decompose block pointers. | |||
3640 | if (type->getAs<BlockPointerType>()) { | |||
3641 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
3642 | : PointerDeclaratorKind::SingleLevelPointer; | |||
3643 | } | |||
3644 | ||||
3645 | // Decompose member pointers. | |||
3646 | if (type->getAs<MemberPointerType>()) { | |||
3647 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
3648 | : PointerDeclaratorKind::SingleLevelPointer; | |||
3649 | } | |||
3650 | ||||
3651 | // Look at Objective-C object pointers. | |||
3652 | if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { | |||
3653 | ++numNormalPointers; | |||
3654 | ++numTypeSpecifierPointers; | |||
3655 | ||||
3656 | // If this is NSError**, report that. | |||
3657 | if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { | |||
3658 | if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && | |||
3659 | numNormalPointers == 2 && numTypeSpecifierPointers < 2) { | |||
3660 | return PointerDeclaratorKind::NSErrorPointerPointer; | |||
3661 | } | |||
3662 | } | |||
3663 | ||||
3664 | break; | |||
3665 | } | |||
3666 | ||||
3667 | // Look at Objective-C class types. | |||
3668 | if (auto objcClass = type->getAs<ObjCInterfaceType>()) { | |||
3669 | if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { | |||
3670 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) | |||
3671 | return PointerDeclaratorKind::NSErrorPointerPointer; | |||
3672 | } | |||
3673 | ||||
3674 | break; | |||
3675 | } | |||
3676 | ||||
3677 | // If at this point we haven't seen a pointer, we won't see one. | |||
3678 | if (numNormalPointers == 0) | |||
3679 | return PointerDeclaratorKind::NonPointer; | |||
3680 | ||||
3681 | if (auto recordType = type->getAs<RecordType>()) { | |||
3682 | RecordDecl *recordDecl = recordType->getDecl(); | |||
3683 | ||||
3684 | bool isCFError = false; | |||
3685 | if (S.CFError) { | |||
3686 | // If we already know about CFError, test it directly. | |||
3687 | isCFError = (S.CFError == recordDecl); | |||
3688 | } else { | |||
3689 | // Check whether this is CFError, which we identify based on its bridge | |||
3690 | // to NSError. CFErrorRef used to be declared with "objc_bridge" but is | |||
3691 | // now declared with "objc_bridge_mutable", so look for either one of | |||
3692 | // the two attributes. | |||
3693 | if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) { | |||
3694 | IdentifierInfo *bridgedType = nullptr; | |||
3695 | if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) | |||
3696 | bridgedType = bridgeAttr->getBridgedType(); | |||
3697 | else if (auto bridgeAttr = | |||
3698 | recordDecl->getAttr<ObjCBridgeMutableAttr>()) | |||
3699 | bridgedType = bridgeAttr->getBridgedType(); | |||
3700 | ||||
3701 | if (bridgedType == S.getNSErrorIdent()) { | |||
3702 | S.CFError = recordDecl; | |||
3703 | isCFError = true; | |||
3704 | } | |||
3705 | } | |||
3706 | } | |||
3707 | ||||
3708 | // If this is CFErrorRef*, report it as such. | |||
3709 | if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) { | |||
3710 | return PointerDeclaratorKind::CFErrorRefPointer; | |||
3711 | } | |||
3712 | break; | |||
3713 | } | |||
3714 | ||||
3715 | break; | |||
3716 | } while (true); | |||
3717 | ||||
3718 | switch (numNormalPointers) { | |||
3719 | case 0: | |||
3720 | return PointerDeclaratorKind::NonPointer; | |||
3721 | ||||
3722 | case 1: | |||
3723 | return PointerDeclaratorKind::SingleLevelPointer; | |||
3724 | ||||
3725 | case 2: | |||
3726 | return PointerDeclaratorKind::MaybePointerToCFRef; | |||
3727 | ||||
3728 | default: | |||
3729 | return PointerDeclaratorKind::MultiLevelPointer; | |||
3730 | } | |||
3731 | } | |||
3732 | ||||
3733 | static FileID getNullabilityCompletenessCheckFileID(Sema &S, | |||
3734 | SourceLocation loc) { | |||
3735 | // If we're anywhere in a function, method, or closure context, don't perform | |||
3736 | // completeness checks. | |||
3737 | for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { | |||
3738 | if (ctx->isFunctionOrMethod()) | |||
3739 | return FileID(); | |||
3740 | ||||
3741 | if (ctx->isFileContext()) | |||
3742 | break; | |||
3743 | } | |||
3744 | ||||
3745 | // We only care about the expansion location. | |||
3746 | loc = S.SourceMgr.getExpansionLoc(loc); | |||
3747 | FileID file = S.SourceMgr.getFileID(loc); | |||
3748 | if (file.isInvalid()) | |||
3749 | return FileID(); | |||
3750 | ||||
3751 | // Retrieve file information. | |||
3752 | bool invalid = false; | |||
3753 | const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); | |||
3754 | if (invalid || !sloc.isFile()) | |||
3755 | return FileID(); | |||
3756 | ||||
3757 | // We don't want to perform completeness checks on the main file or in | |||
3758 | // system headers. | |||
3759 | const SrcMgr::FileInfo &fileInfo = sloc.getFile(); | |||
3760 | if (fileInfo.getIncludeLoc().isInvalid()) | |||
3761 | return FileID(); | |||
3762 | if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && | |||
3763 | S.Diags.getSuppressSystemWarnings()) { | |||
3764 | return FileID(); | |||
3765 | } | |||
3766 | ||||
3767 | return file; | |||
3768 | } | |||
3769 | ||||
3770 | /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, | |||
3771 | /// taking into account whitespace before and after. | |||
3772 | static void fixItNullability(Sema &S, DiagnosticBuilder &Diag, | |||
3773 | SourceLocation PointerLoc, | |||
3774 | NullabilityKind Nullability) { | |||
3775 | assert(PointerLoc.isValid())((PointerLoc.isValid()) ? static_cast<void> (0) : __assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3775, __PRETTY_FUNCTION__)); | |||
3776 | if (PointerLoc.isMacroID()) | |||
3777 | return; | |||
3778 | ||||
3779 | SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); | |||
3780 | if (!FixItLoc.isValid() || FixItLoc == PointerLoc) | |||
3781 | return; | |||
3782 | ||||
3783 | const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); | |||
3784 | if (!NextChar) | |||
3785 | return; | |||
3786 | ||||
3787 | SmallString<32> InsertionTextBuf{" "}; | |||
3788 | InsertionTextBuf += getNullabilitySpelling(Nullability); | |||
3789 | InsertionTextBuf += " "; | |||
3790 | StringRef InsertionText = InsertionTextBuf.str(); | |||
3791 | ||||
3792 | if (isWhitespace(*NextChar)) { | |||
3793 | InsertionText = InsertionText.drop_back(); | |||
3794 | } else if (NextChar[-1] == '[') { | |||
3795 | if (NextChar[0] == ']') | |||
3796 | InsertionText = InsertionText.drop_back().drop_front(); | |||
3797 | else | |||
3798 | InsertionText = InsertionText.drop_front(); | |||
3799 | } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) && | |||
3800 | !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) { | |||
3801 | InsertionText = InsertionText.drop_back().drop_front(); | |||
3802 | } | |||
3803 | ||||
3804 | Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); | |||
3805 | } | |||
3806 | ||||
3807 | static void emitNullabilityConsistencyWarning(Sema &S, | |||
3808 | SimplePointerKind PointerKind, | |||
3809 | SourceLocation PointerLoc, | |||
3810 | SourceLocation PointerEndLoc) { | |||
3811 | assert(PointerLoc.isValid())((PointerLoc.isValid()) ? static_cast<void> (0) : __assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3811, __PRETTY_FUNCTION__)); | |||
3812 | ||||
3813 | if (PointerKind == SimplePointerKind::Array) { | |||
3814 | S.Diag(PointerLoc, diag::warn_nullability_missing_array); | |||
3815 | } else { | |||
3816 | S.Diag(PointerLoc, diag::warn_nullability_missing) | |||
3817 | << static_cast<unsigned>(PointerKind); | |||
3818 | } | |||
3819 | ||||
3820 | auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; | |||
3821 | if (FixItLoc.isMacroID()) | |||
3822 | return; | |||
3823 | ||||
3824 | auto addFixIt = [&](NullabilityKind Nullability) { | |||
3825 | auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); | |||
3826 | Diag << static_cast<unsigned>(Nullability); | |||
3827 | Diag << static_cast<unsigned>(PointerKind); | |||
3828 | fixItNullability(S, Diag, FixItLoc, Nullability); | |||
3829 | }; | |||
3830 | addFixIt(NullabilityKind::Nullable); | |||
3831 | addFixIt(NullabilityKind::NonNull); | |||
3832 | } | |||
3833 | ||||
3834 | /// Complains about missing nullability if the file containing \p pointerLoc | |||
3835 | /// has other uses of nullability (either the keywords or the \c assume_nonnull | |||
3836 | /// pragma). | |||
3837 | /// | |||
3838 | /// If the file has \e not seen other uses of nullability, this particular | |||
3839 | /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). | |||
3840 | static void | |||
3841 | checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, | |||
3842 | SourceLocation pointerLoc, | |||
3843 | SourceLocation pointerEndLoc = SourceLocation()) { | |||
3844 | // Determine which file we're performing consistency checking for. | |||
3845 | FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); | |||
3846 | if (file.isInvalid()) | |||
3847 | return; | |||
3848 | ||||
3849 | // If we haven't seen any type nullability in this file, we won't warn now | |||
3850 | // about anything. | |||
3851 | FileNullability &fileNullability = S.NullabilityMap[file]; | |||
3852 | if (!fileNullability.SawTypeNullability) { | |||
3853 | // If this is the first pointer declarator in the file, and the appropriate | |||
3854 | // warning is on, record it in case we need to diagnose it retroactively. | |||
3855 | diag::kind diagKind; | |||
3856 | if (pointerKind == SimplePointerKind::Array) | |||
3857 | diagKind = diag::warn_nullability_missing_array; | |||
3858 | else | |||
3859 | diagKind = diag::warn_nullability_missing; | |||
3860 | ||||
3861 | if (fileNullability.PointerLoc.isInvalid() && | |||
3862 | !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { | |||
3863 | fileNullability.PointerLoc = pointerLoc; | |||
3864 | fileNullability.PointerEndLoc = pointerEndLoc; | |||
3865 | fileNullability.PointerKind = static_cast<unsigned>(pointerKind); | |||
3866 | } | |||
3867 | ||||
3868 | return; | |||
3869 | } | |||
3870 | ||||
3871 | // Complain about missing nullability. | |||
3872 | emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); | |||
3873 | } | |||
3874 | ||||
3875 | /// Marks that a nullability feature has been used in the file containing | |||
3876 | /// \p loc. | |||
3877 | /// | |||
3878 | /// If this file already had pointer types in it that were missing nullability, | |||
3879 | /// the first such instance is retroactively diagnosed. | |||
3880 | /// | |||
3881 | /// \sa checkNullabilityConsistency | |||
3882 | static void recordNullabilitySeen(Sema &S, SourceLocation loc) { | |||
3883 | FileID file = getNullabilityCompletenessCheckFileID(S, loc); | |||
3884 | if (file.isInvalid()) | |||
3885 | return; | |||
3886 | ||||
3887 | FileNullability &fileNullability = S.NullabilityMap[file]; | |||
3888 | if (fileNullability.SawTypeNullability) | |||
3889 | return; | |||
3890 | fileNullability.SawTypeNullability = true; | |||
3891 | ||||
3892 | // If we haven't seen any type nullability before, now we have. Retroactively | |||
3893 | // diagnose the first unannotated pointer, if there was one. | |||
3894 | if (fileNullability.PointerLoc.isInvalid()) | |||
3895 | return; | |||
3896 | ||||
3897 | auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); | |||
3898 | emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, | |||
3899 | fileNullability.PointerEndLoc); | |||
3900 | } | |||
3901 | ||||
3902 | /// Returns true if any of the declarator chunks before \p endIndex include a | |||
3903 | /// level of indirection: array, pointer, reference, or pointer-to-member. | |||
3904 | /// | |||
3905 | /// Because declarator chunks are stored in outer-to-inner order, testing | |||
3906 | /// every chunk before \p endIndex is testing all chunks that embed the current | |||
3907 | /// chunk as part of their type. | |||
3908 | /// | |||
3909 | /// It is legal to pass the result of Declarator::getNumTypeObjects() as the | |||
3910 | /// end index, in which case all chunks are tested. | |||
3911 | static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { | |||
3912 | unsigned i = endIndex; | |||
3913 | while (i != 0) { | |||
3914 | // Walk outwards along the declarator chunks. | |||
3915 | --i; | |||
3916 | const DeclaratorChunk &DC = D.getTypeObject(i); | |||
3917 | switch (DC.Kind) { | |||
3918 | case DeclaratorChunk::Paren: | |||
3919 | break; | |||
3920 | case DeclaratorChunk::Array: | |||
3921 | case DeclaratorChunk::Pointer: | |||
3922 | case DeclaratorChunk::Reference: | |||
3923 | case DeclaratorChunk::MemberPointer: | |||
3924 | return true; | |||
3925 | case DeclaratorChunk::Function: | |||
3926 | case DeclaratorChunk::BlockPointer: | |||
3927 | case DeclaratorChunk::Pipe: | |||
3928 | // These are invalid anyway, so just ignore. | |||
3929 | break; | |||
3930 | } | |||
3931 | } | |||
3932 | return false; | |||
3933 | } | |||
3934 | ||||
3935 | static bool IsNoDerefableChunk(DeclaratorChunk Chunk) { | |||
3936 | return (Chunk.Kind == DeclaratorChunk::Pointer || | |||
3937 | Chunk.Kind == DeclaratorChunk::Array); | |||
3938 | } | |||
3939 | ||||
3940 | template<typename AttrT> | |||
3941 | static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &Attr) { | |||
3942 | Attr.setUsedAsTypeAttr(); | |||
3943 | return ::new (Ctx) | |||
3944 | AttrT(Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex()); | |||
3945 | } | |||
3946 | ||||
3947 | static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, | |||
3948 | NullabilityKind NK) { | |||
3949 | switch (NK) { | |||
3950 | case NullabilityKind::NonNull: | |||
3951 | return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); | |||
3952 | ||||
3953 | case NullabilityKind::Nullable: | |||
3954 | return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); | |||
3955 | ||||
3956 | case NullabilityKind::Unspecified: | |||
3957 | return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); | |||
3958 | } | |||
3959 | llvm_unreachable("unknown NullabilityKind")::llvm::llvm_unreachable_internal("unknown NullabilityKind", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 3959); | |||
3960 | } | |||
3961 | ||||
3962 | // Diagnose whether this is a case with the multiple addr spaces. | |||
3963 | // Returns true if this is an invalid case. | |||
3964 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified | |||
3965 | // by qualifiers for two or more different address spaces." | |||
3966 | static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, | |||
3967 | LangAS ASNew, | |||
3968 | SourceLocation AttrLoc) { | |||
3969 | if (ASOld != LangAS::Default) { | |||
3970 | if (ASOld != ASNew) { | |||
3971 | S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | |||
3972 | return true; | |||
3973 | } | |||
3974 | // Emit a warning if they are identical; it's likely unintended. | |||
3975 | S.Diag(AttrLoc, | |||
3976 | diag::warn_attribute_address_multiple_identical_qualifiers); | |||
3977 | } | |||
3978 | return false; | |||
3979 | } | |||
3980 | ||||
3981 | static TypeSourceInfo * | |||
3982 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, | |||
3983 | QualType T, TypeSourceInfo *ReturnTypeInfo); | |||
3984 | ||||
3985 | static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, | |||
3986 | QualType declSpecType, | |||
3987 | TypeSourceInfo *TInfo) { | |||
3988 | // The TypeSourceInfo that this function returns will not be a null type. | |||
3989 | // If there is an error, this function will fill in a dummy type as fallback. | |||
3990 | QualType T = declSpecType; | |||
3991 | Declarator &D = state.getDeclarator(); | |||
3992 | Sema &S = state.getSema(); | |||
3993 | ASTContext &Context = S.Context; | |||
3994 | const LangOptions &LangOpts = S.getLangOpts(); | |||
3995 | ||||
3996 | // The name we're declaring, if any. | |||
3997 | DeclarationName Name; | |||
3998 | if (D.getIdentifier()) | |||
3999 | Name = D.getIdentifier(); | |||
4000 | ||||
4001 | // Does this declaration declare a typedef-name? | |||
4002 | bool IsTypedefName = | |||
4003 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || | |||
4004 | D.getContext() == DeclaratorContext::AliasDeclContext || | |||
4005 | D.getContext() == DeclaratorContext::AliasTemplateContext; | |||
4006 | ||||
4007 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | |||
4008 | bool IsQualifiedFunction = T->isFunctionProtoType() && | |||
4009 | (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() || | |||
4010 | T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); | |||
4011 | ||||
4012 | // If T is 'decltype(auto)', the only declarators we can have are parens | |||
4013 | // and at most one function declarator if this is a function declaration. | |||
4014 | // If T is a deduced class template specialization type, we can have no | |||
4015 | // declarator chunks at all. | |||
4016 | if (auto *DT = T->getAs<DeducedType>()) { | |||
4017 | const AutoType *AT = T->getAs<AutoType>(); | |||
4018 | bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); | |||
4019 | if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { | |||
4020 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | |||
4021 | unsigned Index = E - I - 1; | |||
4022 | DeclaratorChunk &DeclChunk = D.getTypeObject(Index); | |||
4023 | unsigned DiagId = IsClassTemplateDeduction | |||
4024 | ? diag::err_deduced_class_template_compound_type | |||
4025 | : diag::err_decltype_auto_compound_type; | |||
4026 | unsigned DiagKind = 0; | |||
4027 | switch (DeclChunk.Kind) { | |||
4028 | case DeclaratorChunk::Paren: | |||
4029 | // FIXME: Rejecting this is a little silly. | |||
4030 | if (IsClassTemplateDeduction) { | |||
4031 | DiagKind = 4; | |||
4032 | break; | |||
4033 | } | |||
4034 | continue; | |||
4035 | case DeclaratorChunk::Function: { | |||
4036 | if (IsClassTemplateDeduction) { | |||
4037 | DiagKind = 3; | |||
4038 | break; | |||
4039 | } | |||
4040 | unsigned FnIndex; | |||
4041 | if (D.isFunctionDeclarationContext() && | |||
4042 | D.isFunctionDeclarator(FnIndex) && FnIndex == Index) | |||
4043 | continue; | |||
4044 | DiagId = diag::err_decltype_auto_function_declarator_not_declaration; | |||
4045 | break; | |||
4046 | } | |||
4047 | case DeclaratorChunk::Pointer: | |||
4048 | case DeclaratorChunk::BlockPointer: | |||
4049 | case DeclaratorChunk::MemberPointer: | |||
4050 | DiagKind = 0; | |||
4051 | break; | |||
4052 | case DeclaratorChunk::Reference: | |||
4053 | DiagKind = 1; | |||
4054 | break; | |||
4055 | case DeclaratorChunk::Array: | |||
4056 | DiagKind = 2; | |||
4057 | break; | |||
4058 | case DeclaratorChunk::Pipe: | |||
4059 | break; | |||
4060 | } | |||
4061 | ||||
4062 | S.Diag(DeclChunk.Loc, DiagId) << DiagKind; | |||
4063 | D.setInvalidType(true); | |||
4064 | break; | |||
4065 | } | |||
4066 | } | |||
4067 | } | |||
4068 | ||||
4069 | // Determine whether we should infer _Nonnull on pointer types. | |||
4070 | Optional<NullabilityKind> inferNullability; | |||
4071 | bool inferNullabilityCS = false; | |||
4072 | bool inferNullabilityInnerOnly = false; | |||
4073 | bool inferNullabilityInnerOnlyComplete = false; | |||
4074 | ||||
4075 | // Are we in an assume-nonnull region? | |||
4076 | bool inAssumeNonNullRegion = false; | |||
4077 | SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); | |||
4078 | if (assumeNonNullLoc.isValid()) { | |||
4079 | inAssumeNonNullRegion = true; | |||
4080 | recordNullabilitySeen(S, assumeNonNullLoc); | |||
4081 | } | |||
4082 | ||||
4083 | // Whether to complain about missing nullability specifiers or not. | |||
4084 | enum { | |||
4085 | /// Never complain. | |||
4086 | CAMN_No, | |||
4087 | /// Complain on the inner pointers (but not the outermost | |||
4088 | /// pointer). | |||
4089 | CAMN_InnerPointers, | |||
4090 | /// Complain about any pointers that don't have nullability | |||
4091 | /// specified or inferred. | |||
4092 | CAMN_Yes | |||
4093 | } complainAboutMissingNullability = CAMN_No; | |||
4094 | unsigned NumPointersRemaining = 0; | |||
4095 | auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; | |||
4096 | ||||
4097 | if (IsTypedefName) { | |||
4098 | // For typedefs, we do not infer any nullability (the default), | |||
4099 | // and we only complain about missing nullability specifiers on | |||
4100 | // inner pointers. | |||
4101 | complainAboutMissingNullability = CAMN_InnerPointers; | |||
4102 | ||||
4103 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | |||
4104 | !T->getNullability(S.Context)) { | |||
4105 | // Note that we allow but don't require nullability on dependent types. | |||
4106 | ++NumPointersRemaining; | |||
4107 | } | |||
4108 | ||||
4109 | for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { | |||
4110 | DeclaratorChunk &chunk = D.getTypeObject(i); | |||
4111 | switch (chunk.Kind) { | |||
4112 | case DeclaratorChunk::Array: | |||
4113 | case DeclaratorChunk::Function: | |||
4114 | case DeclaratorChunk::Pipe: | |||
4115 | break; | |||
4116 | ||||
4117 | case DeclaratorChunk::BlockPointer: | |||
4118 | case DeclaratorChunk::MemberPointer: | |||
4119 | ++NumPointersRemaining; | |||
4120 | break; | |||
4121 | ||||
4122 | case DeclaratorChunk::Paren: | |||
4123 | case DeclaratorChunk::Reference: | |||
4124 | continue; | |||
4125 | ||||
4126 | case DeclaratorChunk::Pointer: | |||
4127 | ++NumPointersRemaining; | |||
4128 | continue; | |||
4129 | } | |||
4130 | } | |||
4131 | } else { | |||
4132 | bool isFunctionOrMethod = false; | |||
4133 | switch (auto context = state.getDeclarator().getContext()) { | |||
4134 | case DeclaratorContext::ObjCParameterContext: | |||
4135 | case DeclaratorContext::ObjCResultContext: | |||
4136 | case DeclaratorContext::PrototypeContext: | |||
4137 | case DeclaratorContext::TrailingReturnContext: | |||
4138 | case DeclaratorContext::TrailingReturnVarContext: | |||
4139 | isFunctionOrMethod = true; | |||
4140 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
4141 | ||||
4142 | case DeclaratorContext::MemberContext: | |||
4143 | if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { | |||
4144 | complainAboutMissingNullability = CAMN_No; | |||
4145 | break; | |||
4146 | } | |||
4147 | ||||
4148 | // Weak properties are inferred to be nullable. | |||
4149 | if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { | |||
4150 | inferNullability = NullabilityKind::Nullable; | |||
4151 | break; | |||
4152 | } | |||
4153 | ||||
4154 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
4155 | ||||
4156 | case DeclaratorContext::FileContext: | |||
4157 | case DeclaratorContext::KNRTypeListContext: { | |||
4158 | complainAboutMissingNullability = CAMN_Yes; | |||
4159 | ||||
4160 | // Nullability inference depends on the type and declarator. | |||
4161 | auto wrappingKind = PointerWrappingDeclaratorKind::None; | |||
4162 | switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { | |||
4163 | case PointerDeclaratorKind::NonPointer: | |||
4164 | case PointerDeclaratorKind::MultiLevelPointer: | |||
4165 | // Cannot infer nullability. | |||
4166 | break; | |||
4167 | ||||
4168 | case PointerDeclaratorKind::SingleLevelPointer: | |||
4169 | // Infer _Nonnull if we are in an assumes-nonnull region. | |||
4170 | if (inAssumeNonNullRegion) { | |||
4171 | complainAboutInferringWithinChunk = wrappingKind; | |||
4172 | inferNullability = NullabilityKind::NonNull; | |||
4173 | inferNullabilityCS = | |||
4174 | (context == DeclaratorContext::ObjCParameterContext || | |||
4175 | context == DeclaratorContext::ObjCResultContext); | |||
4176 | } | |||
4177 | break; | |||
4178 | ||||
4179 | case PointerDeclaratorKind::CFErrorRefPointer: | |||
4180 | case PointerDeclaratorKind::NSErrorPointerPointer: | |||
4181 | // Within a function or method signature, infer _Nullable at both | |||
4182 | // levels. | |||
4183 | if (isFunctionOrMethod && inAssumeNonNullRegion) | |||
4184 | inferNullability = NullabilityKind::Nullable; | |||
4185 | break; | |||
4186 | ||||
4187 | case PointerDeclaratorKind::MaybePointerToCFRef: | |||
4188 | if (isFunctionOrMethod) { | |||
4189 | // On pointer-to-pointer parameters marked cf_returns_retained or | |||
4190 | // cf_returns_not_retained, if the outer pointer is explicit then | |||
4191 | // infer the inner pointer as _Nullable. | |||
4192 | auto hasCFReturnsAttr = | |||
4193 | [](const ParsedAttributesView &AttrList) -> bool { | |||
4194 | return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || | |||
4195 | AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); | |||
4196 | }; | |||
4197 | if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { | |||
4198 | if (hasCFReturnsAttr(D.getAttributes()) || | |||
4199 | hasCFReturnsAttr(InnermostChunk->getAttrs()) || | |||
4200 | hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { | |||
4201 | inferNullability = NullabilityKind::Nullable; | |||
4202 | inferNullabilityInnerOnly = true; | |||
4203 | } | |||
4204 | } | |||
4205 | } | |||
4206 | break; | |||
4207 | } | |||
4208 | break; | |||
4209 | } | |||
4210 | ||||
4211 | case DeclaratorContext::ConversionIdContext: | |||
4212 | complainAboutMissingNullability = CAMN_Yes; | |||
4213 | break; | |||
4214 | ||||
4215 | case DeclaratorContext::AliasDeclContext: | |||
4216 | case DeclaratorContext::AliasTemplateContext: | |||
4217 | case DeclaratorContext::BlockContext: | |||
4218 | case DeclaratorContext::BlockLiteralContext: | |||
4219 | case DeclaratorContext::ConditionContext: | |||
4220 | case DeclaratorContext::CXXCatchContext: | |||
4221 | case DeclaratorContext::CXXNewContext: | |||
4222 | case DeclaratorContext::ForContext: | |||
4223 | case DeclaratorContext::InitStmtContext: | |||
4224 | case DeclaratorContext::LambdaExprContext: | |||
4225 | case DeclaratorContext::LambdaExprParameterContext: | |||
4226 | case DeclaratorContext::ObjCCatchContext: | |||
4227 | case DeclaratorContext::TemplateParamContext: | |||
4228 | case DeclaratorContext::TemplateArgContext: | |||
4229 | case DeclaratorContext::TemplateTypeArgContext: | |||
4230 | case DeclaratorContext::TypeNameContext: | |||
4231 | case DeclaratorContext::FunctionalCastContext: | |||
4232 | // Don't infer in these contexts. | |||
4233 | break; | |||
4234 | } | |||
4235 | } | |||
4236 | ||||
4237 | // Local function that returns true if its argument looks like a va_list. | |||
4238 | auto isVaList = [&S](QualType T) -> bool { | |||
4239 | auto *typedefTy = T->getAs<TypedefType>(); | |||
4240 | if (!typedefTy) | |||
4241 | return false; | |||
4242 | TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); | |||
4243 | do { | |||
4244 | if (typedefTy->getDecl() == vaListTypedef) | |||
4245 | return true; | |||
4246 | if (auto *name = typedefTy->getDecl()->getIdentifier()) | |||
4247 | if (name->isStr("va_list")) | |||
4248 | return true; | |||
4249 | typedefTy = typedefTy->desugar()->getAs<TypedefType>(); | |||
4250 | } while (typedefTy); | |||
4251 | return false; | |||
4252 | }; | |||
4253 | ||||
4254 | // Local function that checks the nullability for a given pointer declarator. | |||
4255 | // Returns true if _Nonnull was inferred. | |||
4256 | auto inferPointerNullability = | |||
4257 | [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, | |||
4258 | SourceLocation pointerEndLoc, | |||
4259 | ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * { | |||
4260 | // We've seen a pointer. | |||
4261 | if (NumPointersRemaining > 0) | |||
4262 | --NumPointersRemaining; | |||
4263 | ||||
4264 | // If a nullability attribute is present, there's nothing to do. | |||
4265 | if (hasNullabilityAttr(attrs)) | |||
4266 | return nullptr; | |||
4267 | ||||
4268 | // If we're supposed to infer nullability, do so now. | |||
4269 | if (inferNullability && !inferNullabilityInnerOnlyComplete) { | |||
4270 | ParsedAttr::Syntax syntax = inferNullabilityCS | |||
4271 | ? ParsedAttr::AS_ContextSensitiveKeyword | |||
4272 | : ParsedAttr::AS_Keyword; | |||
4273 | ParsedAttr *nullabilityAttr = Pool.create( | |||
4274 | S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc), | |||
4275 | nullptr, SourceLocation(), nullptr, 0, syntax); | |||
4276 | ||||
4277 | attrs.addAtEnd(nullabilityAttr); | |||
4278 | ||||
4279 | if (inferNullabilityCS) { | |||
4280 | state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() | |||
4281 | ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); | |||
4282 | } | |||
4283 | ||||
4284 | if (pointerLoc.isValid() && | |||
4285 | complainAboutInferringWithinChunk != | |||
4286 | PointerWrappingDeclaratorKind::None) { | |||
4287 | auto Diag = | |||
4288 | S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); | |||
4289 | Diag << static_cast<int>(complainAboutInferringWithinChunk); | |||
4290 | fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); | |||
4291 | } | |||
4292 | ||||
4293 | if (inferNullabilityInnerOnly) | |||
4294 | inferNullabilityInnerOnlyComplete = true; | |||
4295 | return nullabilityAttr; | |||
4296 | } | |||
4297 | ||||
4298 | // If we're supposed to complain about missing nullability, do so | |||
4299 | // now if it's truly missing. | |||
4300 | switch (complainAboutMissingNullability) { | |||
4301 | case CAMN_No: | |||
4302 | break; | |||
4303 | ||||
4304 | case CAMN_InnerPointers: | |||
4305 | if (NumPointersRemaining == 0) | |||
4306 | break; | |||
4307 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
4308 | ||||
4309 | case CAMN_Yes: | |||
4310 | checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); | |||
4311 | } | |||
4312 | return nullptr; | |||
4313 | }; | |||
4314 | ||||
4315 | // If the type itself could have nullability but does not, infer pointer | |||
4316 | // nullability and perform consistency checking. | |||
4317 | if (S.CodeSynthesisContexts.empty()) { | |||
4318 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | |||
4319 | !T->getNullability(S.Context)) { | |||
4320 | if (isVaList(T)) { | |||
4321 | // Record that we've seen a pointer, but do nothing else. | |||
4322 | if (NumPointersRemaining > 0) | |||
4323 | --NumPointersRemaining; | |||
4324 | } else { | |||
4325 | SimplePointerKind pointerKind = SimplePointerKind::Pointer; | |||
4326 | if (T->isBlockPointerType()) | |||
4327 | pointerKind = SimplePointerKind::BlockPointer; | |||
4328 | else if (T->isMemberPointerType()) | |||
4329 | pointerKind = SimplePointerKind::MemberPointer; | |||
4330 | ||||
4331 | if (auto *attr = inferPointerNullability( | |||
4332 | pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), | |||
4333 | D.getDeclSpec().getEndLoc(), | |||
4334 | D.getMutableDeclSpec().getAttributes(), | |||
4335 | D.getMutableDeclSpec().getAttributePool())) { | |||
4336 | T = state.getAttributedType( | |||
4337 | createNullabilityAttr(Context, *attr, *inferNullability), T, T); | |||
4338 | } | |||
4339 | } | |||
4340 | } | |||
4341 | ||||
4342 | if (complainAboutMissingNullability == CAMN_Yes && | |||
4343 | T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && | |||
4344 | D.isPrototypeContext() && | |||
4345 | !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { | |||
4346 | checkNullabilityConsistency(S, SimplePointerKind::Array, | |||
4347 | D.getDeclSpec().getTypeSpecTypeLoc()); | |||
4348 | } | |||
4349 | } | |||
4350 | ||||
4351 | bool ExpectNoDerefChunk = | |||
4352 | state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); | |||
4353 | ||||
4354 | // Walk the DeclTypeInfo, building the recursive type as we go. | |||
4355 | // DeclTypeInfos are ordered from the identifier out, which is | |||
4356 | // opposite of what we want :). | |||
4357 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
4358 | unsigned chunkIndex = e - i - 1; | |||
4359 | state.setCurrentChunkIndex(chunkIndex); | |||
4360 | DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); | |||
4361 | IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; | |||
4362 | switch (DeclType.Kind) { | |||
4363 | case DeclaratorChunk::Paren: | |||
4364 | if (i == 0) | |||
4365 | warnAboutRedundantParens(S, D, T); | |||
4366 | T = S.BuildParenType(T); | |||
4367 | break; | |||
4368 | case DeclaratorChunk::BlockPointer: | |||
4369 | // If blocks are disabled, emit an error. | |||
4370 | if (!LangOpts.Blocks) | |||
4371 | S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; | |||
4372 | ||||
4373 | // Handle pointer nullability. | |||
4374 | inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, | |||
4375 | DeclType.EndLoc, DeclType.getAttrs(), | |||
4376 | state.getDeclarator().getAttributePool()); | |||
4377 | ||||
4378 | T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); | |||
4379 | if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { | |||
4380 | // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly | |||
4381 | // qualified with const. | |||
4382 | if (LangOpts.OpenCL) | |||
4383 | DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; | |||
4384 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); | |||
4385 | } | |||
4386 | break; | |||
4387 | case DeclaratorChunk::Pointer: | |||
4388 | // Verify that we're not building a pointer to pointer to function with | |||
4389 | // exception specification. | |||
4390 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4391 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4392 | D.setInvalidType(true); | |||
4393 | // Build the type anyway. | |||
4394 | } | |||
4395 | ||||
4396 | // Handle pointer nullability | |||
4397 | inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, | |||
4398 | DeclType.EndLoc, DeclType.getAttrs(), | |||
4399 | state.getDeclarator().getAttributePool()); | |||
4400 | ||||
4401 | if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { | |||
4402 | T = Context.getObjCObjectPointerType(T); | |||
4403 | if (DeclType.Ptr.TypeQuals) | |||
4404 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | |||
4405 | break; | |||
4406 | } | |||
4407 | ||||
4408 | // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. | |||
4409 | // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. | |||
4410 | // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. | |||
4411 | if (LangOpts.OpenCL) { | |||
4412 | if (T->isImageType() || T->isSamplerT() || T->isPipeType() || | |||
4413 | T->isBlockPointerType()) { | |||
4414 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; | |||
4415 | D.setInvalidType(true); | |||
4416 | } | |||
4417 | } | |||
4418 | ||||
4419 | T = S.BuildPointerType(T, DeclType.Loc, Name); | |||
4420 | if (DeclType.Ptr.TypeQuals) | |||
4421 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | |||
4422 | break; | |||
4423 | case DeclaratorChunk::Reference: { | |||
4424 | // Verify that we're not building a reference to pointer to function with | |||
4425 | // exception specification. | |||
4426 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4427 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4428 | D.setInvalidType(true); | |||
4429 | // Build the type anyway. | |||
4430 | } | |||
4431 | T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); | |||
4432 | ||||
4433 | if (DeclType.Ref.HasRestrict) | |||
4434 | T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); | |||
4435 | break; | |||
4436 | } | |||
4437 | case DeclaratorChunk::Array: { | |||
4438 | // Verify that we're not building an array of pointers to function with | |||
4439 | // exception specification. | |||
4440 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4441 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4442 | D.setInvalidType(true); | |||
4443 | // Build the type anyway. | |||
4444 | } | |||
4445 | DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; | |||
4446 | Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); | |||
4447 | ArrayType::ArraySizeModifier ASM; | |||
4448 | if (ATI.isStar) | |||
4449 | ASM = ArrayType::Star; | |||
4450 | else if (ATI.hasStatic) | |||
4451 | ASM = ArrayType::Static; | |||
4452 | else | |||
4453 | ASM = ArrayType::Normal; | |||
4454 | if (ASM == ArrayType::Star && !D.isPrototypeContext()) { | |||
4455 | // FIXME: This check isn't quite right: it allows star in prototypes | |||
4456 | // for function definitions, and disallows some edge cases detailed | |||
4457 | // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html | |||
4458 | S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); | |||
4459 | ASM = ArrayType::Normal; | |||
4460 | D.setInvalidType(true); | |||
4461 | } | |||
4462 | ||||
4463 | // C99 6.7.5.2p1: The optional type qualifiers and the keyword static | |||
4464 | // shall appear only in a declaration of a function parameter with an | |||
4465 | // array type, ... | |||
4466 | if (ASM == ArrayType::Static || ATI.TypeQuals) { | |||
4467 | if (!(D.isPrototypeContext() || | |||
4468 | D.getContext() == DeclaratorContext::KNRTypeListContext)) { | |||
4469 | S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << | |||
4470 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | |||
4471 | // Remove the 'static' and the type qualifiers. | |||
4472 | if (ASM == ArrayType::Static) | |||
4473 | ASM = ArrayType::Normal; | |||
4474 | ATI.TypeQuals = 0; | |||
4475 | D.setInvalidType(true); | |||
4476 | } | |||
4477 | ||||
4478 | // C99 6.7.5.2p1: ... and then only in the outermost array type | |||
4479 | // derivation. | |||
4480 | if (hasOuterPointerLikeChunk(D, chunkIndex)) { | |||
4481 | S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << | |||
4482 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | |||
4483 | if (ASM == ArrayType::Static) | |||
4484 | ASM = ArrayType::Normal; | |||
4485 | ATI.TypeQuals = 0; | |||
4486 | D.setInvalidType(true); | |||
4487 | } | |||
4488 | } | |||
4489 | const AutoType *AT = T->getContainedAutoType(); | |||
4490 | // Allow arrays of auto if we are a generic lambda parameter. | |||
4491 | // i.e. [](auto (&array)[5]) { return array[0]; }; OK | |||
4492 | if (AT && | |||
4493 | D.getContext() != DeclaratorContext::LambdaExprParameterContext) { | |||
4494 | // We've already diagnosed this for decltype(auto). | |||
4495 | if (!AT->isDecltypeAuto()) | |||
4496 | S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) | |||
4497 | << getPrintableNameForEntity(Name) << T; | |||
4498 | T = QualType(); | |||
4499 | break; | |||
4500 | } | |||
4501 | ||||
4502 | // Array parameters can be marked nullable as well, although it's not | |||
4503 | // necessary if they're marked 'static'. | |||
4504 | if (complainAboutMissingNullability == CAMN_Yes && | |||
4505 | !hasNullabilityAttr(DeclType.getAttrs()) && | |||
4506 | ASM != ArrayType::Static && | |||
4507 | D.isPrototypeContext() && | |||
4508 | !hasOuterPointerLikeChunk(D, chunkIndex)) { | |||
4509 | checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); | |||
4510 | } | |||
4511 | ||||
4512 | T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, | |||
4513 | SourceRange(DeclType.Loc, DeclType.EndLoc), Name); | |||
4514 | break; | |||
4515 | } | |||
4516 | case DeclaratorChunk::Function: { | |||
4517 | // If the function declarator has a prototype (i.e. it is not () and | |||
4518 | // does not have a K&R-style identifier list), then the arguments are part | |||
4519 | // of the type, otherwise the argument list is (). | |||
4520 | DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
4521 | IsQualifiedFunction = | |||
4522 | FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier(); | |||
4523 | ||||
4524 | // Check for auto functions and trailing return type and adjust the | |||
4525 | // return type accordingly. | |||
4526 | if (!D.isInvalidType()) { | |||
4527 | // trailing-return-type is only required if we're declaring a function, | |||
4528 | // and not, for instance, a pointer to a function. | |||
4529 | if (D.getDeclSpec().hasAutoTypeSpec() && | |||
4530 | !FTI.hasTrailingReturnType() && chunkIndex == 0) { | |||
4531 | if (!S.getLangOpts().CPlusPlus14) { | |||
4532 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
4533 | D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto | |||
4534 | ? diag::err_auto_missing_trailing_return | |||
4535 | : diag::err_deduced_return_type); | |||
4536 | T = Context.IntTy; | |||
4537 | D.setInvalidType(true); | |||
4538 | } else { | |||
4539 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
4540 | diag::warn_cxx11_compat_deduced_return_type); | |||
4541 | } | |||
4542 | } else if (FTI.hasTrailingReturnType()) { | |||
4543 | // T must be exactly 'auto' at this point. See CWG issue 681. | |||
4544 | if (isa<ParenType>(T)) { | |||
4545 | S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) | |||
4546 | << T << D.getSourceRange(); | |||
4547 | D.setInvalidType(true); | |||
4548 | } else if (D.getName().getKind() == | |||
4549 | UnqualifiedIdKind::IK_DeductionGuideName) { | |||
4550 | if (T != Context.DependentTy) { | |||
4551 | S.Diag(D.getDeclSpec().getBeginLoc(), | |||
4552 | diag::err_deduction_guide_with_complex_decl) | |||
4553 | << D.getSourceRange(); | |||
4554 | D.setInvalidType(true); | |||
4555 | } | |||
4556 | } else if (D.getContext() != DeclaratorContext::LambdaExprContext && | |||
4557 | (T.hasQualifiers() || !isa<AutoType>(T) || | |||
4558 | cast<AutoType>(T)->getKeyword() != | |||
4559 | AutoTypeKeyword::Auto)) { | |||
4560 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
4561 | diag::err_trailing_return_without_auto) | |||
4562 | << T << D.getDeclSpec().getSourceRange(); | |||
4563 | D.setInvalidType(true); | |||
4564 | } | |||
4565 | T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); | |||
4566 | if (T.isNull()) { | |||
4567 | // An error occurred parsing the trailing return type. | |||
4568 | T = Context.IntTy; | |||
4569 | D.setInvalidType(true); | |||
4570 | } | |||
4571 | } else { | |||
4572 | // This function type is not the type of the entity being declared, | |||
4573 | // so checking the 'auto' is not the responsibility of this chunk. | |||
4574 | } | |||
4575 | } | |||
4576 | ||||
4577 | // C99 6.7.5.3p1: The return type may not be a function or array type. | |||
4578 | // For conversion functions, we'll diagnose this particular error later. | |||
4579 | if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && | |||
4580 | (D.getName().getKind() != | |||
4581 | UnqualifiedIdKind::IK_ConversionFunctionId)) { | |||
4582 | unsigned diagID = diag::err_func_returning_array_function; | |||
4583 | // Last processing chunk in block context means this function chunk | |||
4584 | // represents the block. | |||
4585 | if (chunkIndex == 0 && | |||
4586 | D.getContext() == DeclaratorContext::BlockLiteralContext) | |||
4587 | diagID = diag::err_block_returning_array_function; | |||
4588 | S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; | |||
4589 | T = Context.IntTy; | |||
4590 | D.setInvalidType(true); | |||
4591 | } | |||
4592 | ||||
4593 | // Do not allow returning half FP value. | |||
4594 | // FIXME: This really should be in BuildFunctionType. | |||
4595 | if (T->isHalfType()) { | |||
4596 | if (S.getLangOpts().OpenCL) { | |||
4597 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { | |||
4598 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | |||
4599 | << T << 0 /*pointer hint*/; | |||
4600 | D.setInvalidType(true); | |||
4601 | } | |||
4602 | } else if (!S.getLangOpts().HalfArgsAndReturns) { | |||
4603 | S.Diag(D.getIdentifierLoc(), | |||
4604 | diag::err_parameters_retval_cannot_have_fp16_type) << 1; | |||
4605 | D.setInvalidType(true); | |||
4606 | } | |||
4607 | } | |||
4608 | ||||
4609 | if (LangOpts.OpenCL) { | |||
4610 | // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a | |||
4611 | // function. | |||
4612 | if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || | |||
4613 | T->isPipeType()) { | |||
4614 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | |||
4615 | << T << 1 /*hint off*/; | |||
4616 | D.setInvalidType(true); | |||
4617 | } | |||
4618 | // OpenCL doesn't support variadic functions and blocks | |||
4619 | // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. | |||
4620 | // We also allow here any toolchain reserved identifiers. | |||
4621 | if (FTI.isVariadic && | |||
4622 | !(D.getIdentifier() && | |||
4623 | ((D.getIdentifier()->getName() == "printf" && | |||
4624 | (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) || | |||
4625 | D.getIdentifier()->getName().startswith("__")))) { | |||
4626 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); | |||
4627 | D.setInvalidType(true); | |||
4628 | } | |||
4629 | } | |||
4630 | ||||
4631 | // Methods cannot return interface types. All ObjC objects are | |||
4632 | // passed by reference. | |||
4633 | if (T->isObjCObjectType()) { | |||
4634 | SourceLocation DiagLoc, FixitLoc; | |||
4635 | if (TInfo) { | |||
4636 | DiagLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
4637 | FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc()); | |||
4638 | } else { | |||
4639 | DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); | |||
4640 | FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc()); | |||
4641 | } | |||
4642 | S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) | |||
4643 | << 0 << T | |||
4644 | << FixItHint::CreateInsertion(FixitLoc, "*"); | |||
4645 | ||||
4646 | T = Context.getObjCObjectPointerType(T); | |||
4647 | if (TInfo) { | |||
4648 | TypeLocBuilder TLB; | |||
4649 | TLB.pushFullCopy(TInfo->getTypeLoc()); | |||
4650 | ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); | |||
4651 | TLoc.setStarLoc(FixitLoc); | |||
4652 | TInfo = TLB.getTypeSourceInfo(Context, T); | |||
4653 | } | |||
4654 | ||||
4655 | D.setInvalidType(true); | |||
4656 | } | |||
4657 | ||||
4658 | // cv-qualifiers on return types are pointless except when the type is a | |||
4659 | // class type in C++. | |||
4660 | if ((T.getCVRQualifiers() || T->isAtomicType()) && | |||
4661 | !(S.getLangOpts().CPlusPlus && | |||
4662 | (T->isDependentType() || T->isRecordType()))) { | |||
4663 | if (T->isVoidType() && !S.getLangOpts().CPlusPlus && | |||
4664 | D.getFunctionDefinitionKind() == FDK_Definition) { | |||
4665 | // [6.9.1/3] qualified void return is invalid on a C | |||
4666 | // function definition. Apparently ok on declarations and | |||
4667 | // in C++ though (!) | |||
4668 | S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; | |||
4669 | } else | |||
4670 | diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); | |||
4671 | } | |||
4672 | ||||
4673 | // Objective-C ARC ownership qualifiers are ignored on the function | |||
4674 | // return type (by type canonicalization). Complain if this attribute | |||
4675 | // was written here. | |||
4676 | if (T.getQualifiers().hasObjCLifetime()) { | |||
4677 | SourceLocation AttrLoc; | |||
4678 | if (chunkIndex + 1 < D.getNumTypeObjects()) { | |||
4679 | DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); | |||
4680 | for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { | |||
4681 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { | |||
4682 | AttrLoc = AL.getLoc(); | |||
4683 | break; | |||
4684 | } | |||
4685 | } | |||
4686 | } | |||
4687 | if (AttrLoc.isInvalid()) { | |||
4688 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | |||
4689 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { | |||
4690 | AttrLoc = AL.getLoc(); | |||
4691 | break; | |||
4692 | } | |||
4693 | } | |||
4694 | } | |||
4695 | ||||
4696 | if (AttrLoc.isValid()) { | |||
4697 | // The ownership attributes are almost always written via | |||
4698 | // the predefined | |||
4699 | // __strong/__weak/__autoreleasing/__unsafe_unretained. | |||
4700 | if (AttrLoc.isMacroID()) | |||
4701 | AttrLoc = | |||
4702 | S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); | |||
4703 | ||||
4704 | S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) | |||
4705 | << T.getQualifiers().getObjCLifetime(); | |||
4706 | } | |||
4707 | } | |||
4708 | ||||
4709 | if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { | |||
4710 | // C++ [dcl.fct]p6: | |||
4711 | // Types shall not be defined in return or parameter types. | |||
4712 | TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
4713 | S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) | |||
4714 | << Context.getTypeDeclType(Tag); | |||
4715 | } | |||
4716 | ||||
4717 | // Exception specs are not allowed in typedefs. Complain, but add it | |||
4718 | // anyway. | |||
4719 | if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) | |||
4720 | S.Diag(FTI.getExceptionSpecLocBeg(), | |||
4721 | diag::err_exception_spec_in_typedef) | |||
4722 | << (D.getContext() == DeclaratorContext::AliasDeclContext || | |||
4723 | D.getContext() == DeclaratorContext::AliasTemplateContext); | |||
4724 | ||||
4725 | // If we see "T var();" or "T var(T());" at block scope, it is probably | |||
4726 | // an attempt to initialize a variable, not a function declaration. | |||
4727 | if (FTI.isAmbiguous) | |||
4728 | warnAboutAmbiguousFunction(S, D, DeclType, T); | |||
4729 | ||||
4730 | FunctionType::ExtInfo EI( | |||
4731 | getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); | |||
4732 | ||||
4733 | if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus | |||
4734 | && !LangOpts.OpenCL) { | |||
4735 | // Simple void foo(), where the incoming T is the result type. | |||
4736 | T = Context.getFunctionNoProtoType(T, EI); | |||
4737 | } else { | |||
4738 | // We allow a zero-parameter variadic function in C if the | |||
4739 | // function is marked with the "overloadable" attribute. Scan | |||
4740 | // for this attribute now. | |||
4741 | if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) | |||
4742 | if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable)) | |||
4743 | S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); | |||
4744 | ||||
4745 | if (FTI.NumParams && FTI.Params[0].Param == nullptr) { | |||
4746 | // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function | |||
4747 | // definition. | |||
4748 | S.Diag(FTI.Params[0].IdentLoc, | |||
4749 | diag::err_ident_list_in_fn_declaration); | |||
4750 | D.setInvalidType(true); | |||
4751 | // Recover by creating a K&R-style function type. | |||
4752 | T = Context.getFunctionNoProtoType(T, EI); | |||
4753 | break; | |||
4754 | } | |||
4755 | ||||
4756 | FunctionProtoType::ExtProtoInfo EPI; | |||
4757 | EPI.ExtInfo = EI; | |||
4758 | EPI.Variadic = FTI.isVariadic; | |||
4759 | EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); | |||
4760 | EPI.TypeQuals.addCVRUQualifiers( | |||
4761 | FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() | |||
4762 | : 0); | |||
4763 | EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None | |||
4764 | : FTI.RefQualifierIsLValueRef? RQ_LValue | |||
4765 | : RQ_RValue; | |||
4766 | ||||
4767 | // Otherwise, we have a function with a parameter list that is | |||
4768 | // potentially variadic. | |||
4769 | SmallVector<QualType, 16> ParamTys; | |||
4770 | ParamTys.reserve(FTI.NumParams); | |||
4771 | ||||
4772 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> | |||
4773 | ExtParameterInfos(FTI.NumParams); | |||
4774 | bool HasAnyInterestingExtParameterInfos = false; | |||
4775 | ||||
4776 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | |||
4777 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
4778 | QualType ParamTy = Param->getType(); | |||
4779 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 4779, __PRETTY_FUNCTION__)); | |||
4780 | ||||
4781 | // Look for 'void'. void is allowed only as a single parameter to a | |||
4782 | // function with no other parameters (C99 6.7.5.3p10). We record | |||
4783 | // int(void) as a FunctionProtoType with an empty parameter list. | |||
4784 | if (ParamTy->isVoidType()) { | |||
4785 | // If this is something like 'float(int, void)', reject it. 'void' | |||
4786 | // is an incomplete type (C99 6.2.5p19) and function decls cannot | |||
4787 | // have parameters of incomplete type. | |||
4788 | if (FTI.NumParams != 1 || FTI.isVariadic) { | |||
4789 | S.Diag(DeclType.Loc, diag::err_void_only_param); | |||
4790 | ParamTy = Context.IntTy; | |||
4791 | Param->setType(ParamTy); | |||
4792 | } else if (FTI.Params[i].Ident) { | |||
4793 | // Reject, but continue to parse 'int(void abc)'. | |||
4794 | S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); | |||
4795 | ParamTy = Context.IntTy; | |||
4796 | Param->setType(ParamTy); | |||
4797 | } else { | |||
4798 | // Reject, but continue to parse 'float(const void)'. | |||
4799 | if (ParamTy.hasQualifiers()) | |||
4800 | S.Diag(DeclType.Loc, diag::err_void_param_qualified); | |||
4801 | ||||
4802 | // Do not add 'void' to the list. | |||
4803 | break; | |||
4804 | } | |||
4805 | } else if (ParamTy->isHalfType()) { | |||
4806 | // Disallow half FP parameters. | |||
4807 | // FIXME: This really should be in BuildFunctionType. | |||
4808 | if (S.getLangOpts().OpenCL) { | |||
4809 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { | |||
4810 | S.Diag(Param->getLocation(), | |||
4811 | diag::err_opencl_half_param) << ParamTy; | |||
4812 | D.setInvalidType(); | |||
4813 | Param->setInvalidDecl(); | |||
4814 | } | |||
4815 | } else if (!S.getLangOpts().HalfArgsAndReturns) { | |||
4816 | S.Diag(Param->getLocation(), | |||
4817 | diag::err_parameters_retval_cannot_have_fp16_type) << 0; | |||
4818 | D.setInvalidType(); | |||
4819 | } | |||
4820 | } else if (!FTI.hasPrototype) { | |||
4821 | if (ParamTy->isPromotableIntegerType()) { | |||
4822 | ParamTy = Context.getPromotedIntegerType(ParamTy); | |||
4823 | Param->setKNRPromoted(true); | |||
4824 | } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { | |||
4825 | if (BTy->getKind() == BuiltinType::Float) { | |||
4826 | ParamTy = Context.DoubleTy; | |||
4827 | Param->setKNRPromoted(true); | |||
4828 | } | |||
4829 | } | |||
4830 | } | |||
4831 | ||||
4832 | if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { | |||
4833 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); | |||
4834 | HasAnyInterestingExtParameterInfos = true; | |||
4835 | } | |||
4836 | ||||
4837 | if (auto attr = Param->getAttr<ParameterABIAttr>()) { | |||
4838 | ExtParameterInfos[i] = | |||
4839 | ExtParameterInfos[i].withABI(attr->getABI()); | |||
4840 | HasAnyInterestingExtParameterInfos = true; | |||
4841 | } | |||
4842 | ||||
4843 | if (Param->hasAttr<PassObjectSizeAttr>()) { | |||
4844 | ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); | |||
4845 | HasAnyInterestingExtParameterInfos = true; | |||
4846 | } | |||
4847 | ||||
4848 | if (Param->hasAttr<NoEscapeAttr>()) { | |||
4849 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); | |||
4850 | HasAnyInterestingExtParameterInfos = true; | |||
4851 | } | |||
4852 | ||||
4853 | ParamTys.push_back(ParamTy); | |||
4854 | } | |||
4855 | ||||
4856 | if (HasAnyInterestingExtParameterInfos) { | |||
4857 | EPI.ExtParameterInfos = ExtParameterInfos.data(); | |||
4858 | checkExtParameterInfos(S, ParamTys, EPI, | |||
4859 | [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); | |||
4860 | } | |||
4861 | ||||
4862 | SmallVector<QualType, 4> Exceptions; | |||
4863 | SmallVector<ParsedType, 2> DynamicExceptions; | |||
4864 | SmallVector<SourceRange, 2> DynamicExceptionRanges; | |||
4865 | Expr *NoexceptExpr = nullptr; | |||
4866 | ||||
4867 | if (FTI.getExceptionSpecType() == EST_Dynamic) { | |||
4868 | // FIXME: It's rather inefficient to have to split into two vectors | |||
4869 | // here. | |||
4870 | unsigned N = FTI.getNumExceptions(); | |||
4871 | DynamicExceptions.reserve(N); | |||
4872 | DynamicExceptionRanges.reserve(N); | |||
4873 | for (unsigned I = 0; I != N; ++I) { | |||
4874 | DynamicExceptions.push_back(FTI.Exceptions[I].Ty); | |||
4875 | DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); | |||
4876 | } | |||
4877 | } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { | |||
4878 | NoexceptExpr = FTI.NoexceptExpr; | |||
4879 | } | |||
4880 | ||||
4881 | S.checkExceptionSpecification(D.isFunctionDeclarationContext(), | |||
4882 | FTI.getExceptionSpecType(), | |||
4883 | DynamicExceptions, | |||
4884 | DynamicExceptionRanges, | |||
4885 | NoexceptExpr, | |||
4886 | Exceptions, | |||
4887 | EPI.ExceptionSpec); | |||
4888 | ||||
4889 | // FIXME: Set address space from attrs for C++ mode here. | |||
4890 | // OpenCLCPlusPlus: A class member function has an address space. | |||
4891 | auto IsClassMember = [&]() { | |||
4892 | return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && | |||
4893 | state.getDeclarator() | |||
4894 | .getCXXScopeSpec() | |||
4895 | .getScopeRep() | |||
4896 | ->getKind() == NestedNameSpecifier::TypeSpec) || | |||
4897 | state.getDeclarator().getContext() == | |||
4898 | DeclaratorContext::MemberContext; | |||
4899 | }; | |||
4900 | ||||
4901 | if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { | |||
4902 | LangAS ASIdx = LangAS::Default; | |||
4903 | // Take address space attr if any and mark as invalid to avoid adding | |||
4904 | // them later while creating QualType. | |||
4905 | if (FTI.MethodQualifiers) | |||
4906 | for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { | |||
4907 | LangAS ASIdxNew = attr.asOpenCLLangAS(); | |||
4908 | if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew, | |||
4909 | attr.getLoc())) | |||
4910 | D.setInvalidType(true); | |||
4911 | else | |||
4912 | ASIdx = ASIdxNew; | |||
4913 | } | |||
4914 | // If a class member function's address space is not set, set it to | |||
4915 | // __generic. | |||
4916 | LangAS AS = | |||
4917 | (ASIdx == LangAS::Default ? LangAS::opencl_generic : ASIdx); | |||
4918 | EPI.TypeQuals.addAddressSpace(AS); | |||
4919 | } | |||
4920 | T = Context.getFunctionType(T, ParamTys, EPI); | |||
4921 | } | |||
4922 | break; | |||
4923 | } | |||
4924 | case DeclaratorChunk::MemberPointer: { | |||
4925 | // The scope spec must refer to a class, or be dependent. | |||
4926 | CXXScopeSpec &SS = DeclType.Mem.Scope(); | |||
4927 | QualType ClsType; | |||
4928 | ||||
4929 | // Handle pointer nullability. | |||
4930 | inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, | |||
4931 | DeclType.EndLoc, DeclType.getAttrs(), | |||
4932 | state.getDeclarator().getAttributePool()); | |||
4933 | ||||
4934 | if (SS.isInvalid()) { | |||
4935 | // Avoid emitting extra errors if we already errored on the scope. | |||
4936 | D.setInvalidType(true); | |||
4937 | } else if (S.isDependentScopeSpecifier(SS) || | |||
4938 | dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { | |||
4939 | NestedNameSpecifier *NNS = SS.getScopeRep(); | |||
4940 | NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); | |||
4941 | switch (NNS->getKind()) { | |||
4942 | case NestedNameSpecifier::Identifier: | |||
4943 | ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, | |||
4944 | NNS->getAsIdentifier()); | |||
4945 | break; | |||
4946 | ||||
4947 | case NestedNameSpecifier::Namespace: | |||
4948 | case NestedNameSpecifier::NamespaceAlias: | |||
4949 | case NestedNameSpecifier::Global: | |||
4950 | case NestedNameSpecifier::Super: | |||
4951 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 4951); | |||
4952 | ||||
4953 | case NestedNameSpecifier::TypeSpec: | |||
4954 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
4955 | ClsType = QualType(NNS->getAsType(), 0); | |||
4956 | // Note: if the NNS has a prefix and ClsType is a nondependent | |||
4957 | // TemplateSpecializationType, then the NNS prefix is NOT included | |||
4958 | // in ClsType; hence we wrap ClsType into an ElaboratedType. | |||
4959 | // NOTE: in particular, no wrap occurs if ClsType already is an | |||
4960 | // Elaborated, DependentName, or DependentTemplateSpecialization. | |||
4961 | if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) | |||
4962 | ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); | |||
4963 | break; | |||
4964 | } | |||
4965 | } else { | |||
4966 | S.Diag(DeclType.Mem.Scope().getBeginLoc(), | |||
4967 | diag::err_illegal_decl_mempointer_in_nonclass) | |||
4968 | << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") | |||
4969 | << DeclType.Mem.Scope().getRange(); | |||
4970 | D.setInvalidType(true); | |||
4971 | } | |||
4972 | ||||
4973 | if (!ClsType.isNull()) | |||
4974 | T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, | |||
4975 | D.getIdentifier()); | |||
4976 | if (T.isNull()) { | |||
4977 | T = Context.IntTy; | |||
4978 | D.setInvalidType(true); | |||
4979 | } else if (DeclType.Mem.TypeQuals) { | |||
4980 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); | |||
4981 | } | |||
4982 | break; | |||
4983 | } | |||
4984 | ||||
4985 | case DeclaratorChunk::Pipe: { | |||
4986 | T = S.BuildReadPipeType(T, DeclType.Loc); | |||
4987 | processTypeAttrs(state, T, TAL_DeclSpec, | |||
4988 | D.getMutableDeclSpec().getAttributes()); | |||
4989 | break; | |||
4990 | } | |||
4991 | } | |||
4992 | ||||
4993 | if (T.isNull()) { | |||
4994 | D.setInvalidType(true); | |||
4995 | T = Context.IntTy; | |||
4996 | } | |||
4997 | ||||
4998 | // See if there are any attributes on this declarator chunk. | |||
4999 | processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs()); | |||
5000 | ||||
5001 | if (DeclType.Kind != DeclaratorChunk::Paren) { | |||
5002 | if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType)) | |||
5003 | S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); | |||
5004 | ||||
5005 | ExpectNoDerefChunk = state.didParseNoDeref(); | |||
5006 | } | |||
5007 | } | |||
5008 | ||||
5009 | if (ExpectNoDerefChunk) | |||
5010 | S.Diag(state.getDeclarator().getBeginLoc(), | |||
5011 | diag::warn_noderef_on_non_pointer_or_array); | |||
5012 | ||||
5013 | // GNU warning -Wstrict-prototypes | |||
5014 | // Warn if a function declaration is without a prototype. | |||
5015 | // This warning is issued for all kinds of unprototyped function | |||
5016 | // declarations (i.e. function type typedef, function pointer etc.) | |||
5017 | // C99 6.7.5.3p14: | |||
5018 | // The empty list in a function declarator that is not part of a definition | |||
5019 | // of that function specifies that no information about the number or types | |||
5020 | // of the parameters is supplied. | |||
5021 | if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) { | |||
5022 | bool IsBlock = false; | |||
5023 | for (const DeclaratorChunk &DeclType : D.type_objects()) { | |||
5024 | switch (DeclType.Kind) { | |||
5025 | case DeclaratorChunk::BlockPointer: | |||
5026 | IsBlock = true; | |||
5027 | break; | |||
5028 | case DeclaratorChunk::Function: { | |||
5029 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
5030 | // We supress the warning when there's no LParen location, as this | |||
5031 | // indicates the declaration was an implicit declaration, which gets | |||
5032 | // warned about separately via -Wimplicit-function-declaration. | |||
5033 | if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid()) | |||
5034 | S.Diag(DeclType.Loc, diag::warn_strict_prototypes) | |||
5035 | << IsBlock | |||
5036 | << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); | |||
5037 | IsBlock = false; | |||
5038 | break; | |||
5039 | } | |||
5040 | default: | |||
5041 | break; | |||
5042 | } | |||
5043 | } | |||
5044 | } | |||
5045 | ||||
5046 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5046, __PRETTY_FUNCTION__)); | |||
5047 | ||||
5048 | if (LangOpts.CPlusPlus && T->isFunctionType()) { | |||
5049 | const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); | |||
5050 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5050, __PRETTY_FUNCTION__)); | |||
5051 | ||||
5052 | // C++ 8.3.5p4: | |||
5053 | // A cv-qualifier-seq shall only be part of the function type | |||
5054 | // for a nonstatic member function, the function type to which a pointer | |||
5055 | // to member refers, or the top-level function type of a function typedef | |||
5056 | // declaration. | |||
5057 | // | |||
5058 | // Core issue 547 also allows cv-qualifiers on function types that are | |||
5059 | // top-level template type arguments. | |||
5060 | enum { NonMember, Member, DeductionGuide } Kind = NonMember; | |||
5061 | if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) | |||
5062 | Kind = DeductionGuide; | |||
5063 | else if (!D.getCXXScopeSpec().isSet()) { | |||
5064 | if ((D.getContext() == DeclaratorContext::MemberContext || | |||
5065 | D.getContext() == DeclaratorContext::LambdaExprContext) && | |||
5066 | !D.getDeclSpec().isFriendSpecified()) | |||
5067 | Kind = Member; | |||
5068 | } else { | |||
5069 | DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); | |||
5070 | if (!DC || DC->isRecord()) | |||
5071 | Kind = Member; | |||
5072 | } | |||
5073 | ||||
5074 | // C++11 [dcl.fct]p6 (w/DR1417): | |||
5075 | // An attempt to specify a function type with a cv-qualifier-seq or a | |||
5076 | // ref-qualifier (including by typedef-name) is ill-formed unless it is: | |||
5077 | // - the function type for a non-static member function, | |||
5078 | // - the function type to which a pointer to member refers, | |||
5079 | // - the top-level function type of a function typedef declaration or | |||
5080 | // alias-declaration, | |||
5081 | // - the type-id in the default argument of a type-parameter, or | |||
5082 | // - the type-id of a template-argument for a type-parameter | |||
5083 | // | |||
5084 | // FIXME: Checking this here is insufficient. We accept-invalid on: | |||
5085 | // | |||
5086 | // template<typename T> struct S { void f(T); }; | |||
5087 | // S<int() const> s; | |||
5088 | // | |||
5089 | // ... for instance. | |||
5090 | if (IsQualifiedFunction && | |||
5091 | !(Kind == Member && | |||
5092 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && | |||
5093 | !IsTypedefName && | |||
5094 | D.getContext() != DeclaratorContext::TemplateArgContext && | |||
5095 | D.getContext() != DeclaratorContext::TemplateTypeArgContext) { | |||
5096 | SourceLocation Loc = D.getBeginLoc(); | |||
5097 | SourceRange RemovalRange; | |||
5098 | unsigned I; | |||
5099 | if (D.isFunctionDeclarator(I)) { | |||
5100 | SmallVector<SourceLocation, 4> RemovalLocs; | |||
5101 | const DeclaratorChunk &Chunk = D.getTypeObject(I); | |||
5102 | assert(Chunk.Kind == DeclaratorChunk::Function)((Chunk.Kind == DeclaratorChunk::Function) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5102, __PRETTY_FUNCTION__)); | |||
5103 | ||||
5104 | if (Chunk.Fun.hasRefQualifier()) | |||
5105 | RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); | |||
5106 | ||||
5107 | if (Chunk.Fun.hasMethodTypeQualifiers()) | |||
5108 | Chunk.Fun.MethodQualifiers->forEachQualifier( | |||
5109 | [&](DeclSpec::TQ TypeQual, StringRef QualName, | |||
5110 | SourceLocation SL) { RemovalLocs.push_back(SL); }); | |||
5111 | ||||
5112 | if (!RemovalLocs.empty()) { | |||
5113 | llvm::sort(RemovalLocs, | |||
5114 | BeforeThanCompare<SourceLocation>(S.getSourceManager())); | |||
5115 | RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); | |||
5116 | Loc = RemovalLocs.front(); | |||
5117 | } | |||
5118 | } | |||
5119 | ||||
5120 | S.Diag(Loc, diag::err_invalid_qualified_function_type) | |||
5121 | << Kind << D.isFunctionDeclarator() << T | |||
5122 | << getFunctionQualifiersAsString(FnTy) | |||
5123 | << FixItHint::CreateRemoval(RemovalRange); | |||
5124 | ||||
5125 | // Strip the cv-qualifiers and ref-qualifiers from the type. | |||
5126 | FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); | |||
5127 | EPI.TypeQuals.removeCVRQualifiers(); | |||
5128 | EPI.RefQualifier = RQ_None; | |||
5129 | ||||
5130 | T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), | |||
5131 | EPI); | |||
5132 | // Rebuild any parens around the identifier in the function type. | |||
5133 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
5134 | if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) | |||
5135 | break; | |||
5136 | T = S.BuildParenType(T); | |||
5137 | } | |||
5138 | } | |||
5139 | } | |||
5140 | ||||
5141 | // Apply any undistributed attributes from the declarator. | |||
5142 | processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); | |||
5143 | ||||
5144 | // Diagnose any ignored type attributes. | |||
5145 | state.diagnoseIgnoredTypeAttrs(T); | |||
5146 | ||||
5147 | // C++0x [dcl.constexpr]p9: | |||
5148 | // A constexpr specifier used in an object declaration declares the object | |||
5149 | // as const. | |||
5150 | if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { | |||
5151 | T.addConst(); | |||
5152 | } | |||
5153 | ||||
5154 | // If there was an ellipsis in the declarator, the declaration declares a | |||
5155 | // parameter pack whose type may be a pack expansion type. | |||
5156 | if (D.hasEllipsis()) { | |||
5157 | // C++0x [dcl.fct]p13: | |||
5158 | // A declarator-id or abstract-declarator containing an ellipsis shall | |||
5159 | // only be used in a parameter-declaration. Such a parameter-declaration | |||
5160 | // is a parameter pack (14.5.3). [...] | |||
5161 | switch (D.getContext()) { | |||
5162 | case DeclaratorContext::PrototypeContext: | |||
5163 | case DeclaratorContext::LambdaExprParameterContext: | |||
5164 | // C++0x [dcl.fct]p13: | |||
5165 | // [...] When it is part of a parameter-declaration-clause, the | |||
5166 | // parameter pack is a function parameter pack (14.5.3). The type T | |||
5167 | // of the declarator-id of the function parameter pack shall contain | |||
5168 | // a template parameter pack; each template parameter pack in T is | |||
5169 | // expanded by the function parameter pack. | |||
5170 | // | |||
5171 | // We represent function parameter packs as function parameters whose | |||
5172 | // type is a pack expansion. | |||
5173 | if (!T->containsUnexpandedParameterPack()) { | |||
5174 | S.Diag(D.getEllipsisLoc(), | |||
5175 | diag::err_function_parameter_pack_without_parameter_packs) | |||
5176 | << T << D.getSourceRange(); | |||
5177 | D.setEllipsisLoc(SourceLocation()); | |||
5178 | } else { | |||
5179 | T = Context.getPackExpansionType(T, None); | |||
5180 | } | |||
5181 | break; | |||
5182 | case DeclaratorContext::TemplateParamContext: | |||
5183 | // C++0x [temp.param]p15: | |||
5184 | // If a template-parameter is a [...] is a parameter-declaration that | |||
5185 | // declares a parameter pack (8.3.5), then the template-parameter is a | |||
5186 | // template parameter pack (14.5.3). | |||
5187 | // | |||
5188 | // Note: core issue 778 clarifies that, if there are any unexpanded | |||
5189 | // parameter packs in the type of the non-type template parameter, then | |||
5190 | // it expands those parameter packs. | |||
5191 | if (T->containsUnexpandedParameterPack()) | |||
5192 | T = Context.getPackExpansionType(T, None); | |||
5193 | else | |||
5194 | S.Diag(D.getEllipsisLoc(), | |||
5195 | LangOpts.CPlusPlus11 | |||
5196 | ? diag::warn_cxx98_compat_variadic_templates | |||
5197 | : diag::ext_variadic_templates); | |||
5198 | break; | |||
5199 | ||||
5200 | case DeclaratorContext::FileContext: | |||
5201 | case DeclaratorContext::KNRTypeListContext: | |||
5202 | case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic | |||
5203 | // here? | |||
5204 | case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic | |||
5205 | // here? | |||
5206 | case DeclaratorContext::TypeNameContext: | |||
5207 | case DeclaratorContext::FunctionalCastContext: | |||
5208 | case DeclaratorContext::CXXNewContext: | |||
5209 | case DeclaratorContext::AliasDeclContext: | |||
5210 | case DeclaratorContext::AliasTemplateContext: | |||
5211 | case DeclaratorContext::MemberContext: | |||
5212 | case DeclaratorContext::BlockContext: | |||
5213 | case DeclaratorContext::ForContext: | |||
5214 | case DeclaratorContext::InitStmtContext: | |||
5215 | case DeclaratorContext::ConditionContext: | |||
5216 | case DeclaratorContext::CXXCatchContext: | |||
5217 | case DeclaratorContext::ObjCCatchContext: | |||
5218 | case DeclaratorContext::BlockLiteralContext: | |||
5219 | case DeclaratorContext::LambdaExprContext: | |||
5220 | case DeclaratorContext::ConversionIdContext: | |||
5221 | case DeclaratorContext::TrailingReturnContext: | |||
5222 | case DeclaratorContext::TrailingReturnVarContext: | |||
5223 | case DeclaratorContext::TemplateArgContext: | |||
5224 | case DeclaratorContext::TemplateTypeArgContext: | |||
5225 | // FIXME: We may want to allow parameter packs in block-literal contexts | |||
5226 | // in the future. | |||
5227 | S.Diag(D.getEllipsisLoc(), | |||
5228 | diag::err_ellipsis_in_declarator_not_parameter); | |||
5229 | D.setEllipsisLoc(SourceLocation()); | |||
5230 | break; | |||
5231 | } | |||
5232 | } | |||
5233 | ||||
5234 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5234, __PRETTY_FUNCTION__)); | |||
5235 | if (D.isInvalidType()) | |||
5236 | return Context.getTrivialTypeSourceInfo(T); | |||
5237 | ||||
5238 | return GetTypeSourceInfoForDeclarator(state, T, TInfo); | |||
5239 | } | |||
5240 | ||||
5241 | /// GetTypeForDeclarator - Convert the type for the specified | |||
5242 | /// declarator to Type instances. | |||
5243 | /// | |||
5244 | /// The result of this call will never be null, but the associated | |||
5245 | /// type may be a null type if there's an unrecoverable error. | |||
5246 | TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { | |||
5247 | // Determine the type of the declarator. Not all forms of declarator | |||
5248 | // have a type. | |||
5249 | ||||
5250 | TypeProcessingState state(*this, D); | |||
5251 | ||||
5252 | TypeSourceInfo *ReturnTypeInfo = nullptr; | |||
5253 | QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | |||
5254 | if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) | |||
5255 | inferARCWriteback(state, T); | |||
5256 | ||||
5257 | return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); | |||
5258 | } | |||
5259 | ||||
5260 | static void transferARCOwnershipToDeclSpec(Sema &S, | |||
5261 | QualType &declSpecTy, | |||
5262 | Qualifiers::ObjCLifetime ownership) { | |||
5263 | if (declSpecTy->isObjCRetainableType() && | |||
5264 | declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { | |||
5265 | Qualifiers qs; | |||
5266 | qs.addObjCLifetime(ownership); | |||
5267 | declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); | |||
5268 | } | |||
5269 | } | |||
5270 | ||||
5271 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | |||
5272 | Qualifiers::ObjCLifetime ownership, | |||
5273 | unsigned chunkIndex) { | |||
5274 | Sema &S = state.getSema(); | |||
5275 | Declarator &D = state.getDeclarator(); | |||
5276 | ||||
5277 | // Look for an explicit lifetime attribute. | |||
5278 | DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); | |||
5279 | if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) | |||
5280 | return; | |||
5281 | ||||
5282 | const char *attrStr = nullptr; | |||
5283 | switch (ownership) { | |||
5284 | case Qualifiers::OCL_None: llvm_unreachable("no ownership!")::llvm::llvm_unreachable_internal("no ownership!", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5284); | |||
5285 | case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; | |||
5286 | case Qualifiers::OCL_Strong: attrStr = "strong"; break; | |||
5287 | case Qualifiers::OCL_Weak: attrStr = "weak"; break; | |||
5288 | case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; | |||
5289 | } | |||
5290 | ||||
5291 | IdentifierLoc *Arg = new (S.Context) IdentifierLoc; | |||
5292 | Arg->Ident = &S.Context.Idents.get(attrStr); | |||
5293 | Arg->Loc = SourceLocation(); | |||
5294 | ||||
5295 | ArgsUnion Args(Arg); | |||
5296 | ||||
5297 | // If there wasn't one, add one (with an invalid source location | |||
5298 | // so that we don't make an AttributedType for it). | |||
5299 | ParsedAttr *attr = D.getAttributePool().create( | |||
5300 | &S.Context.Idents.get("objc_ownership"), SourceLocation(), | |||
5301 | /*scope*/ nullptr, SourceLocation(), | |||
5302 | /*args*/ &Args, 1, ParsedAttr::AS_GNU); | |||
5303 | chunk.getAttrs().addAtEnd(attr); | |||
5304 | // TODO: mark whether we did this inference? | |||
5305 | } | |||
5306 | ||||
5307 | /// Used for transferring ownership in casts resulting in l-values. | |||
5308 | static void transferARCOwnership(TypeProcessingState &state, | |||
5309 | QualType &declSpecTy, | |||
5310 | Qualifiers::ObjCLifetime ownership) { | |||
5311 | Sema &S = state.getSema(); | |||
5312 | Declarator &D = state.getDeclarator(); | |||
5313 | ||||
5314 | int inner = -1; | |||
5315 | bool hasIndirection = false; | |||
5316 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
5317 | DeclaratorChunk &chunk = D.getTypeObject(i); | |||
5318 | switch (chunk.Kind) { | |||
5319 | case DeclaratorChunk::Paren: | |||
5320 | // Ignore parens. | |||
5321 | break; | |||
5322 | ||||
5323 | case DeclaratorChunk::Array: | |||
5324 | case DeclaratorChunk::Reference: | |||
5325 | case DeclaratorChunk::Pointer: | |||
5326 | if (inner != -1) | |||
5327 | hasIndirection = true; | |||
5328 | inner = i; | |||
5329 | break; | |||
5330 | ||||
5331 | case DeclaratorChunk::BlockPointer: | |||
5332 | if (inner != -1) | |||
5333 | transferARCOwnershipToDeclaratorChunk(state, ownership, i); | |||
5334 | return; | |||
5335 | ||||
5336 | case DeclaratorChunk::Function: | |||
5337 | case DeclaratorChunk::MemberPointer: | |||
5338 | case DeclaratorChunk::Pipe: | |||
5339 | return; | |||
5340 | } | |||
5341 | } | |||
5342 | ||||
5343 | if (inner == -1) | |||
5344 | return; | |||
5345 | ||||
5346 | DeclaratorChunk &chunk = D.getTypeObject(inner); | |||
5347 | if (chunk.Kind == DeclaratorChunk::Pointer) { | |||
5348 | if (declSpecTy->isObjCRetainableType()) | |||
5349 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | |||
5350 | if (declSpecTy->isObjCObjectType() && hasIndirection) | |||
5351 | return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); | |||
5352 | } else { | |||
5353 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5354, __PRETTY_FUNCTION__)) | |||
5354 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5354, __PRETTY_FUNCTION__)); | |||
5355 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | |||
5356 | } | |||
5357 | } | |||
5358 | ||||
5359 | TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { | |||
5360 | TypeProcessingState state(*this, D); | |||
5361 | ||||
5362 | TypeSourceInfo *ReturnTypeInfo = nullptr; | |||
5363 | QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | |||
5364 | ||||
5365 | if (getLangOpts().ObjC) { | |||
5366 | Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); | |||
5367 | if (ownership != Qualifiers::OCL_None) | |||
5368 | transferARCOwnership(state, declSpecTy, ownership); | |||
5369 | } | |||
5370 | ||||
5371 | return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); | |||
5372 | } | |||
5373 | ||||
5374 | static void fillAttributedTypeLoc(AttributedTypeLoc TL, | |||
5375 | TypeProcessingState &State) { | |||
5376 | TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); | |||
5377 | } | |||
5378 | ||||
5379 | namespace { | |||
5380 | class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { | |||
5381 | ASTContext &Context; | |||
5382 | TypeProcessingState &State; | |||
5383 | const DeclSpec &DS; | |||
5384 | ||||
5385 | public: | |||
5386 | TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State, | |||
5387 | const DeclSpec &DS) | |||
5388 | : Context(Context), State(State), DS(DS) {} | |||
5389 | ||||
5390 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | |||
5391 | Visit(TL.getModifiedLoc()); | |||
5392 | fillAttributedTypeLoc(TL, State); | |||
5393 | } | |||
5394 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { | |||
5395 | Visit(TL.getInnerLoc()); | |||
5396 | TL.setExpansionLoc( | |||
5397 | State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); | |||
5398 | } | |||
5399 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | |||
5400 | Visit(TL.getUnqualifiedLoc()); | |||
5401 | } | |||
5402 | void VisitTypedefTypeLoc(TypedefTypeLoc TL) { | |||
5403 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
5404 | } | |||
5405 | void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { | |||
5406 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
5407 | // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires | |||
5408 | // addition field. What we have is good enough for dispay of location | |||
5409 | // of 'fixit' on interface name. | |||
5410 | TL.setNameEndLoc(DS.getEndLoc()); | |||
5411 | } | |||
5412 | void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { | |||
5413 | TypeSourceInfo *RepTInfo = nullptr; | |||
5414 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | |||
5415 | TL.copy(RepTInfo->getTypeLoc()); | |||
5416 | } | |||
5417 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | |||
5418 | TypeSourceInfo *RepTInfo = nullptr; | |||
5419 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | |||
5420 | TL.copy(RepTInfo->getTypeLoc()); | |||
5421 | } | |||
5422 | void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { | |||
5423 | TypeSourceInfo *TInfo = nullptr; | |||
5424 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5425 | ||||
5426 | // If we got no declarator info from previous Sema routines, | |||
5427 | // just fill with the typespec loc. | |||
5428 | if (!TInfo) { | |||
5429 | TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); | |||
5430 | return; | |||
5431 | } | |||
5432 | ||||
5433 | TypeLoc OldTL = TInfo->getTypeLoc(); | |||
5434 | if (TInfo->getType()->getAs<ElaboratedType>()) { | |||
5435 | ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); | |||
5436 | TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() | |||
5437 | .castAs<TemplateSpecializationTypeLoc>(); | |||
5438 | TL.copy(NamedTL); | |||
5439 | } else { | |||
5440 | TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); | |||
5441 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5441, __PRETTY_FUNCTION__)); | |||
5442 | } | |||
5443 | ||||
5444 | } | |||
5445 | void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { | |||
5446 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5446, __PRETTY_FUNCTION__)); | |||
5447 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | |||
5448 | TL.setParensRange(DS.getTypeofParensRange()); | |||
5449 | } | |||
5450 | void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { | |||
5451 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5451, __PRETTY_FUNCTION__)); | |||
5452 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | |||
5453 | TL.setParensRange(DS.getTypeofParensRange()); | |||
5454 | assert(DS.getRepAsType())((DS.getRepAsType()) ? static_cast<void> (0) : __assert_fail ("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5454, __PRETTY_FUNCTION__)); | |||
5455 | TypeSourceInfo *TInfo = nullptr; | |||
5456 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5457 | TL.setUnderlyingTInfo(TInfo); | |||
5458 | } | |||
5459 | void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { | |||
5460 | // FIXME: This holds only because we only have one unary transform. | |||
5461 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5461, __PRETTY_FUNCTION__)); | |||
5462 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
5463 | TL.setParensRange(DS.getTypeofParensRange()); | |||
5464 | assert(DS.getRepAsType())((DS.getRepAsType()) ? static_cast<void> (0) : __assert_fail ("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5464, __PRETTY_FUNCTION__)); | |||
5465 | TypeSourceInfo *TInfo = nullptr; | |||
5466 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5467 | TL.setUnderlyingTInfo(TInfo); | |||
5468 | } | |||
5469 | void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { | |||
5470 | // By default, use the source location of the type specifier. | |||
5471 | TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); | |||
5472 | if (TL.needsExtraLocalData()) { | |||
5473 | // Set info for the written builtin specifiers. | |||
5474 | TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); | |||
5475 | // Try to have a meaningful source location. | |||
5476 | if (TL.getWrittenSignSpec() != TSS_unspecified) | |||
5477 | TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); | |||
5478 | if (TL.getWrittenWidthSpec() != TSW_unspecified) | |||
5479 | TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); | |||
5480 | } | |||
5481 | } | |||
5482 | void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { | |||
5483 | ElaboratedTypeKeyword Keyword | |||
5484 | = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); | |||
5485 | if (DS.getTypeSpecType() == TST_typename) { | |||
5486 | TypeSourceInfo *TInfo = nullptr; | |||
5487 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5488 | if (TInfo) { | |||
5489 | TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); | |||
5490 | return; | |||
5491 | } | |||
5492 | } | |||
5493 | TL.setElaboratedKeywordLoc(Keyword != ETK_None | |||
5494 | ? DS.getTypeSpecTypeLoc() | |||
5495 | : SourceLocation()); | |||
5496 | const CXXScopeSpec& SS = DS.getTypeSpecScope(); | |||
5497 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
5498 | Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); | |||
5499 | } | |||
5500 | void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { | |||
5501 | assert(DS.getTypeSpecType() == TST_typename)((DS.getTypeSpecType() == TST_typename) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5501, __PRETTY_FUNCTION__)); | |||
5502 | TypeSourceInfo *TInfo = nullptr; | |||
5503 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5504 | assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5504, __PRETTY_FUNCTION__)); | |||
5505 | TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); | |||
5506 | } | |||
5507 | void VisitDependentTemplateSpecializationTypeLoc( | |||
5508 | DependentTemplateSpecializationTypeLoc TL) { | |||
5509 | assert(DS.getTypeSpecType() == TST_typename)((DS.getTypeSpecType() == TST_typename) ? static_cast<void > (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5509, __PRETTY_FUNCTION__)); | |||
5510 | TypeSourceInfo *TInfo = nullptr; | |||
5511 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5512 | assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5512, __PRETTY_FUNCTION__)); | |||
5513 | TL.copy( | |||
5514 | TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); | |||
5515 | } | |||
5516 | void VisitTagTypeLoc(TagTypeLoc TL) { | |||
5517 | TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); | |||
5518 | } | |||
5519 | void VisitAtomicTypeLoc(AtomicTypeLoc TL) { | |||
5520 | // An AtomicTypeLoc can come from either an _Atomic(...) type specifier | |||
5521 | // or an _Atomic qualifier. | |||
5522 | if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { | |||
5523 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
5524 | TL.setParensRange(DS.getTypeofParensRange()); | |||
5525 | ||||
5526 | TypeSourceInfo *TInfo = nullptr; | |||
5527 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5528 | assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5528, __PRETTY_FUNCTION__)); | |||
5529 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | |||
5530 | } else { | |||
5531 | TL.setKWLoc(DS.getAtomicSpecLoc()); | |||
5532 | // No parens, to indicate this was spelled as an _Atomic qualifier. | |||
5533 | TL.setParensRange(SourceRange()); | |||
5534 | Visit(TL.getValueLoc()); | |||
5535 | } | |||
5536 | } | |||
5537 | ||||
5538 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | |||
5539 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
5540 | ||||
5541 | TypeSourceInfo *TInfo = nullptr; | |||
5542 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5543 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | |||
5544 | } | |||
5545 | ||||
5546 | void VisitTypeLoc(TypeLoc TL) { | |||
5547 | // FIXME: add other typespec types and change this to an assert. | |||
5548 | TL.initialize(Context, DS.getTypeSpecTypeLoc()); | |||
5549 | } | |||
5550 | }; | |||
5551 | ||||
5552 | class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { | |||
5553 | ASTContext &Context; | |||
5554 | TypeProcessingState &State; | |||
5555 | const DeclaratorChunk &Chunk; | |||
5556 | ||||
5557 | public: | |||
5558 | DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, | |||
5559 | const DeclaratorChunk &Chunk) | |||
5560 | : Context(Context), State(State), Chunk(Chunk) {} | |||
5561 | ||||
5562 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | |||
5563 | llvm_unreachable("qualified type locs not expected here!")::llvm::llvm_unreachable_internal("qualified type locs not expected here!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5563); | |||
5564 | } | |||
5565 | void VisitDecayedTypeLoc(DecayedTypeLoc TL) { | |||
5566 | llvm_unreachable("decayed type locs not expected here!")::llvm::llvm_unreachable_internal("decayed type locs not expected here!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5566); | |||
5567 | } | |||
5568 | ||||
5569 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | |||
5570 | fillAttributedTypeLoc(TL, State); | |||
5571 | } | |||
5572 | void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { | |||
5573 | // nothing | |||
5574 | } | |||
5575 | void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { | |||
5576 | assert(Chunk.Kind == DeclaratorChunk::BlockPointer)((Chunk.Kind == DeclaratorChunk::BlockPointer) ? static_cast< void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::BlockPointer" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5576, __PRETTY_FUNCTION__)); | |||
5577 | TL.setCaretLoc(Chunk.Loc); | |||
5578 | } | |||
5579 | void VisitPointerTypeLoc(PointerTypeLoc TL) { | |||
5580 | assert(Chunk.Kind == DeclaratorChunk::Pointer)((Chunk.Kind == DeclaratorChunk::Pointer) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5580, __PRETTY_FUNCTION__)); | |||
5581 | TL.setStarLoc(Chunk.Loc); | |||
5582 | } | |||
5583 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | |||
5584 | assert(Chunk.Kind == DeclaratorChunk::Pointer)((Chunk.Kind == DeclaratorChunk::Pointer) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5584, __PRETTY_FUNCTION__)); | |||
5585 | TL.setStarLoc(Chunk.Loc); | |||
5586 | } | |||
5587 | void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { | |||
5588 | assert(Chunk.Kind == DeclaratorChunk::MemberPointer)((Chunk.Kind == DeclaratorChunk::MemberPointer) ? static_cast <void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::MemberPointer" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5588, __PRETTY_FUNCTION__)); | |||
5589 | const CXXScopeSpec& SS = Chunk.Mem.Scope(); | |||
5590 | NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); | |||
5591 | ||||
5592 | const Type* ClsTy = TL.getClass(); | |||
5593 | QualType ClsQT = QualType(ClsTy, 0); | |||
5594 | TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); | |||
5595 | // Now copy source location info into the type loc component. | |||
5596 | TypeLoc ClsTL = ClsTInfo->getTypeLoc(); | |||
5597 | switch (NNSLoc.getNestedNameSpecifier()->getKind()) { | |||
5598 | case NestedNameSpecifier::Identifier: | |||
5599 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5599, __PRETTY_FUNCTION__)); | |||
5600 | { | |||
5601 | DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); | |||
5602 | DNTLoc.setElaboratedKeywordLoc(SourceLocation()); | |||
5603 | DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); | |||
5604 | DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); | |||
5605 | } | |||
5606 | break; | |||
5607 | ||||
5608 | case NestedNameSpecifier::TypeSpec: | |||
5609 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
5610 | if (isa<ElaboratedType>(ClsTy)) { | |||
5611 | ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); | |||
5612 | ETLoc.setElaboratedKeywordLoc(SourceLocation()); | |||
5613 | ETLoc.setQualifierLoc(NNSLoc.getPrefix()); | |||
5614 | TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); | |||
5615 | NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); | |||
5616 | } else { | |||
5617 | ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); | |||
5618 | } | |||
5619 | break; | |||
5620 | ||||
5621 | case NestedNameSpecifier::Namespace: | |||
5622 | case NestedNameSpecifier::NamespaceAlias: | |||
5623 | case NestedNameSpecifier::Global: | |||
5624 | case NestedNameSpecifier::Super: | |||
5625 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5625); | |||
5626 | } | |||
5627 | ||||
5628 | // Finally fill in MemberPointerLocInfo fields. | |||
5629 | TL.setStarLoc(Chunk.Loc); | |||
5630 | TL.setClassTInfo(ClsTInfo); | |||
5631 | } | |||
5632 | void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { | |||
5633 | assert(Chunk.Kind == DeclaratorChunk::Reference)((Chunk.Kind == DeclaratorChunk::Reference) ? static_cast< void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5633, __PRETTY_FUNCTION__)); | |||
5634 | // 'Amp' is misleading: this might have been originally | |||
5635 | /// spelled with AmpAmp. | |||
5636 | TL.setAmpLoc(Chunk.Loc); | |||
5637 | } | |||
5638 | void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { | |||
5639 | assert(Chunk.Kind == DeclaratorChunk::Reference)((Chunk.Kind == DeclaratorChunk::Reference) ? static_cast< void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5639, __PRETTY_FUNCTION__)); | |||
5640 | assert(!Chunk.Ref.LValueRef)((!Chunk.Ref.LValueRef) ? static_cast<void> (0) : __assert_fail ("!Chunk.Ref.LValueRef", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5640, __PRETTY_FUNCTION__)); | |||
5641 | TL.setAmpAmpLoc(Chunk.Loc); | |||
5642 | } | |||
5643 | void VisitArrayTypeLoc(ArrayTypeLoc TL) { | |||
5644 | assert(Chunk.Kind == DeclaratorChunk::Array)((Chunk.Kind == DeclaratorChunk::Array) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Array" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5644, __PRETTY_FUNCTION__)); | |||
5645 | TL.setLBracketLoc(Chunk.Loc); | |||
5646 | TL.setRBracketLoc(Chunk.EndLoc); | |||
5647 | TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); | |||
5648 | } | |||
5649 | void VisitFunctionTypeLoc(FunctionTypeLoc TL) { | |||
5650 | assert(Chunk.Kind == DeclaratorChunk::Function)((Chunk.Kind == DeclaratorChunk::Function) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5650, __PRETTY_FUNCTION__)); | |||
5651 | TL.setLocalRangeBegin(Chunk.Loc); | |||
5652 | TL.setLocalRangeEnd(Chunk.EndLoc); | |||
5653 | ||||
5654 | const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; | |||
5655 | TL.setLParenLoc(FTI.getLParenLoc()); | |||
5656 | TL.setRParenLoc(FTI.getRParenLoc()); | |||
5657 | for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { | |||
5658 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
5659 | TL.setParam(tpi++, Param); | |||
5660 | } | |||
5661 | TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); | |||
5662 | } | |||
5663 | void VisitParenTypeLoc(ParenTypeLoc TL) { | |||
5664 | assert(Chunk.Kind == DeclaratorChunk::Paren)((Chunk.Kind == DeclaratorChunk::Paren) ? static_cast<void > (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Paren" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5664, __PRETTY_FUNCTION__)); | |||
5665 | TL.setLParenLoc(Chunk.Loc); | |||
5666 | TL.setRParenLoc(Chunk.EndLoc); | |||
5667 | } | |||
5668 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | |||
5669 | assert(Chunk.Kind == DeclaratorChunk::Pipe)((Chunk.Kind == DeclaratorChunk::Pipe) ? static_cast<void> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pipe", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5669, __PRETTY_FUNCTION__)); | |||
5670 | TL.setKWLoc(Chunk.Loc); | |||
5671 | } | |||
5672 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { | |||
5673 | TL.setExpansionLoc(Chunk.Loc); | |||
5674 | } | |||
5675 | ||||
5676 | void VisitTypeLoc(TypeLoc TL) { | |||
5677 | llvm_unreachable("unsupported TypeLoc kind in declarator!")::llvm::llvm_unreachable_internal("unsupported TypeLoc kind in declarator!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5677); | |||
5678 | } | |||
5679 | }; | |||
5680 | } // end anonymous namespace | |||
5681 | ||||
5682 | static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { | |||
5683 | SourceLocation Loc; | |||
5684 | switch (Chunk.Kind) { | |||
5685 | case DeclaratorChunk::Function: | |||
5686 | case DeclaratorChunk::Array: | |||
5687 | case DeclaratorChunk::Paren: | |||
5688 | case DeclaratorChunk::Pipe: | |||
5689 | llvm_unreachable("cannot be _Atomic qualified")::llvm::llvm_unreachable_internal("cannot be _Atomic qualified" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5689); | |||
5690 | ||||
5691 | case DeclaratorChunk::Pointer: | |||
5692 | Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); | |||
5693 | break; | |||
5694 | ||||
5695 | case DeclaratorChunk::BlockPointer: | |||
5696 | case DeclaratorChunk::Reference: | |||
5697 | case DeclaratorChunk::MemberPointer: | |||
5698 | // FIXME: Provide a source location for the _Atomic keyword. | |||
5699 | break; | |||
5700 | } | |||
5701 | ||||
5702 | ATL.setKWLoc(Loc); | |||
5703 | ATL.setParensRange(SourceRange()); | |||
5704 | } | |||
5705 | ||||
5706 | static void | |||
5707 | fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, | |||
5708 | const ParsedAttributesView &Attrs) { | |||
5709 | for (const ParsedAttr &AL : Attrs) { | |||
5710 | if (AL.getKind() == ParsedAttr::AT_AddressSpace) { | |||
5711 | DASTL.setAttrNameLoc(AL.getLoc()); | |||
5712 | DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); | |||
5713 | DASTL.setAttrOperandParensRange(SourceRange()); | |||
5714 | return; | |||
5715 | } | |||
5716 | } | |||
5717 | ||||
5718 | llvm_unreachable(::llvm::llvm_unreachable_internal("no address_space attribute found at the expected location!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5719) | |||
5719 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5719); | |||
5720 | } | |||
5721 | ||||
5722 | /// Create and instantiate a TypeSourceInfo with type source information. | |||
5723 | /// | |||
5724 | /// \param T QualType referring to the type as written in source code. | |||
5725 | /// | |||
5726 | /// \param ReturnTypeInfo For declarators whose return type does not show | |||
5727 | /// up in the normal place in the declaration specifiers (such as a C++ | |||
5728 | /// conversion function), this pointer will refer to a type source information | |||
5729 | /// for that return type. | |||
5730 | static TypeSourceInfo * | |||
5731 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, | |||
5732 | QualType T, TypeSourceInfo *ReturnTypeInfo) { | |||
5733 | Sema &S = State.getSema(); | |||
5734 | Declarator &D = State.getDeclarator(); | |||
5735 | ||||
5736 | TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); | |||
5737 | UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); | |||
5738 | ||||
5739 | // Handle parameter packs whose type is a pack expansion. | |||
5740 | if (isa<PackExpansionType>(T)) { | |||
5741 | CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); | |||
5742 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | |||
5743 | } | |||
5744 | ||||
5745 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
5746 | // An AtomicTypeLoc might be produced by an atomic qualifier in this | |||
5747 | // declarator chunk. | |||
5748 | if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { | |||
5749 | fillAtomicQualLoc(ATL, D.getTypeObject(i)); | |||
5750 | CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); | |||
5751 | } | |||
5752 | ||||
5753 | while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) { | |||
5754 | TL.setExpansionLoc( | |||
5755 | State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); | |||
5756 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
5757 | } | |||
5758 | ||||
5759 | while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { | |||
5760 | fillAttributedTypeLoc(TL, State); | |||
5761 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
5762 | } | |||
5763 | ||||
5764 | while (DependentAddressSpaceTypeLoc TL = | |||
5765 | CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { | |||
5766 | fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); | |||
5767 | CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); | |||
5768 | } | |||
5769 | ||||
5770 | // FIXME: Ordering here? | |||
5771 | while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) | |||
5772 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
5773 | ||||
5774 | DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); | |||
5775 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | |||
5776 | } | |||
5777 | ||||
5778 | // If we have different source information for the return type, use | |||
5779 | // that. This really only applies to C++ conversion functions. | |||
5780 | if (ReturnTypeInfo) { | |||
5781 | TypeLoc TL = ReturnTypeInfo->getTypeLoc(); | |||
5782 | assert(TL.getFullDataSize() == CurrTL.getFullDataSize())((TL.getFullDataSize() == CurrTL.getFullDataSize()) ? static_cast <void> (0) : __assert_fail ("TL.getFullDataSize() == CurrTL.getFullDataSize()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5782, __PRETTY_FUNCTION__)); | |||
5783 | memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); | |||
5784 | } else { | |||
5785 | TypeSpecLocFiller(S.Context, State, D.getDeclSpec()).Visit(CurrTL); | |||
5786 | } | |||
5787 | ||||
5788 | return TInfo; | |||
5789 | } | |||
5790 | ||||
5791 | /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. | |||
5792 | ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { | |||
5793 | // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser | |||
5794 | // and Sema during declaration parsing. Try deallocating/caching them when | |||
5795 | // it's appropriate, instead of allocating them and keeping them around. | |||
5796 | LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), | |||
5797 | TypeAlignment); | |||
5798 | new (LocT) LocInfoType(T, TInfo); | |||
5799 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5800, __PRETTY_FUNCTION__)) | |||
5800 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5800, __PRETTY_FUNCTION__)); | |||
5801 | return ParsedType::make(QualType(LocT, 0)); | |||
5802 | } | |||
5803 | ||||
5804 | void LocInfoType::getAsStringInternal(std::string &Str, | |||
5805 | const PrintingPolicy &Policy) const { | |||
5806 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5808) | |||
5807 | " 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5808) | |||
5808 | " 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5808); | |||
5809 | } | |||
5810 | ||||
5811 | TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { | |||
5812 | // C99 6.7.6: Type names have no identifier. This is already validated by | |||
5813 | // the parser. | |||
5814 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5815, __PRETTY_FUNCTION__)) | |||
5815 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 5815, __PRETTY_FUNCTION__)); | |||
5816 | ||||
5817 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
5818 | QualType T = TInfo->getType(); | |||
5819 | if (D.isInvalidType()) | |||
5820 | return true; | |||
5821 | ||||
5822 | // Make sure there are no unused decl attributes on the declarator. | |||
5823 | // We don't want to do this for ObjC parameters because we're going | |||
5824 | // to apply them to the actual parameter declaration. | |||
5825 | // Likewise, we don't want to do this for alias declarations, because | |||
5826 | // we are actually going to build a declaration from this eventually. | |||
5827 | if (D.getContext() != DeclaratorContext::ObjCParameterContext && | |||
5828 | D.getContext() != DeclaratorContext::AliasDeclContext && | |||
5829 | D.getContext() != DeclaratorContext::AliasTemplateContext) | |||
5830 | checkUnusedDeclAttributes(D); | |||
5831 | ||||
5832 | if (getLangOpts().CPlusPlus) { | |||
5833 | // Check that there are no default arguments (C++ only). | |||
5834 | CheckExtraCXXDefaultArguments(D); | |||
5835 | } | |||
5836 | ||||
5837 | return CreateParsedType(T, TInfo); | |||
5838 | } | |||
5839 | ||||
5840 | ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { | |||
5841 | QualType T = Context.getObjCInstanceType(); | |||
5842 | TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
5843 | return CreateParsedType(T, TInfo); | |||
5844 | } | |||
5845 | ||||
5846 | //===----------------------------------------------------------------------===// | |||
5847 | // Type Attribute Processing | |||
5848 | //===----------------------------------------------------------------------===// | |||
5849 | ||||
5850 | /// Build an AddressSpace index from a constant expression and diagnose any | |||
5851 | /// errors related to invalid address_spaces. Returns true on successfully | |||
5852 | /// building an AddressSpace index. | |||
5853 | static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, | |||
5854 | const Expr *AddrSpace, | |||
5855 | SourceLocation AttrLoc) { | |||
5856 | if (!AddrSpace->isValueDependent()) { | |||
5857 | llvm::APSInt addrSpace(32); | |||
5858 | if (!AddrSpace->isIntegerConstantExpr(addrSpace, S.Context)) { | |||
5859 | S.Diag(AttrLoc, diag::err_attribute_argument_type) | |||
5860 | << "'address_space'" << AANT_ArgumentIntegerConstant | |||
5861 | << AddrSpace->getSourceRange(); | |||
5862 | return false; | |||
5863 | } | |||
5864 | ||||
5865 | // Bounds checking. | |||
5866 | if (addrSpace.isSigned()) { | |||
5867 | if (addrSpace.isNegative()) { | |||
5868 | S.Diag(AttrLoc, diag::err_attribute_address_space_negative) | |||
5869 | << AddrSpace->getSourceRange(); | |||
5870 | return false; | |||
5871 | } | |||
5872 | addrSpace.setIsSigned(false); | |||
5873 | } | |||
5874 | ||||
5875 | llvm::APSInt max(addrSpace.getBitWidth()); | |||
5876 | max = | |||
5877 | Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; | |||
5878 | if (addrSpace > max) { | |||
5879 | S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) | |||
5880 | << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); | |||
5881 | return false; | |||
5882 | } | |||
5883 | ||||
5884 | ASIdx = | |||
5885 | getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); | |||
5886 | return true; | |||
5887 | } | |||
5888 | ||||
5889 | // Default value for DependentAddressSpaceTypes | |||
5890 | ASIdx = LangAS::Default; | |||
5891 | return true; | |||
5892 | } | |||
5893 | ||||
5894 | /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression | |||
5895 | /// is uninstantiated. If instantiated it will apply the appropriate address | |||
5896 | /// space to the type. This function allows dependent template variables to be | |||
5897 | /// used in conjunction with the address_space attribute | |||
5898 | QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, | |||
5899 | SourceLocation AttrLoc) { | |||
5900 | if (!AddrSpace->isValueDependent()) { | |||
5901 | if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, | |||
5902 | AttrLoc)) | |||
5903 | return QualType(); | |||
5904 | ||||
5905 | return Context.getAddrSpaceQualType(T, ASIdx); | |||
5906 | } | |||
5907 | ||||
5908 | // A check with similar intentions as checking if a type already has an | |||
5909 | // address space except for on a dependent types, basically if the | |||
5910 | // current type is already a DependentAddressSpaceType then its already | |||
5911 | // lined up to have another address space on it and we can't have | |||
5912 | // multiple address spaces on the one pointer indirection | |||
5913 | if (T->getAs<DependentAddressSpaceType>()) { | |||
5914 | Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | |||
5915 | return QualType(); | |||
5916 | } | |||
5917 | ||||
5918 | return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); | |||
5919 | } | |||
5920 | ||||
5921 | QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, | |||
5922 | SourceLocation AttrLoc) { | |||
5923 | LangAS ASIdx; | |||
5924 | if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) | |||
5925 | return QualType(); | |||
5926 | return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); | |||
5927 | } | |||
5928 | ||||
5929 | /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the | |||
5930 | /// specified type. The attribute contains 1 argument, the id of the address | |||
5931 | /// space for the type. | |||
5932 | static void HandleAddressSpaceTypeAttribute(QualType &Type, | |||
5933 | const ParsedAttr &Attr, | |||
5934 | TypeProcessingState &State) { | |||
5935 | Sema &S = State.getSema(); | |||
5936 | ||||
5937 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be | |||
5938 | // qualified by an address-space qualifier." | |||
5939 | if (Type->isFunctionType()) { | |||
5940 | S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); | |||
5941 | Attr.setInvalid(); | |||
5942 | return; | |||
5943 | } | |||
5944 | ||||
5945 | LangAS ASIdx; | |||
5946 | if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { | |||
5947 | ||||
5948 | // Check the attribute arguments. | |||
5949 | if (Attr.getNumArgs() != 1) { | |||
5950 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
5951 | << 1; | |||
5952 | Attr.setInvalid(); | |||
5953 | return; | |||
5954 | } | |||
5955 | ||||
5956 | Expr *ASArgExpr; | |||
5957 | if (Attr.isArgIdent(0)) { | |||
5958 | // Special case where the argument is a template id. | |||
5959 | CXXScopeSpec SS; | |||
5960 | SourceLocation TemplateKWLoc; | |||
5961 | UnqualifiedId id; | |||
5962 | id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); | |||
5963 | ||||
5964 | ExprResult AddrSpace = S.ActOnIdExpression( | |||
5965 | S.getCurScope(), SS, TemplateKWLoc, id, /*HasTrailingLParen=*/false, | |||
5966 | /*IsAddressOfOperand=*/false); | |||
5967 | if (AddrSpace.isInvalid()) | |||
5968 | return; | |||
5969 | ||||
5970 | ASArgExpr = static_cast<Expr *>(AddrSpace.get()); | |||
5971 | } else { | |||
5972 | ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); | |||
5973 | } | |||
5974 | ||||
5975 | LangAS ASIdx; | |||
5976 | if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { | |||
5977 | Attr.setInvalid(); | |||
5978 | return; | |||
5979 | } | |||
5980 | ||||
5981 | ASTContext &Ctx = S.Context; | |||
5982 | auto *ASAttr = ::new (Ctx) AddressSpaceAttr( | |||
5983 | Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex(), | |||
5984 | static_cast<unsigned>(ASIdx)); | |||
5985 | ||||
5986 | // If the expression is not value dependent (not templated), then we can | |||
5987 | // apply the address space qualifiers just to the equivalent type. | |||
5988 | // Otherwise, we make an AttributedType with the modified and equivalent | |||
5989 | // type the same, and wrap it in a DependentAddressSpaceType. When this | |||
5990 | // dependent type is resolved, the qualifier is added to the equivalent type | |||
5991 | // later. | |||
5992 | QualType T; | |||
5993 | if (!ASArgExpr->isValueDependent()) { | |||
5994 | QualType EquivType = | |||
5995 | S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); | |||
5996 | if (EquivType.isNull()) { | |||
5997 | Attr.setInvalid(); | |||
5998 | return; | |||
5999 | } | |||
6000 | T = State.getAttributedType(ASAttr, Type, EquivType); | |||
6001 | } else { | |||
6002 | T = State.getAttributedType(ASAttr, Type, Type); | |||
6003 | T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); | |||
6004 | } | |||
6005 | ||||
6006 | if (!T.isNull()) | |||
6007 | Type = T; | |||
6008 | else | |||
6009 | Attr.setInvalid(); | |||
6010 | } else { | |||
6011 | // The keyword-based type attributes imply which address space to use. | |||
6012 | ASIdx = Attr.asOpenCLLangAS(); | |||
6013 | if (ASIdx == LangAS::Default) | |||
6014 | llvm_unreachable("Invalid address space")::llvm::llvm_unreachable_internal("Invalid address space", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6014); | |||
6015 | ||||
6016 | if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, | |||
6017 | Attr.getLoc())) { | |||
6018 | Attr.setInvalid(); | |||
6019 | return; | |||
6020 | } | |||
6021 | ||||
6022 | Type = S.Context.getAddrSpaceQualType(Type, ASIdx); | |||
6023 | } | |||
6024 | } | |||
6025 | ||||
6026 | /// Does this type have a "direct" ownership qualifier? That is, | |||
6027 | /// is it written like "__strong id", as opposed to something like | |||
6028 | /// "typeof(foo)", where that happens to be strong? | |||
6029 | static bool hasDirectOwnershipQualifier(QualType type) { | |||
6030 | // Fast path: no qualifier at all. | |||
6031 | assert(type.getQualifiers().hasObjCLifetime())((type.getQualifiers().hasObjCLifetime()) ? static_cast<void > (0) : __assert_fail ("type.getQualifiers().hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6031, __PRETTY_FUNCTION__)); | |||
6032 | ||||
6033 | while (true) { | |||
6034 | // __strong id | |||
6035 | if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { | |||
6036 | if (attr->getAttrKind() == attr::ObjCOwnership) | |||
6037 | return true; | |||
6038 | ||||
6039 | type = attr->getModifiedType(); | |||
6040 | ||||
6041 | // X *__strong (...) | |||
6042 | } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { | |||
6043 | type = paren->getInnerType(); | |||
6044 | ||||
6045 | // That's it for things we want to complain about. In particular, | |||
6046 | // we do not want to look through typedefs, typeof(expr), | |||
6047 | // typeof(type), or any other way that the type is somehow | |||
6048 | // abstracted. | |||
6049 | } else { | |||
6050 | ||||
6051 | return false; | |||
6052 | } | |||
6053 | } | |||
6054 | } | |||
6055 | ||||
6056 | /// handleObjCOwnershipTypeAttr - Process an objc_ownership | |||
6057 | /// attribute on the specified type. | |||
6058 | /// | |||
6059 | /// Returns 'true' if the attribute was handled. | |||
6060 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | |||
6061 | ParsedAttr &attr, QualType &type) { | |||
6062 | bool NonObjCPointer = false; | |||
6063 | ||||
6064 | if (!type->isDependentType() && !type->isUndeducedType()) { | |||
6065 | if (const PointerType *ptr = type->getAs<PointerType>()) { | |||
6066 | QualType pointee = ptr->getPointeeType(); | |||
6067 | if (pointee->isObjCRetainableType() || pointee->isPointerType()) | |||
6068 | return false; | |||
6069 | // It is important not to lose the source info that there was an attribute | |||
6070 | // applied to non-objc pointer. We will create an attributed type but | |||
6071 | // its type will be the same as the original type. | |||
6072 | NonObjCPointer = true; | |||
6073 | } else if (!type->isObjCRetainableType()) { | |||
6074 | return false; | |||
6075 | } | |||
6076 | ||||
6077 | // Don't accept an ownership attribute in the declspec if it would | |||
6078 | // just be the return type of a block pointer. | |||
6079 | if (state.isProcessingDeclSpec()) { | |||
6080 | Declarator &D = state.getDeclarator(); | |||
6081 | if (maybeMovePastReturnType(D, D.getNumTypeObjects(), | |||
6082 | /*onlyBlockPointers=*/true)) | |||
6083 | return false; | |||
6084 | } | |||
6085 | } | |||
6086 | ||||
6087 | Sema &S = state.getSema(); | |||
6088 | SourceLocation AttrLoc = attr.getLoc(); | |||
6089 | if (AttrLoc.isMacroID()) | |||
6090 | AttrLoc = | |||
6091 | S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); | |||
6092 | ||||
6093 | if (!attr.isArgIdent(0)) { | |||
6094 | S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr | |||
6095 | << AANT_ArgumentString; | |||
6096 | attr.setInvalid(); | |||
6097 | return true; | |||
6098 | } | |||
6099 | ||||
6100 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | |||
6101 | Qualifiers::ObjCLifetime lifetime; | |||
6102 | if (II->isStr("none")) | |||
6103 | lifetime = Qualifiers::OCL_ExplicitNone; | |||
6104 | else if (II->isStr("strong")) | |||
6105 | lifetime = Qualifiers::OCL_Strong; | |||
6106 | else if (II->isStr("weak")) | |||
6107 | lifetime = Qualifiers::OCL_Weak; | |||
6108 | else if (II->isStr("autoreleasing")) | |||
6109 | lifetime = Qualifiers::OCL_Autoreleasing; | |||
6110 | else { | |||
6111 | S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) | |||
6112 | << attr.getName() << II; | |||
6113 | attr.setInvalid(); | |||
6114 | return true; | |||
6115 | } | |||
6116 | ||||
6117 | // Just ignore lifetime attributes other than __weak and __unsafe_unretained | |||
6118 | // outside of ARC mode. | |||
6119 | if (!S.getLangOpts().ObjCAutoRefCount && | |||
6120 | lifetime != Qualifiers::OCL_Weak && | |||
6121 | lifetime != Qualifiers::OCL_ExplicitNone) { | |||
6122 | return true; | |||
6123 | } | |||
6124 | ||||
6125 | SplitQualType underlyingType = type.split(); | |||
6126 | ||||
6127 | // Check for redundant/conflicting ownership qualifiers. | |||
6128 | if (Qualifiers::ObjCLifetime previousLifetime | |||
6129 | = type.getQualifiers().getObjCLifetime()) { | |||
6130 | // If it's written directly, that's an error. | |||
6131 | if (hasDirectOwnershipQualifier(type)) { | |||
6132 | S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) | |||
6133 | << type; | |||
6134 | return true; | |||
6135 | } | |||
6136 | ||||
6137 | // Otherwise, if the qualifiers actually conflict, pull sugar off | |||
6138 | // and remove the ObjCLifetime qualifiers. | |||
6139 | if (previousLifetime != lifetime) { | |||
6140 | // It's possible to have multiple local ObjCLifetime qualifiers. We | |||
6141 | // can't stop after we reach a type that is directly qualified. | |||
6142 | const Type *prevTy = nullptr; | |||
6143 | while (!prevTy || prevTy != underlyingType.Ty) { | |||
6144 | prevTy = underlyingType.Ty; | |||
6145 | underlyingType = underlyingType.getSingleStepDesugaredType(); | |||
6146 | } | |||
6147 | underlyingType.Quals.removeObjCLifetime(); | |||
6148 | } | |||
6149 | } | |||
6150 | ||||
6151 | underlyingType.Quals.addObjCLifetime(lifetime); | |||
6152 | ||||
6153 | if (NonObjCPointer) { | |||
6154 | StringRef name = attr.getName()->getName(); | |||
6155 | switch (lifetime) { | |||
6156 | case Qualifiers::OCL_None: | |||
6157 | case Qualifiers::OCL_ExplicitNone: | |||
6158 | break; | |||
6159 | case Qualifiers::OCL_Strong: name = "__strong"; break; | |||
6160 | case Qualifiers::OCL_Weak: name = "__weak"; break; | |||
6161 | case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; | |||
6162 | } | |||
6163 | S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name | |||
6164 | << TDS_ObjCObjOrBlock << type; | |||
6165 | } | |||
6166 | ||||
6167 | // Don't actually add the __unsafe_unretained qualifier in non-ARC files, | |||
6168 | // because having both 'T' and '__unsafe_unretained T' exist in the type | |||
6169 | // system causes unfortunate widespread consistency problems. (For example, | |||
6170 | // they're not considered compatible types, and we mangle them identicially | |||
6171 | // as template arguments.) These problems are all individually fixable, | |||
6172 | // but it's easier to just not add the qualifier and instead sniff it out | |||
6173 | // in specific places using isObjCInertUnsafeUnretainedType(). | |||
6174 | // | |||
6175 | // Doing this does means we miss some trivial consistency checks that | |||
6176 | // would've triggered in ARC, but that's better than trying to solve all | |||
6177 | // the coexistence problems with __unsafe_unretained. | |||
6178 | if (!S.getLangOpts().ObjCAutoRefCount && | |||
6179 | lifetime == Qualifiers::OCL_ExplicitNone) { | |||
6180 | type = state.getAttributedType( | |||
6181 | createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), | |||
6182 | type, type); | |||
6183 | return true; | |||
6184 | } | |||
6185 | ||||
6186 | QualType origType = type; | |||
6187 | if (!NonObjCPointer) | |||
6188 | type = S.Context.getQualifiedType(underlyingType); | |||
6189 | ||||
6190 | // If we have a valid source location for the attribute, use an | |||
6191 | // AttributedType instead. | |||
6192 | if (AttrLoc.isValid()) { | |||
6193 | type = state.getAttributedType(::new (S.Context) ObjCOwnershipAttr( | |||
6194 | attr.getRange(), S.Context, II, | |||
6195 | attr.getAttributeSpellingListIndex()), | |||
6196 | origType, type); | |||
6197 | } | |||
6198 | ||||
6199 | auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, | |||
6200 | unsigned diagnostic, QualType type) { | |||
6201 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | |||
6202 | S.DelayedDiagnostics.add( | |||
6203 | sema::DelayedDiagnostic::makeForbiddenType( | |||
6204 | S.getSourceManager().getExpansionLoc(loc), | |||
6205 | diagnostic, type, /*ignored*/ 0)); | |||
6206 | } else { | |||
6207 | S.Diag(loc, diagnostic); | |||
6208 | } | |||
6209 | }; | |||
6210 | ||||
6211 | // Sometimes, __weak isn't allowed. | |||
6212 | if (lifetime == Qualifiers::OCL_Weak && | |||
6213 | !S.getLangOpts().ObjCWeak && !NonObjCPointer) { | |||
6214 | ||||
6215 | // Use a specialized diagnostic if the runtime just doesn't support them. | |||
6216 | unsigned diagnostic = | |||
6217 | (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled | |||
6218 | : diag::err_arc_weak_no_runtime); | |||
6219 | ||||
6220 | // In any case, delay the diagnostic until we know what we're parsing. | |||
6221 | diagnoseOrDelay(S, AttrLoc, diagnostic, type); | |||
6222 | ||||
6223 | attr.setInvalid(); | |||
6224 | return true; | |||
6225 | } | |||
6226 | ||||
6227 | // Forbid __weak for class objects marked as | |||
6228 | // objc_arc_weak_reference_unavailable | |||
6229 | if (lifetime == Qualifiers::OCL_Weak) { | |||
6230 | if (const ObjCObjectPointerType *ObjT = | |||
6231 | type->getAs<ObjCObjectPointerType>()) { | |||
6232 | if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { | |||
6233 | if (Class->isArcWeakrefUnavailable()) { | |||
6234 | S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); | |||
6235 | S.Diag(ObjT->getInterfaceDecl()->getLocation(), | |||
6236 | diag::note_class_declared); | |||
6237 | } | |||
6238 | } | |||
6239 | } | |||
6240 | } | |||
6241 | ||||
6242 | return true; | |||
6243 | } | |||
6244 | ||||
6245 | /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type | |||
6246 | /// attribute on the specified type. Returns true to indicate that | |||
6247 | /// the attribute was handled, false to indicate that the type does | |||
6248 | /// not permit the attribute. | |||
6249 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
6250 | QualType &type) { | |||
6251 | Sema &S = state.getSema(); | |||
6252 | ||||
6253 | // Delay if this isn't some kind of pointer. | |||
6254 | if (!type->isPointerType() && | |||
6255 | !type->isObjCObjectPointerType() && | |||
6256 | !type->isBlockPointerType()) | |||
6257 | return false; | |||
6258 | ||||
6259 | if (type.getObjCGCAttr() != Qualifiers::GCNone) { | |||
6260 | S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); | |||
6261 | attr.setInvalid(); | |||
6262 | return true; | |||
6263 | } | |||
6264 | ||||
6265 | // Check the attribute arguments. | |||
6266 | if (!attr.isArgIdent(0)) { | |||
6267 | S.Diag(attr.getLoc(), diag::err_attribute_argument_type) | |||
6268 | << attr << AANT_ArgumentString; | |||
6269 | attr.setInvalid(); | |||
6270 | return true; | |||
6271 | } | |||
6272 | Qualifiers::GC GCAttr; | |||
6273 | if (attr.getNumArgs() > 1) { | |||
6274 | S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr | |||
6275 | << 1; | |||
6276 | attr.setInvalid(); | |||
6277 | return true; | |||
6278 | } | |||
6279 | ||||
6280 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | |||
6281 | if (II->isStr("weak")) | |||
6282 | GCAttr = Qualifiers::Weak; | |||
6283 | else if (II->isStr("strong")) | |||
6284 | GCAttr = Qualifiers::Strong; | |||
6285 | else { | |||
6286 | S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) | |||
6287 | << attr.getName() << II; | |||
6288 | attr.setInvalid(); | |||
6289 | return true; | |||
6290 | } | |||
6291 | ||||
6292 | QualType origType = type; | |||
6293 | type = S.Context.getObjCGCQualType(origType, GCAttr); | |||
6294 | ||||
6295 | // Make an attributed type to preserve the source information. | |||
6296 | if (attr.getLoc().isValid()) | |||
6297 | type = state.getAttributedType( | |||
6298 | ::new (S.Context) ObjCGCAttr(attr.getRange(), S.Context, II, | |||
6299 | attr.getAttributeSpellingListIndex()), | |||
6300 | origType, type); | |||
6301 | ||||
6302 | return true; | |||
6303 | } | |||
6304 | ||||
6305 | namespace { | |||
6306 | /// A helper class to unwrap a type down to a function for the | |||
6307 | /// purposes of applying attributes there. | |||
6308 | /// | |||
6309 | /// Use: | |||
6310 | /// FunctionTypeUnwrapper unwrapped(SemaRef, T); | |||
6311 | /// if (unwrapped.isFunctionType()) { | |||
6312 | /// const FunctionType *fn = unwrapped.get(); | |||
6313 | /// // change fn somehow | |||
6314 | /// T = unwrapped.wrap(fn); | |||
6315 | /// } | |||
6316 | struct FunctionTypeUnwrapper { | |||
6317 | enum WrapKind { | |||
6318 | Desugar, | |||
6319 | Attributed, | |||
6320 | Parens, | |||
6321 | Pointer, | |||
6322 | BlockPointer, | |||
6323 | Reference, | |||
6324 | MemberPointer | |||
6325 | }; | |||
6326 | ||||
6327 | QualType Original; | |||
6328 | const FunctionType *Fn; | |||
6329 | SmallVector<unsigned char /*WrapKind*/, 8> Stack; | |||
6330 | ||||
6331 | FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { | |||
6332 | while (true) { | |||
6333 | const Type *Ty = T.getTypePtr(); | |||
6334 | if (isa<FunctionType>(Ty)) { | |||
6335 | Fn = cast<FunctionType>(Ty); | |||
6336 | return; | |||
6337 | } else if (isa<ParenType>(Ty)) { | |||
6338 | T = cast<ParenType>(Ty)->getInnerType(); | |||
6339 | Stack.push_back(Parens); | |||
6340 | } else if (isa<PointerType>(Ty)) { | |||
6341 | T = cast<PointerType>(Ty)->getPointeeType(); | |||
6342 | Stack.push_back(Pointer); | |||
6343 | } else if (isa<BlockPointerType>(Ty)) { | |||
6344 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | |||
6345 | Stack.push_back(BlockPointer); | |||
6346 | } else if (isa<MemberPointerType>(Ty)) { | |||
6347 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | |||
6348 | Stack.push_back(MemberPointer); | |||
6349 | } else if (isa<ReferenceType>(Ty)) { | |||
6350 | T = cast<ReferenceType>(Ty)->getPointeeType(); | |||
6351 | Stack.push_back(Reference); | |||
6352 | } else if (isa<AttributedType>(Ty)) { | |||
6353 | T = cast<AttributedType>(Ty)->getEquivalentType(); | |||
6354 | Stack.push_back(Attributed); | |||
6355 | } else { | |||
6356 | const Type *DTy = Ty->getUnqualifiedDesugaredType(); | |||
6357 | if (Ty == DTy) { | |||
6358 | Fn = nullptr; | |||
6359 | return; | |||
6360 | } | |||
6361 | ||||
6362 | T = QualType(DTy, 0); | |||
6363 | Stack.push_back(Desugar); | |||
6364 | } | |||
6365 | } | |||
6366 | } | |||
6367 | ||||
6368 | bool isFunctionType() const { return (Fn != nullptr); } | |||
6369 | const FunctionType *get() const { return Fn; } | |||
6370 | ||||
6371 | QualType wrap(Sema &S, const FunctionType *New) { | |||
6372 | // If T wasn't modified from the unwrapped type, do nothing. | |||
6373 | if (New == get()) return Original; | |||
6374 | ||||
6375 | Fn = New; | |||
6376 | return wrap(S.Context, Original, 0); | |||
6377 | } | |||
6378 | ||||
6379 | private: | |||
6380 | QualType wrap(ASTContext &C, QualType Old, unsigned I) { | |||
6381 | if (I == Stack.size()) | |||
6382 | return C.getQualifiedType(Fn, Old.getQualifiers()); | |||
6383 | ||||
6384 | // Build up the inner type, applying the qualifiers from the old | |||
6385 | // type to the new type. | |||
6386 | SplitQualType SplitOld = Old.split(); | |||
6387 | ||||
6388 | // As a special case, tail-recurse if there are no qualifiers. | |||
6389 | if (SplitOld.Quals.empty()) | |||
6390 | return wrap(C, SplitOld.Ty, I); | |||
6391 | return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); | |||
6392 | } | |||
6393 | ||||
6394 | QualType wrap(ASTContext &C, const Type *Old, unsigned I) { | |||
6395 | if (I == Stack.size()) return QualType(Fn, 0); | |||
6396 | ||||
6397 | switch (static_cast<WrapKind>(Stack[I++])) { | |||
6398 | case Desugar: | |||
6399 | // This is the point at which we potentially lose source | |||
6400 | // information. | |||
6401 | return wrap(C, Old->getUnqualifiedDesugaredType(), I); | |||
6402 | ||||
6403 | case Attributed: | |||
6404 | return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); | |||
6405 | ||||
6406 | case Parens: { | |||
6407 | QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); | |||
6408 | return C.getParenType(New); | |||
6409 | } | |||
6410 | ||||
6411 | case Pointer: { | |||
6412 | QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); | |||
6413 | return C.getPointerType(New); | |||
6414 | } | |||
6415 | ||||
6416 | case BlockPointer: { | |||
6417 | QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); | |||
6418 | return C.getBlockPointerType(New); | |||
6419 | } | |||
6420 | ||||
6421 | case MemberPointer: { | |||
6422 | const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); | |||
6423 | QualType New = wrap(C, OldMPT->getPointeeType(), I); | |||
6424 | return C.getMemberPointerType(New, OldMPT->getClass()); | |||
6425 | } | |||
6426 | ||||
6427 | case Reference: { | |||
6428 | const ReferenceType *OldRef = cast<ReferenceType>(Old); | |||
6429 | QualType New = wrap(C, OldRef->getPointeeType(), I); | |||
6430 | if (isa<LValueReferenceType>(OldRef)) | |||
6431 | return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); | |||
6432 | else | |||
6433 | return C.getRValueReferenceType(New); | |||
6434 | } | |||
6435 | } | |||
6436 | ||||
6437 | llvm_unreachable("unknown wrapping kind")::llvm::llvm_unreachable_internal("unknown wrapping kind", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6437); | |||
6438 | } | |||
6439 | }; | |||
6440 | } // end anonymous namespace | |||
6441 | ||||
6442 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, | |||
6443 | ParsedAttr &PAttr, QualType &Type) { | |||
6444 | Sema &S = State.getSema(); | |||
6445 | ||||
6446 | Attr *A; | |||
6447 | switch (PAttr.getKind()) { | |||
6448 | default: llvm_unreachable("Unknown attribute kind")::llvm::llvm_unreachable_internal("Unknown attribute kind", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6448); | |||
6449 | case ParsedAttr::AT_Ptr32: | |||
6450 | A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); | |||
6451 | break; | |||
6452 | case ParsedAttr::AT_Ptr64: | |||
6453 | A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); | |||
6454 | break; | |||
6455 | case ParsedAttr::AT_SPtr: | |||
6456 | A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); | |||
6457 | break; | |||
6458 | case ParsedAttr::AT_UPtr: | |||
6459 | A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); | |||
6460 | break; | |||
6461 | } | |||
6462 | ||||
6463 | attr::Kind NewAttrKind = A->getKind(); | |||
6464 | QualType Desugared = Type; | |||
6465 | const AttributedType *AT = dyn_cast<AttributedType>(Type); | |||
6466 | while (AT) { | |||
6467 | attr::Kind CurAttrKind = AT->getAttrKind(); | |||
6468 | ||||
6469 | // You cannot specify duplicate type attributes, so if the attribute has | |||
6470 | // already been applied, flag it. | |||
6471 | if (NewAttrKind == CurAttrKind) { | |||
6472 | S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) | |||
6473 | << PAttr.getName(); | |||
6474 | return true; | |||
6475 | } | |||
6476 | ||||
6477 | // You cannot have both __sptr and __uptr on the same type, nor can you | |||
6478 | // have __ptr32 and __ptr64. | |||
6479 | if ((CurAttrKind == attr::Ptr32 && NewAttrKind == attr::Ptr64) || | |||
6480 | (CurAttrKind == attr::Ptr64 && NewAttrKind == attr::Ptr32)) { | |||
6481 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) | |||
6482 | << "'__ptr32'" << "'__ptr64'"; | |||
6483 | return true; | |||
6484 | } else if ((CurAttrKind == attr::SPtr && NewAttrKind == attr::UPtr) || | |||
6485 | (CurAttrKind == attr::UPtr && NewAttrKind == attr::SPtr)) { | |||
6486 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) | |||
6487 | << "'__sptr'" << "'__uptr'"; | |||
6488 | return true; | |||
6489 | } | |||
6490 | ||||
6491 | Desugared = AT->getEquivalentType(); | |||
6492 | AT = dyn_cast<AttributedType>(Desugared); | |||
6493 | } | |||
6494 | ||||
6495 | // Pointer type qualifiers can only operate on pointer types, but not | |||
6496 | // pointer-to-member types. | |||
6497 | // | |||
6498 | // FIXME: Should we really be disallowing this attribute if there is any | |||
6499 | // type sugar between it and the pointer (other than attributes)? Eg, this | |||
6500 | // disallows the attribute on a parenthesized pointer. | |||
6501 | // And if so, should we really allow *any* type attribute? | |||
6502 | if (!isa<PointerType>(Desugared)) { | |||
6503 | if (Type->isMemberPointerType()) | |||
6504 | S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; | |||
6505 | else | |||
6506 | S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; | |||
6507 | return true; | |||
6508 | } | |||
6509 | ||||
6510 | Type = State.getAttributedType(A, Type, Type); | |||
6511 | return false; | |||
6512 | } | |||
6513 | ||||
6514 | /// Map a nullability attribute kind to a nullability kind. | |||
6515 | static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { | |||
6516 | switch (kind) { | |||
6517 | case ParsedAttr::AT_TypeNonNull: | |||
6518 | return NullabilityKind::NonNull; | |||
6519 | ||||
6520 | case ParsedAttr::AT_TypeNullable: | |||
6521 | return NullabilityKind::Nullable; | |||
6522 | ||||
6523 | case ParsedAttr::AT_TypeNullUnspecified: | |||
6524 | return NullabilityKind::Unspecified; | |||
6525 | ||||
6526 | default: | |||
6527 | llvm_unreachable("not a nullability attribute kind")::llvm::llvm_unreachable_internal("not a nullability attribute kind" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6527); | |||
6528 | } | |||
6529 | } | |||
6530 | ||||
6531 | /// Applies a nullability type specifier to the given type, if possible. | |||
6532 | /// | |||
6533 | /// \param state The type processing state. | |||
6534 | /// | |||
6535 | /// \param type The type to which the nullability specifier will be | |||
6536 | /// added. On success, this type will be updated appropriately. | |||
6537 | /// | |||
6538 | /// \param attr The attribute as written on the type. | |||
6539 | /// | |||
6540 | /// \param allowOnArrayType Whether to accept nullability specifiers on an | |||
6541 | /// array type (e.g., because it will decay to a pointer). | |||
6542 | /// | |||
6543 | /// \returns true if a problem has been diagnosed, false on success. | |||
6544 | static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, | |||
6545 | QualType &type, | |||
6546 | ParsedAttr &attr, | |||
6547 | bool allowOnArrayType) { | |||
6548 | Sema &S = state.getSema(); | |||
6549 | ||||
6550 | NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); | |||
6551 | SourceLocation nullabilityLoc = attr.getLoc(); | |||
6552 | bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); | |||
6553 | ||||
6554 | recordNullabilitySeen(S, nullabilityLoc); | |||
6555 | ||||
6556 | // Check for existing nullability attributes on the type. | |||
6557 | QualType desugared = type; | |||
6558 | while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { | |||
6559 | // Check whether there is already a null | |||
6560 | if (auto existingNullability = attributed->getImmediateNullability()) { | |||
6561 | // Duplicated nullability. | |||
6562 | if (nullability == *existingNullability) { | |||
6563 | S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) | |||
6564 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
6565 | << FixItHint::CreateRemoval(nullabilityLoc); | |||
6566 | ||||
6567 | break; | |||
6568 | } | |||
6569 | ||||
6570 | // Conflicting nullability. | |||
6571 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) | |||
6572 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
6573 | << DiagNullabilityKind(*existingNullability, false); | |||
6574 | return true; | |||
6575 | } | |||
6576 | ||||
6577 | desugared = attributed->getModifiedType(); | |||
6578 | } | |||
6579 | ||||
6580 | // If there is already a different nullability specifier, complain. | |||
6581 | // This (unlike the code above) looks through typedefs that might | |||
6582 | // have nullability specifiers on them, which means we cannot | |||
6583 | // provide a useful Fix-It. | |||
6584 | if (auto existingNullability = desugared->getNullability(S.Context)) { | |||
6585 | if (nullability != *existingNullability) { | |||
6586 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) | |||
6587 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
6588 | << DiagNullabilityKind(*existingNullability, false); | |||
6589 | ||||
6590 | // Try to find the typedef with the existing nullability specifier. | |||
6591 | if (auto typedefType = desugared->getAs<TypedefType>()) { | |||
6592 | TypedefNameDecl *typedefDecl = typedefType->getDecl(); | |||
6593 | QualType underlyingType = typedefDecl->getUnderlyingType(); | |||
6594 | if (auto typedefNullability | |||
6595 | = AttributedType::stripOuterNullability(underlyingType)) { | |||
6596 | if (*typedefNullability == *existingNullability) { | |||
6597 | S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) | |||
6598 | << DiagNullabilityKind(*existingNullability, false); | |||
6599 | } | |||
6600 | } | |||
6601 | } | |||
6602 | ||||
6603 | return true; | |||
6604 | } | |||
6605 | } | |||
6606 | ||||
6607 | // If this definitely isn't a pointer type, reject the specifier. | |||
6608 | if (!desugared->canHaveNullability() && | |||
6609 | !(allowOnArrayType && desugared->isArrayType())) { | |||
6610 | S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) | |||
6611 | << DiagNullabilityKind(nullability, isContextSensitive) << type; | |||
6612 | return true; | |||
6613 | } | |||
6614 | ||||
6615 | // For the context-sensitive keywords/Objective-C property | |||
6616 | // attributes, require that the type be a single-level pointer. | |||
6617 | if (isContextSensitive) { | |||
6618 | // Make sure that the pointee isn't itself a pointer type. | |||
6619 | const Type *pointeeType; | |||
6620 | if (desugared->isArrayType()) | |||
6621 | pointeeType = desugared->getArrayElementTypeNoTypeQual(); | |||
6622 | else | |||
6623 | pointeeType = desugared->getPointeeType().getTypePtr(); | |||
6624 | ||||
6625 | if (pointeeType->isAnyPointerType() || | |||
6626 | pointeeType->isObjCObjectPointerType() || | |||
6627 | pointeeType->isMemberPointerType()) { | |||
6628 | S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) | |||
6629 | << DiagNullabilityKind(nullability, true) | |||
6630 | << type; | |||
6631 | S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) | |||
6632 | << DiagNullabilityKind(nullability, false) | |||
6633 | << type | |||
6634 | << FixItHint::CreateReplacement(nullabilityLoc, | |||
6635 | getNullabilitySpelling(nullability)); | |||
6636 | return true; | |||
6637 | } | |||
6638 | } | |||
6639 | ||||
6640 | // Form the attributed type. | |||
6641 | type = state.getAttributedType( | |||
6642 | createNullabilityAttr(S.Context, attr, nullability), type, type); | |||
6643 | return false; | |||
6644 | } | |||
6645 | ||||
6646 | /// Check the application of the Objective-C '__kindof' qualifier to | |||
6647 | /// the given type. | |||
6648 | static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, | |||
6649 | ParsedAttr &attr) { | |||
6650 | Sema &S = state.getSema(); | |||
6651 | ||||
6652 | if (isa<ObjCTypeParamType>(type)) { | |||
6653 | // Build the attributed type to record where __kindof occurred. | |||
6654 | type = state.getAttributedType( | |||
6655 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); | |||
6656 | return false; | |||
6657 | } | |||
6658 | ||||
6659 | // Find out if it's an Objective-C object or object pointer type; | |||
6660 | const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); | |||
6661 | const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() | |||
6662 | : type->getAs<ObjCObjectType>(); | |||
6663 | ||||
6664 | // If not, we can't apply __kindof. | |||
6665 | if (!objType) { | |||
6666 | // FIXME: Handle dependent types that aren't yet object types. | |||
6667 | S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) | |||
6668 | << type; | |||
6669 | return true; | |||
6670 | } | |||
6671 | ||||
6672 | // Rebuild the "equivalent" type, which pushes __kindof down into | |||
6673 | // the object type. | |||
6674 | // There is no need to apply kindof on an unqualified id type. | |||
6675 | QualType equivType = S.Context.getObjCObjectType( | |||
6676 | objType->getBaseType(), objType->getTypeArgsAsWritten(), | |||
6677 | objType->getProtocols(), | |||
6678 | /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); | |||
6679 | ||||
6680 | // If we started with an object pointer type, rebuild it. | |||
6681 | if (ptrType) { | |||
6682 | equivType = S.Context.getObjCObjectPointerType(equivType); | |||
6683 | if (auto nullability = type->getNullability(S.Context)) { | |||
6684 | // We create a nullability attribute from the __kindof attribute. | |||
6685 | // Make sure that will make sense. | |||
6686 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6687, __PRETTY_FUNCTION__)) | |||
6687 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6687, __PRETTY_FUNCTION__)); | |||
6688 | Attr *A = createNullabilityAttr(S.Context, attr, *nullability); | |||
6689 | A->setImplicit(true); | |||
6690 | equivType = state.getAttributedType(A, equivType, equivType); | |||
6691 | } | |||
6692 | } | |||
6693 | ||||
6694 | // Build the attributed type to record where __kindof occurred. | |||
6695 | type = state.getAttributedType( | |||
6696 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); | |||
6697 | return false; | |||
6698 | } | |||
6699 | ||||
6700 | /// Distribute a nullability type attribute that cannot be applied to | |||
6701 | /// the type specifier to a pointer, block pointer, or member pointer | |||
6702 | /// declarator, complaining if necessary. | |||
6703 | /// | |||
6704 | /// \returns true if the nullability annotation was distributed, false | |||
6705 | /// otherwise. | |||
6706 | static bool distributeNullabilityTypeAttr(TypeProcessingState &state, | |||
6707 | QualType type, ParsedAttr &attr) { | |||
6708 | Declarator &declarator = state.getDeclarator(); | |||
6709 | ||||
6710 | /// Attempt to move the attribute to the specified chunk. | |||
6711 | auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { | |||
6712 | // If there is already a nullability attribute there, don't add | |||
6713 | // one. | |||
6714 | if (hasNullabilityAttr(chunk.getAttrs())) | |||
6715 | return false; | |||
6716 | ||||
6717 | // Complain about the nullability qualifier being in the wrong | |||
6718 | // place. | |||
6719 | enum { | |||
6720 | PK_Pointer, | |||
6721 | PK_BlockPointer, | |||
6722 | PK_MemberPointer, | |||
6723 | PK_FunctionPointer, | |||
6724 | PK_MemberFunctionPointer, | |||
6725 | } pointerKind | |||
6726 | = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer | |||
6727 | : PK_Pointer) | |||
6728 | : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer | |||
6729 | : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; | |||
6730 | ||||
6731 | auto diag = state.getSema().Diag(attr.getLoc(), | |||
6732 | diag::warn_nullability_declspec) | |||
6733 | << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), | |||
6734 | attr.isContextSensitiveKeywordAttribute()) | |||
6735 | << type | |||
6736 | << static_cast<unsigned>(pointerKind); | |||
6737 | ||||
6738 | // FIXME: MemberPointer chunks don't carry the location of the *. | |||
6739 | if (chunk.Kind != DeclaratorChunk::MemberPointer) { | |||
6740 | diag << FixItHint::CreateRemoval(attr.getLoc()) | |||
6741 | << FixItHint::CreateInsertion( | |||
6742 | state.getSema().getPreprocessor() | |||
6743 | .getLocForEndOfToken(chunk.Loc), | |||
6744 | " " + attr.getName()->getName().str() + " "); | |||
6745 | } | |||
6746 | ||||
6747 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
6748 | chunk.getAttrs()); | |||
6749 | return true; | |||
6750 | }; | |||
6751 | ||||
6752 | // Move it to the outermost pointer, member pointer, or block | |||
6753 | // pointer declarator. | |||
6754 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
6755 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
6756 | switch (chunk.Kind) { | |||
6757 | case DeclaratorChunk::Pointer: | |||
6758 | case DeclaratorChunk::BlockPointer: | |||
6759 | case DeclaratorChunk::MemberPointer: | |||
6760 | return moveToChunk(chunk, false); | |||
6761 | ||||
6762 | case DeclaratorChunk::Paren: | |||
6763 | case DeclaratorChunk::Array: | |||
6764 | continue; | |||
6765 | ||||
6766 | case DeclaratorChunk::Function: | |||
6767 | // Try to move past the return type to a function/block/member | |||
6768 | // function pointer. | |||
6769 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | |||
6770 | declarator, i, | |||
6771 | /*onlyBlockPointers=*/false)) { | |||
6772 | return moveToChunk(*dest, true); | |||
6773 | } | |||
6774 | ||||
6775 | return false; | |||
6776 | ||||
6777 | // Don't walk through these. | |||
6778 | case DeclaratorChunk::Reference: | |||
6779 | case DeclaratorChunk::Pipe: | |||
6780 | return false; | |||
6781 | } | |||
6782 | } | |||
6783 | ||||
6784 | return false; | |||
6785 | } | |||
6786 | ||||
6787 | static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { | |||
6788 | assert(!Attr.isInvalid())((!Attr.isInvalid()) ? static_cast<void> (0) : __assert_fail ("!Attr.isInvalid()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6788, __PRETTY_FUNCTION__)); | |||
6789 | switch (Attr.getKind()) { | |||
6790 | default: | |||
6791 | llvm_unreachable("not a calling convention attribute")::llvm::llvm_unreachable_internal("not a calling convention attribute" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6791); | |||
6792 | case ParsedAttr::AT_CDecl: | |||
6793 | return createSimpleAttr<CDeclAttr>(Ctx, Attr); | |||
6794 | case ParsedAttr::AT_FastCall: | |||
6795 | return createSimpleAttr<FastCallAttr>(Ctx, Attr); | |||
6796 | case ParsedAttr::AT_StdCall: | |||
6797 | return createSimpleAttr<StdCallAttr>(Ctx, Attr); | |||
6798 | case ParsedAttr::AT_ThisCall: | |||
6799 | return createSimpleAttr<ThisCallAttr>(Ctx, Attr); | |||
6800 | case ParsedAttr::AT_RegCall: | |||
6801 | return createSimpleAttr<RegCallAttr>(Ctx, Attr); | |||
6802 | case ParsedAttr::AT_Pascal: | |||
6803 | return createSimpleAttr<PascalAttr>(Ctx, Attr); | |||
6804 | case ParsedAttr::AT_SwiftCall: | |||
6805 | return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); | |||
6806 | case ParsedAttr::AT_VectorCall: | |||
6807 | return createSimpleAttr<VectorCallAttr>(Ctx, Attr); | |||
6808 | case ParsedAttr::AT_AArch64VectorPcs: | |||
6809 | return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); | |||
6810 | case ParsedAttr::AT_Pcs: { | |||
6811 | // The attribute may have had a fixit applied where we treated an | |||
6812 | // identifier as a string literal. The contents of the string are valid, | |||
6813 | // but the form may not be. | |||
6814 | StringRef Str; | |||
6815 | if (Attr.isArgExpr(0)) | |||
6816 | Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); | |||
6817 | else | |||
6818 | Str = Attr.getArgAsIdent(0)->Ident->getName(); | |||
6819 | PcsAttr::PCSType Type; | |||
6820 | if (!PcsAttr::ConvertStrToPCSType(Str, Type)) | |||
6821 | llvm_unreachable("already validated the attribute")::llvm::llvm_unreachable_internal("already validated the attribute" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6821); | |||
6822 | return ::new (Ctx) PcsAttr(Attr.getRange(), Ctx, Type, | |||
6823 | Attr.getAttributeSpellingListIndex()); | |||
6824 | } | |||
6825 | case ParsedAttr::AT_IntelOclBicc: | |||
6826 | return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); | |||
6827 | case ParsedAttr::AT_MSABI: | |||
6828 | return createSimpleAttr<MSABIAttr>(Ctx, Attr); | |||
6829 | case ParsedAttr::AT_SysVABI: | |||
6830 | return createSimpleAttr<SysVABIAttr>(Ctx, Attr); | |||
6831 | case ParsedAttr::AT_PreserveMost: | |||
6832 | return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); | |||
6833 | case ParsedAttr::AT_PreserveAll: | |||
6834 | return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); | |||
6835 | } | |||
6836 | llvm_unreachable("unexpected attribute kind!")::llvm::llvm_unreachable_internal("unexpected attribute kind!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6836); | |||
6837 | } | |||
6838 | ||||
6839 | /// Process an individual function attribute. Returns true to | |||
6840 | /// indicate that the attribute was handled, false if it wasn't. | |||
6841 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
6842 | QualType &type) { | |||
6843 | Sema &S = state.getSema(); | |||
6844 | ||||
6845 | FunctionTypeUnwrapper unwrapped(S, type); | |||
6846 | ||||
6847 | if (attr.getKind() == ParsedAttr::AT_NoReturn) { | |||
6848 | if (S.CheckAttrNoArgs(attr)) | |||
6849 | return true; | |||
6850 | ||||
6851 | // Delay if this is not a function type. | |||
6852 | if (!unwrapped.isFunctionType()) | |||
6853 | return false; | |||
6854 | ||||
6855 | // Otherwise we can process right away. | |||
6856 | FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); | |||
6857 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6858 | return true; | |||
6859 | } | |||
6860 | ||||
6861 | // ns_returns_retained is not always a type attribute, but if we got | |||
6862 | // here, we're treating it as one right now. | |||
6863 | if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { | |||
6864 | if (attr.getNumArgs()) return true; | |||
6865 | ||||
6866 | // Delay if this is not a function type. | |||
6867 | if (!unwrapped.isFunctionType()) | |||
6868 | return false; | |||
6869 | ||||
6870 | // Check whether the return type is reasonable. | |||
6871 | if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), | |||
6872 | unwrapped.get()->getReturnType())) | |||
6873 | return true; | |||
6874 | ||||
6875 | // Only actually change the underlying type in ARC builds. | |||
6876 | QualType origType = type; | |||
6877 | if (state.getSema().getLangOpts().ObjCAutoRefCount) { | |||
6878 | FunctionType::ExtInfo EI | |||
6879 | = unwrapped.get()->getExtInfo().withProducesResult(true); | |||
6880 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6881 | } | |||
6882 | type = state.getAttributedType( | |||
6883 | createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), | |||
6884 | origType, type); | |||
6885 | return true; | |||
6886 | } | |||
6887 | ||||
6888 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { | |||
6889 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) | |||
6890 | return true; | |||
6891 | ||||
6892 | // Delay if this is not a function type. | |||
6893 | if (!unwrapped.isFunctionType()) | |||
6894 | return false; | |||
6895 | ||||
6896 | FunctionType::ExtInfo EI = | |||
6897 | unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); | |||
6898 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6899 | return true; | |||
6900 | } | |||
6901 | ||||
6902 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { | |||
6903 | if (!S.getLangOpts().CFProtectionBranch) { | |||
6904 | S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); | |||
6905 | attr.setInvalid(); | |||
6906 | return true; | |||
6907 | } | |||
6908 | ||||
6909 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) | |||
6910 | return true; | |||
6911 | ||||
6912 | // If this is not a function type, warning will be asserted by subject | |||
6913 | // check. | |||
6914 | if (!unwrapped.isFunctionType()) | |||
6915 | return true; | |||
6916 | ||||
6917 | FunctionType::ExtInfo EI = | |||
6918 | unwrapped.get()->getExtInfo().withNoCfCheck(true); | |||
6919 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6920 | return true; | |||
6921 | } | |||
6922 | ||||
6923 | if (attr.getKind() == ParsedAttr::AT_Regparm) { | |||
6924 | unsigned value; | |||
6925 | if (S.CheckRegparmAttr(attr, value)) | |||
6926 | return true; | |||
6927 | ||||
6928 | // Delay if this is not a function type. | |||
6929 | if (!unwrapped.isFunctionType()) | |||
6930 | return false; | |||
6931 | ||||
6932 | // Diagnose regparm with fastcall. | |||
6933 | const FunctionType *fn = unwrapped.get(); | |||
6934 | CallingConv CC = fn->getCallConv(); | |||
6935 | if (CC == CC_X86FastCall) { | |||
6936 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
6937 | << FunctionType::getNameForCallConv(CC) | |||
6938 | << "regparm"; | |||
6939 | attr.setInvalid(); | |||
6940 | return true; | |||
6941 | } | |||
6942 | ||||
6943 | FunctionType::ExtInfo EI = | |||
6944 | unwrapped.get()->getExtInfo().withRegParm(value); | |||
6945 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6946 | return true; | |||
6947 | } | |||
6948 | ||||
6949 | if (attr.getKind() == ParsedAttr::AT_NoThrow) { | |||
6950 | if (S.CheckAttrNoArgs(attr)) | |||
6951 | return true; | |||
6952 | ||||
6953 | // Delay if this is not a function type. | |||
6954 | if (!unwrapped.isFunctionType()) | |||
6955 | return false; | |||
6956 | ||||
6957 | // Otherwise we can process right away. | |||
6958 | auto *Proto = unwrapped.get()->getAs<FunctionProtoType>(); | |||
6959 | ||||
6960 | // In the case where this is a FunctionNoProtoType instead of a | |||
6961 | // FunctionProtoType, let the existing NoThrowAttr implementation do its | |||
6962 | // thing. | |||
6963 | if (!Proto) | |||
6964 | return false; | |||
6965 | ||||
6966 | attr.setUsedAsTypeAttr(); | |||
6967 | ||||
6968 | // MSVC ignores nothrow if it is in conflict with an explicit exception | |||
6969 | // specification. | |||
6970 | if (Proto->hasExceptionSpec()) { | |||
6971 | switch (Proto->getExceptionSpecType()) { | |||
6972 | case EST_None: | |||
6973 | llvm_unreachable("This doesn't have an exception spec!")::llvm::llvm_unreachable_internal("This doesn't have an exception spec!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 6973); | |||
6974 | ||||
6975 | case EST_DynamicNone: | |||
6976 | case EST_BasicNoexcept: | |||
6977 | case EST_NoexceptTrue: | |||
6978 | case EST_NoThrow: | |||
6979 | // Exception spec doesn't conflict with nothrow, so don't warn. | |||
6980 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
6981 | case EST_Unparsed: | |||
6982 | case EST_Uninstantiated: | |||
6983 | case EST_DependentNoexcept: | |||
6984 | case EST_Unevaluated: | |||
6985 | // We don't have enough information to properly determine if there is a | |||
6986 | // conflict, so suppress the warning. | |||
6987 | break; | |||
6988 | case EST_Dynamic: | |||
6989 | case EST_MSAny: | |||
6990 | case EST_NoexceptFalse: | |||
6991 | S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); | |||
6992 | break; | |||
6993 | } | |||
6994 | return true; | |||
6995 | } | |||
6996 | ||||
6997 | type = unwrapped.wrap( | |||
6998 | S, S.Context | |||
6999 | .getFunctionTypeWithExceptionSpec( | |||
7000 | QualType{Proto, 0}, | |||
7001 | FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) | |||
7002 | ->getAs<FunctionType>()); | |||
7003 | return true; | |||
7004 | } | |||
7005 | ||||
7006 | // Delay if the type didn't work out to a function. | |||
7007 | if (!unwrapped.isFunctionType()) return false; | |||
7008 | ||||
7009 | // Otherwise, a calling convention. | |||
7010 | CallingConv CC; | |||
7011 | if (S.CheckCallingConvAttr(attr, CC)) | |||
7012 | return true; | |||
7013 | ||||
7014 | const FunctionType *fn = unwrapped.get(); | |||
7015 | CallingConv CCOld = fn->getCallConv(); | |||
7016 | Attr *CCAttr = getCCTypeAttr(S.Context, attr); | |||
7017 | ||||
7018 | if (CCOld != CC) { | |||
7019 | // Error out on when there's already an attribute on the type | |||
7020 | // and the CCs don't match. | |||
7021 | if (S.getCallingConvAttributedType(type)) { | |||
7022 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7023 | << FunctionType::getNameForCallConv(CC) | |||
7024 | << FunctionType::getNameForCallConv(CCOld); | |||
7025 | attr.setInvalid(); | |||
7026 | return true; | |||
7027 | } | |||
7028 | } | |||
7029 | ||||
7030 | // Diagnose use of variadic functions with calling conventions that | |||
7031 | // don't support them (e.g. because they're callee-cleanup). | |||
7032 | // We delay warning about this on unprototyped function declarations | |||
7033 | // until after redeclaration checking, just in case we pick up a | |||
7034 | // prototype that way. And apparently we also "delay" warning about | |||
7035 | // unprototyped function types in general, despite not necessarily having | |||
7036 | // much ability to diagnose it later. | |||
7037 | if (!supportsVariadicCall(CC)) { | |||
7038 | const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); | |||
7039 | if (FnP && FnP->isVariadic()) { | |||
7040 | // stdcall and fastcall are ignored with a warning for GCC and MS | |||
7041 | // compatibility. | |||
7042 | if (CC == CC_X86StdCall || CC == CC_X86FastCall) | |||
7043 | return S.Diag(attr.getLoc(), diag::warn_cconv_ignored) | |||
7044 | << FunctionType::getNameForCallConv(CC) | |||
7045 | << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; | |||
7046 | ||||
7047 | attr.setInvalid(); | |||
7048 | return S.Diag(attr.getLoc(), diag::err_cconv_varargs) | |||
7049 | << FunctionType::getNameForCallConv(CC); | |||
7050 | } | |||
7051 | } | |||
7052 | ||||
7053 | // Also diagnose fastcall with regparm. | |||
7054 | if (CC == CC_X86FastCall && fn->getHasRegParm()) { | |||
7055 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7056 | << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); | |||
7057 | attr.setInvalid(); | |||
7058 | return true; | |||
7059 | } | |||
7060 | ||||
7061 | // Modify the CC from the wrapped function type, wrap it all back, and then | |||
7062 | // wrap the whole thing in an AttributedType as written. The modified type | |||
7063 | // might have a different CC if we ignored the attribute. | |||
7064 | QualType Equivalent; | |||
7065 | if (CCOld == CC) { | |||
7066 | Equivalent = type; | |||
7067 | } else { | |||
7068 | auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); | |||
7069 | Equivalent = | |||
7070 | unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7071 | } | |||
7072 | type = state.getAttributedType(CCAttr, type, Equivalent); | |||
7073 | return true; | |||
7074 | } | |||
7075 | ||||
7076 | bool Sema::hasExplicitCallingConv(QualType T) { | |||
7077 | const AttributedType *AT; | |||
7078 | ||||
7079 | // Stop if we'd be stripping off a typedef sugar node to reach the | |||
7080 | // AttributedType. | |||
7081 | while ((AT = T->getAs<AttributedType>()) && | |||
7082 | AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { | |||
7083 | if (AT->isCallingConv()) | |||
7084 | return true; | |||
7085 | T = AT->getModifiedType(); | |||
7086 | } | |||
7087 | return false; | |||
7088 | } | |||
7089 | ||||
7090 | void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, | |||
7091 | SourceLocation Loc) { | |||
7092 | FunctionTypeUnwrapper Unwrapped(*this, T); | |||
7093 | const FunctionType *FT = Unwrapped.get(); | |||
7094 | bool IsVariadic = (isa<FunctionProtoType>(FT) && | |||
7095 | cast<FunctionProtoType>(FT)->isVariadic()); | |||
7096 | CallingConv CurCC = FT->getCallConv(); | |||
7097 | CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); | |||
7098 | ||||
7099 | if (CurCC == ToCC) | |||
7100 | return; | |||
7101 | ||||
7102 | // MS compiler ignores explicit calling convention attributes on structors. We | |||
7103 | // should do the same. | |||
7104 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { | |||
7105 | // Issue a warning on ignored calling convention -- except of __stdcall. | |||
7106 | // Again, this is what MS compiler does. | |||
7107 | if (CurCC != CC_X86StdCall) | |||
7108 | Diag(Loc, diag::warn_cconv_ignored) | |||
7109 | << FunctionType::getNameForCallConv(CurCC) | |||
7110 | << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; | |||
7111 | // Default adjustment. | |||
7112 | } else { | |||
7113 | // Only adjust types with the default convention. For example, on Windows | |||
7114 | // we should adjust a __cdecl type to __thiscall for instance methods, and a | |||
7115 | // __thiscall type to __cdecl for static methods. | |||
7116 | CallingConv DefaultCC = | |||
7117 | Context.getDefaultCallingConvention(IsVariadic, IsStatic); | |||
7118 | ||||
7119 | if (CurCC != DefaultCC || DefaultCC == ToCC) | |||
7120 | return; | |||
7121 | ||||
7122 | if (hasExplicitCallingConv(T)) | |||
7123 | return; | |||
7124 | } | |||
7125 | ||||
7126 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); | |||
7127 | QualType Wrapped = Unwrapped.wrap(*this, FT); | |||
7128 | T = Context.getAdjustedType(T, Wrapped); | |||
7129 | } | |||
7130 | ||||
7131 | /// HandleVectorSizeAttribute - this attribute is only applicable to integral | |||
7132 | /// and float scalars, although arrays, pointers, and function return values are | |||
7133 | /// allowed in conjunction with this construct. Aggregates with this attribute | |||
7134 | /// are invalid, even if they are of the same size as a corresponding scalar. | |||
7135 | /// The raw attribute should contain precisely 1 argument, the vector size for | |||
7136 | /// the variable, measured in bytes. If curType and rawAttr are well formed, | |||
7137 | /// this routine will return a new vector type. | |||
7138 | static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
7139 | Sema &S) { | |||
7140 | // Check the attribute arguments. | |||
7141 | if (Attr.getNumArgs() != 1) { | |||
7142 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
7143 | << 1; | |||
7144 | Attr.setInvalid(); | |||
7145 | return; | |||
7146 | } | |||
7147 | ||||
7148 | Expr *SizeExpr; | |||
7149 | // Special case where the argument is a template id. | |||
7150 | if (Attr.isArgIdent(0)) { | |||
7151 | CXXScopeSpec SS; | |||
7152 | SourceLocation TemplateKWLoc; | |||
7153 | UnqualifiedId Id; | |||
7154 | Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); | |||
7155 | ||||
7156 | ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, | |||
7157 | Id, /*HasTrailingLParen=*/false, | |||
7158 | /*IsAddressOfOperand=*/false); | |||
7159 | ||||
7160 | if (Size.isInvalid()) | |||
7161 | return; | |||
7162 | SizeExpr = Size.get(); | |||
7163 | } else { | |||
7164 | SizeExpr = Attr.getArgAsExpr(0); | |||
7165 | } | |||
7166 | ||||
7167 | QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); | |||
7168 | if (!T.isNull()) | |||
7169 | CurType = T; | |||
7170 | else | |||
7171 | Attr.setInvalid(); | |||
7172 | } | |||
7173 | ||||
7174 | /// Process the OpenCL-like ext_vector_type attribute when it occurs on | |||
7175 | /// a type. | |||
7176 | static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
7177 | Sema &S) { | |||
7178 | // check the attribute arguments. | |||
7179 | if (Attr.getNumArgs() != 1) { | |||
7180 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
7181 | << 1; | |||
7182 | return; | |||
7183 | } | |||
7184 | ||||
7185 | Expr *sizeExpr; | |||
7186 | ||||
7187 | // Special case where the argument is a template id. | |||
7188 | if (Attr.isArgIdent(0)) { | |||
7189 | CXXScopeSpec SS; | |||
7190 | SourceLocation TemplateKWLoc; | |||
7191 | UnqualifiedId id; | |||
7192 | id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); | |||
7193 | ||||
7194 | ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, | |||
7195 | id, /*HasTrailingLParen=*/false, | |||
7196 | /*IsAddressOfOperand=*/false); | |||
7197 | if (Size.isInvalid()) | |||
7198 | return; | |||
7199 | ||||
7200 | sizeExpr = Size.get(); | |||
7201 | } else { | |||
7202 | sizeExpr = Attr.getArgAsExpr(0); | |||
7203 | } | |||
7204 | ||||
7205 | // Create the vector type. | |||
7206 | QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); | |||
7207 | if (!T.isNull()) | |||
7208 | CurType = T; | |||
7209 | } | |||
7210 | ||||
7211 | static bool isPermittedNeonBaseType(QualType &Ty, | |||
7212 | VectorType::VectorKind VecKind, Sema &S) { | |||
7213 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
7214 | if (!BTy) | |||
7215 | return false; | |||
7216 | ||||
7217 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); | |||
7218 | ||||
7219 | // Signed poly is mathematically wrong, but has been baked into some ABIs by | |||
7220 | // now. | |||
7221 | bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || | |||
7222 | Triple.getArch() == llvm::Triple::aarch64_be; | |||
7223 | if (VecKind == VectorType::NeonPolyVector) { | |||
7224 | if (IsPolyUnsigned) { | |||
7225 | // AArch64 polynomial vectors are unsigned and support poly64. | |||
7226 | return BTy->getKind() == BuiltinType::UChar || | |||
7227 | BTy->getKind() == BuiltinType::UShort || | |||
7228 | BTy->getKind() == BuiltinType::ULong || | |||
7229 | BTy->getKind() == BuiltinType::ULongLong; | |||
7230 | } else { | |||
7231 | // AArch32 polynomial vector are signed. | |||
7232 | return BTy->getKind() == BuiltinType::SChar || | |||
7233 | BTy->getKind() == BuiltinType::Short; | |||
7234 | } | |||
7235 | } | |||
7236 | ||||
7237 | // Non-polynomial vector types: the usual suspects are allowed, as well as | |||
7238 | // float64_t on AArch64. | |||
7239 | bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || | |||
7240 | Triple.getArch() == llvm::Triple::aarch64_be; | |||
7241 | ||||
7242 | if (Is64Bit && BTy->getKind() == BuiltinType::Double) | |||
7243 | return true; | |||
7244 | ||||
7245 | return BTy->getKind() == BuiltinType::SChar || | |||
7246 | BTy->getKind() == BuiltinType::UChar || | |||
7247 | BTy->getKind() == BuiltinType::Short || | |||
7248 | BTy->getKind() == BuiltinType::UShort || | |||
7249 | BTy->getKind() == BuiltinType::Int || | |||
7250 | BTy->getKind() == BuiltinType::UInt || | |||
7251 | BTy->getKind() == BuiltinType::Long || | |||
7252 | BTy->getKind() == BuiltinType::ULong || | |||
7253 | BTy->getKind() == BuiltinType::LongLong || | |||
7254 | BTy->getKind() == BuiltinType::ULongLong || | |||
7255 | BTy->getKind() == BuiltinType::Float || | |||
7256 | BTy->getKind() == BuiltinType::Half; | |||
7257 | } | |||
7258 | ||||
7259 | /// HandleNeonVectorTypeAttr - The "neon_vector_type" and | |||
7260 | /// "neon_polyvector_type" attributes are used to create vector types that | |||
7261 | /// are mangled according to ARM's ABI. Otherwise, these types are identical | |||
7262 | /// to those created with the "vector_size" attribute. Unlike "vector_size" | |||
7263 | /// the argument to these Neon attributes is the number of vector elements, | |||
7264 | /// not the vector size in bytes. The vector width and element type must | |||
7265 | /// match one of the standard Neon vector types. | |||
7266 | static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
7267 | Sema &S, VectorType::VectorKind VecKind) { | |||
7268 | // Target must have NEON | |||
7269 | if (!S.Context.getTargetInfo().hasFeature("neon")) { | |||
7270 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr; | |||
7271 | Attr.setInvalid(); | |||
7272 | return; | |||
7273 | } | |||
7274 | // Check the attribute arguments. | |||
7275 | if (Attr.getNumArgs() != 1) { | |||
7276 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
7277 | << 1; | |||
7278 | Attr.setInvalid(); | |||
7279 | return; | |||
7280 | } | |||
7281 | // The number of elements must be an ICE. | |||
7282 | Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); | |||
7283 | llvm::APSInt numEltsInt(32); | |||
7284 | if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || | |||
7285 | !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { | |||
7286 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) | |||
7287 | << Attr << AANT_ArgumentIntegerConstant | |||
7288 | << numEltsExpr->getSourceRange(); | |||
7289 | Attr.setInvalid(); | |||
7290 | return; | |||
7291 | } | |||
7292 | // Only certain element types are supported for Neon vectors. | |||
7293 | if (!isPermittedNeonBaseType(CurType, VecKind, S)) { | |||
7294 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; | |||
7295 | Attr.setInvalid(); | |||
7296 | return; | |||
7297 | } | |||
7298 | ||||
7299 | // The total size of the vector must be 64 or 128 bits. | |||
7300 | unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); | |||
7301 | unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); | |||
7302 | unsigned vecSize = typeSize * numElts; | |||
7303 | if (vecSize != 64 && vecSize != 128) { | |||
7304 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; | |||
7305 | Attr.setInvalid(); | |||
7306 | return; | |||
7307 | } | |||
7308 | ||||
7309 | CurType = S.Context.getVectorType(CurType, numElts, VecKind); | |||
7310 | } | |||
7311 | ||||
7312 | /// Handle OpenCL Access Qualifier Attribute. | |||
7313 | static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, | |||
7314 | Sema &S) { | |||
7315 | // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. | |||
7316 | if (!(CurType->isImageType() || CurType->isPipeType())) { | |||
7317 | S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); | |||
7318 | Attr.setInvalid(); | |||
7319 | return; | |||
7320 | } | |||
7321 | ||||
7322 | if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { | |||
7323 | QualType BaseTy = TypedefTy->desugar(); | |||
7324 | ||||
7325 | std::string PrevAccessQual; | |||
7326 | if (BaseTy->isPipeType()) { | |||
7327 | if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { | |||
7328 | OpenCLAccessAttr *Attr = | |||
7329 | TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); | |||
7330 | PrevAccessQual = Attr->getSpelling(); | |||
7331 | } else { | |||
7332 | PrevAccessQual = "read_only"; | |||
7333 | } | |||
7334 | } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { | |||
7335 | ||||
7336 | switch (ImgType->getKind()) { | |||
7337 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
7338 | case BuiltinType::Id: \ | |||
7339 | PrevAccessQual = #Access; \ | |||
7340 | break; | |||
7341 | #include "clang/Basic/OpenCLImageTypes.def" | |||
7342 | default: | |||
7343 | llvm_unreachable("Unable to find corresponding image type.")::llvm::llvm_unreachable_internal("Unable to find corresponding image type." , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 7343); | |||
7344 | } | |||
7345 | } else { | |||
7346 | llvm_unreachable("unexpected type")::llvm::llvm_unreachable_internal("unexpected type", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 7346); | |||
7347 | } | |||
7348 | StringRef AttrName = Attr.getName()->getName(); | |||
7349 | if (PrevAccessQual == AttrName.ltrim("_")) { | |||
7350 | // Duplicated qualifiers | |||
7351 | S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) | |||
7352 | << AttrName << Attr.getRange(); | |||
7353 | } else { | |||
7354 | // Contradicting qualifiers | |||
7355 | S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); | |||
7356 | } | |||
7357 | ||||
7358 | S.Diag(TypedefTy->getDecl()->getBeginLoc(), | |||
7359 | diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; | |||
7360 | } else if (CurType->isPipeType()) { | |||
7361 | if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { | |||
7362 | QualType ElemType = CurType->getAs<PipeType>()->getElementType(); | |||
7363 | CurType = S.Context.getWritePipeType(ElemType); | |||
7364 | } | |||
7365 | } | |||
7366 | } | |||
7367 | ||||
7368 | static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State, | |||
7369 | QualType &T, TypeAttrLocation TAL) { | |||
7370 | Declarator &D = State.getDeclarator(); | |||
7371 | ||||
7372 | // Handle the cases where address space should not be deduced. | |||
7373 | // | |||
7374 | // The pointee type of a pointer type is always deduced since a pointer always | |||
7375 | // points to some memory location which should has an address space. | |||
7376 | // | |||
7377 | // There are situations that at the point of certain declarations, the address | |||
7378 | // space may be unknown and better to be left as default. For example, when | |||
7379 | // defining a typedef or struct type, they are not associated with any | |||
7380 | // specific address space. Later on, they may be used with any address space | |||
7381 | // to declare a variable. | |||
7382 | // | |||
7383 | // The return value of a function is r-value, therefore should not have | |||
7384 | // address space. | |||
7385 | // | |||
7386 | // The void type does not occupy memory, therefore should not have address | |||
7387 | // space, except when it is used as a pointee type. | |||
7388 | // | |||
7389 | // Since LLVM assumes function type is in default address space, it should not | |||
7390 | // have address space. | |||
7391 | auto ChunkIndex = State.getCurrentChunkIndex(); | |||
7392 | bool IsPointee = | |||
7393 | ChunkIndex > 0 && | |||
7394 | (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer || | |||
7395 | D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer || | |||
7396 | D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference); | |||
7397 | bool IsFuncReturnType = | |||
7398 | ChunkIndex > 0 && | |||
7399 | D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function; | |||
7400 | bool IsFuncType = | |||
7401 | ChunkIndex < D.getNumTypeObjects() && | |||
7402 | D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function; | |||
7403 | if ( // Do not deduce addr space for function return type and function type, | |||
7404 | // otherwise it will fail some sema check. | |||
7405 | IsFuncReturnType || IsFuncType || | |||
7406 | // Do not deduce addr space for member types of struct, except the pointee | |||
7407 | // type of a pointer member type or static data members. | |||
7408 | (D.getContext() == DeclaratorContext::MemberContext && | |||
7409 | (!IsPointee && | |||
7410 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)) || | |||
7411 | // Do not deduce addr space for types used to define a typedef and the | |||
7412 | // typedef itself, except the pointee type of a pointer type which is used | |||
7413 | // to define the typedef. | |||
7414 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef && | |||
7415 | !IsPointee) || | |||
7416 | // Do not deduce addr space of the void type, e.g. in f(void), otherwise | |||
7417 | // it will fail some sema check. | |||
7418 | (T->isVoidType() && !IsPointee) || | |||
7419 | // Do not deduce addr spaces for dependent types because they might end | |||
7420 | // up instantiating to a type with an explicit address space qualifier. | |||
7421 | T->isDependentType() || | |||
7422 | // Do not deduce addr space of decltype because it will be taken from | |||
7423 | // its argument. | |||
7424 | T->isDecltypeType() || | |||
7425 | // OpenCL spec v2.0 s6.9.b: | |||
7426 | // The sampler type cannot be used with the __local and __global address | |||
7427 | // space qualifiers. | |||
7428 | // OpenCL spec v2.0 s6.13.14: | |||
7429 | // Samplers can also be declared as global constants in the program | |||
7430 | // source using the following syntax. | |||
7431 | // const sampler_t <sampler name> = <value> | |||
7432 | // In codegen, file-scope sampler type variable has special handing and | |||
7433 | // does not rely on address space qualifier. On the other hand, deducing | |||
7434 | // address space of const sampler file-scope variable as global address | |||
7435 | // space causes spurious diagnostic about __global address space | |||
7436 | // qualifier, therefore do not deduce address space of file-scope sampler | |||
7437 | // type variable. | |||
7438 | (D.getContext() == DeclaratorContext::FileContext && T->isSamplerT())) | |||
7439 | return; | |||
7440 | ||||
7441 | LangAS ImpAddr = LangAS::Default; | |||
7442 | // Put OpenCL automatic variable in private address space. | |||
7443 | // OpenCL v1.2 s6.5: | |||
7444 | // The default address space name for arguments to a function in a | |||
7445 | // program, or local variables of a function is __private. All function | |||
7446 | // arguments shall be in the __private address space. | |||
7447 | if (State.getSema().getLangOpts().OpenCLVersion <= 120 && | |||
7448 | !State.getSema().getLangOpts().OpenCLCPlusPlus) { | |||
7449 | ImpAddr = LangAS::opencl_private; | |||
7450 | } else { | |||
7451 | // If address space is not set, OpenCL 2.0 defines non private default | |||
7452 | // address spaces for some cases: | |||
7453 | // OpenCL 2.0, section 6.5: | |||
7454 | // The address space for a variable at program scope or a static variable | |||
7455 | // inside a function can either be __global or __constant, but defaults to | |||
7456 | // __global if not specified. | |||
7457 | // (...) | |||
7458 | // Pointers that are declared without pointing to a named address space | |||
7459 | // point to the generic address space. | |||
7460 | if (IsPointee) { | |||
7461 | ImpAddr = LangAS::opencl_generic; | |||
7462 | } else { | |||
7463 | if (D.getContext() == DeclaratorContext::TemplateArgContext) { | |||
7464 | // Do not deduce address space for non-pointee type in template arg. | |||
7465 | } else if (D.getContext() == DeclaratorContext::FileContext) { | |||
7466 | ImpAddr = LangAS::opencl_global; | |||
7467 | } else { | |||
7468 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || | |||
7469 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) { | |||
7470 | ImpAddr = LangAS::opencl_global; | |||
7471 | } else { | |||
7472 | ImpAddr = LangAS::opencl_private; | |||
7473 | } | |||
7474 | } | |||
7475 | } | |||
7476 | } | |||
7477 | T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr); | |||
7478 | } | |||
7479 | ||||
7480 | static void HandleLifetimeBoundAttr(TypeProcessingState &State, | |||
7481 | QualType &CurType, | |||
7482 | ParsedAttr &Attr) { | |||
7483 | if (State.getDeclarator().isDeclarationOfFunction()) { | |||
7484 | CurType = State.getAttributedType( | |||
7485 | createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), | |||
7486 | CurType, CurType); | |||
7487 | } else { | |||
7488 | Attr.diagnoseAppertainsTo(State.getSema(), nullptr); | |||
7489 | } | |||
7490 | } | |||
7491 | ||||
7492 | ||||
7493 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, | |||
7494 | TypeAttrLocation TAL, | |||
7495 | ParsedAttributesView &attrs) { | |||
7496 | // Scan through and apply attributes to this type where it makes sense. Some | |||
7497 | // attributes (such as __address_space__, __vector_size__, etc) apply to the | |||
7498 | // type, but others can be present in the type specifiers even though they | |||
7499 | // apply to the decl. Here we apply type attributes and ignore the rest. | |||
7500 | ||||
7501 | // This loop modifies the list pretty frequently, but we still need to make | |||
7502 | // sure we visit every element once. Copy the attributes list, and iterate | |||
7503 | // over that. | |||
7504 | ParsedAttributesView AttrsCopy{attrs}; | |||
7505 | ||||
7506 | state.setParsedNoDeref(false); | |||
7507 | ||||
7508 | for (ParsedAttr &attr : AttrsCopy) { | |||
7509 | ||||
7510 | // Skip attributes that were marked to be invalid. | |||
7511 | if (attr.isInvalid()) | |||
7512 | continue; | |||
7513 | ||||
7514 | if (attr.isCXX11Attribute()) { | |||
7515 | // [[gnu::...]] attributes are treated as declaration attributes, so may | |||
7516 | // not appertain to a DeclaratorChunk. If we handle them as type | |||
7517 | // attributes, accept them in that position and diagnose the GCC | |||
7518 | // incompatibility. | |||
7519 | if (attr.isGNUScope()) { | |||
7520 | bool IsTypeAttr = attr.isTypeAttr(); | |||
7521 | if (TAL == TAL_DeclChunk) { | |||
7522 | state.getSema().Diag(attr.getLoc(), | |||
7523 | IsTypeAttr | |||
7524 | ? diag::warn_gcc_ignores_type_attr | |||
7525 | : diag::warn_cxx11_gnu_attribute_on_type) | |||
7526 | << attr.getName(); | |||
7527 | if (!IsTypeAttr) | |||
7528 | continue; | |||
7529 | } | |||
7530 | } else if (TAL != TAL_DeclChunk && | |||
7531 | attr.getKind() != ParsedAttr::AT_AddressSpace) { | |||
7532 | // Otherwise, only consider type processing for a C++11 attribute if | |||
7533 | // it's actually been applied to a type. | |||
7534 | // We also allow C++11 address_space attributes to pass through. | |||
7535 | continue; | |||
7536 | } | |||
7537 | } | |||
7538 | ||||
7539 | // If this is an attribute we can handle, do so now, | |||
7540 | // otherwise, add it to the FnAttrs list for rechaining. | |||
7541 | switch (attr.getKind()) { | |||
7542 | default: | |||
7543 | // A C++11 attribute on a declarator chunk must appertain to a type. | |||
7544 | if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { | |||
7545 | state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) | |||
7546 | << attr; | |||
7547 | attr.setUsedAsTypeAttr(); | |||
7548 | } | |||
7549 | break; | |||
7550 | ||||
7551 | case ParsedAttr::UnknownAttribute: | |||
7552 | if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) | |||
7553 | state.getSema().Diag(attr.getLoc(), | |||
7554 | diag::warn_unknown_attribute_ignored) | |||
7555 | << attr.getName(); | |||
7556 | break; | |||
7557 | ||||
7558 | case ParsedAttr::IgnoredAttribute: | |||
7559 | break; | |||
7560 | ||||
7561 | case ParsedAttr::AT_MayAlias: | |||
7562 | // FIXME: This attribute needs to actually be handled, but if we ignore | |||
7563 | // it it breaks large amounts of Linux software. | |||
7564 | attr.setUsedAsTypeAttr(); | |||
7565 | break; | |||
7566 | case ParsedAttr::AT_OpenCLPrivateAddressSpace: | |||
7567 | case ParsedAttr::AT_OpenCLGlobalAddressSpace: | |||
7568 | case ParsedAttr::AT_OpenCLLocalAddressSpace: | |||
7569 | case ParsedAttr::AT_OpenCLConstantAddressSpace: | |||
7570 | case ParsedAttr::AT_OpenCLGenericAddressSpace: | |||
7571 | case ParsedAttr::AT_AddressSpace: | |||
7572 | HandleAddressSpaceTypeAttribute(type, attr, state); | |||
7573 | attr.setUsedAsTypeAttr(); | |||
7574 | break; | |||
7575 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: | |||
7576 | if (!handleObjCPointerTypeAttr(state, attr, type)) | |||
7577 | distributeObjCPointerTypeAttr(state, attr, type); | |||
7578 | attr.setUsedAsTypeAttr(); | |||
7579 | break; | |||
7580 | case ParsedAttr::AT_VectorSize: | |||
7581 | HandleVectorSizeAttr(type, attr, state.getSema()); | |||
7582 | attr.setUsedAsTypeAttr(); | |||
7583 | break; | |||
7584 | case ParsedAttr::AT_ExtVectorType: | |||
7585 | HandleExtVectorTypeAttr(type, attr, state.getSema()); | |||
7586 | attr.setUsedAsTypeAttr(); | |||
7587 | break; | |||
7588 | case ParsedAttr::AT_NeonVectorType: | |||
7589 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | |||
7590 | VectorType::NeonVector); | |||
7591 | attr.setUsedAsTypeAttr(); | |||
7592 | break; | |||
7593 | case ParsedAttr::AT_NeonPolyVectorType: | |||
7594 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | |||
7595 | VectorType::NeonPolyVector); | |||
7596 | attr.setUsedAsTypeAttr(); | |||
7597 | break; | |||
7598 | case ParsedAttr::AT_OpenCLAccess: | |||
7599 | HandleOpenCLAccessAttr(type, attr, state.getSema()); | |||
7600 | attr.setUsedAsTypeAttr(); | |||
7601 | break; | |||
7602 | case ParsedAttr::AT_LifetimeBound: | |||
7603 | if (TAL == TAL_DeclChunk) | |||
7604 | HandleLifetimeBoundAttr(state, type, attr); | |||
7605 | break; | |||
7606 | ||||
7607 | case ParsedAttr::AT_NoDeref: { | |||
7608 | ASTContext &Ctx = state.getSema().Context; | |||
7609 | type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), | |||
7610 | type, type); | |||
7611 | attr.setUsedAsTypeAttr(); | |||
7612 | state.setParsedNoDeref(true); | |||
7613 | break; | |||
7614 | } | |||
7615 | ||||
7616 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: | |||
7617 | if (!handleMSPointerTypeQualifierAttr(state, attr, type)) | |||
7618 | attr.setUsedAsTypeAttr(); | |||
7619 | break; | |||
7620 | ||||
7621 | ||||
7622 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullUnspecified: | |||
7623 | // Either add nullability here or try to distribute it. We | |||
7624 | // don't want to distribute the nullability specifier past any | |||
7625 | // dependent type, because that complicates the user model. | |||
7626 | if (type->canHaveNullability() || type->isDependentType() || | |||
7627 | type->isArrayType() || | |||
7628 | !distributeNullabilityTypeAttr(state, type, attr)) { | |||
7629 | unsigned endIndex; | |||
7630 | if (TAL == TAL_DeclChunk) | |||
7631 | endIndex = state.getCurrentChunkIndex(); | |||
7632 | else | |||
7633 | endIndex = state.getDeclarator().getNumTypeObjects(); | |||
7634 | bool allowOnArrayType = | |||
7635 | state.getDeclarator().isPrototypeContext() && | |||
7636 | !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); | |||
7637 | if (checkNullabilityTypeSpecifier( | |||
7638 | state, | |||
7639 | type, | |||
7640 | attr, | |||
7641 | allowOnArrayType)) { | |||
7642 | attr.setInvalid(); | |||
7643 | } | |||
7644 | ||||
7645 | attr.setUsedAsTypeAttr(); | |||
7646 | } | |||
7647 | break; | |||
7648 | ||||
7649 | case ParsedAttr::AT_ObjCKindOf: | |||
7650 | // '__kindof' must be part of the decl-specifiers. | |||
7651 | switch (TAL) { | |||
7652 | case TAL_DeclSpec: | |||
7653 | break; | |||
7654 | ||||
7655 | case TAL_DeclChunk: | |||
7656 | case TAL_DeclName: | |||
7657 | state.getSema().Diag(attr.getLoc(), | |||
7658 | diag::err_objc_kindof_wrong_position) | |||
7659 | << FixItHint::CreateRemoval(attr.getLoc()) | |||
7660 | << FixItHint::CreateInsertion( | |||
7661 | state.getDeclarator().getDeclSpec().getBeginLoc(), | |||
7662 | "__kindof "); | |||
7663 | break; | |||
7664 | } | |||
7665 | ||||
7666 | // Apply it regardless. | |||
7667 | if (checkObjCKindOfType(state, type, attr)) | |||
7668 | attr.setInvalid(); | |||
7669 | break; | |||
7670 | ||||
7671 | 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_NoThrow : 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: | |||
7672 | attr.setUsedAsTypeAttr(); | |||
7673 | ||||
7674 | // Never process function type attributes as part of the | |||
7675 | // declaration-specifiers. | |||
7676 | if (TAL == TAL_DeclSpec) | |||
7677 | distributeFunctionTypeAttrFromDeclSpec(state, attr, type); | |||
7678 | ||||
7679 | // Otherwise, handle the possible delays. | |||
7680 | else if (!handleFunctionTypeAttr(state, attr, type)) | |||
7681 | distributeFunctionTypeAttr(state, attr, type); | |||
7682 | break; | |||
7683 | } | |||
7684 | ||||
7685 | // Handle attributes that are defined in a macro. We do not want this to be | |||
7686 | // applied to ObjC builtin attributes. | |||
7687 | if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && | |||
7688 | !type.getQualifiers().hasObjCLifetime() && | |||
7689 | !type.getQualifiers().hasObjCGCAttr() && | |||
7690 | attr.getKind() != ParsedAttr::AT_ObjCGC && | |||
7691 | attr.getKind() != ParsedAttr::AT_ObjCOwnership) { | |||
7692 | const IdentifierInfo *MacroII = attr.getMacroIdentifier(); | |||
7693 | type = state.getSema().Context.getMacroQualifiedType(type, MacroII); | |||
7694 | state.setExpansionLocForMacroQualifiedType( | |||
7695 | cast<MacroQualifiedType>(type.getTypePtr()), | |||
7696 | attr.getMacroExpansionLoc()); | |||
7697 | } | |||
7698 | } | |||
7699 | ||||
7700 | if (!state.getSema().getLangOpts().OpenCL || | |||
7701 | type.getAddressSpace() != LangAS::Default) | |||
7702 | return; | |||
7703 | ||||
7704 | deduceOpenCLImplicitAddrSpace(state, type, TAL); | |||
7705 | } | |||
7706 | ||||
7707 | void Sema::completeExprArrayBound(Expr *E) { | |||
7708 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
7709 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
7710 | if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { | |||
7711 | auto *Def = Var->getDefinition(); | |||
7712 | if (!Def) { | |||
7713 | SourceLocation PointOfInstantiation = E->getExprLoc(); | |||
7714 | InstantiateVariableDefinition(PointOfInstantiation, Var); | |||
7715 | Def = Var->getDefinition(); | |||
7716 | ||||
7717 | // If we don't already have a point of instantiation, and we managed | |||
7718 | // to instantiate a definition, this is the point of instantiation. | |||
7719 | // Otherwise, we don't request an end-of-TU instantiation, so this is | |||
7720 | // not a point of instantiation. | |||
7721 | // FIXME: Is this really the right behavior? | |||
7722 | if (Var->getPointOfInstantiation().isInvalid() && Def) { | |||
7723 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 7725, __PRETTY_FUNCTION__)) | |||
7724 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 7725, __PRETTY_FUNCTION__)) | |||
7725 | "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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 7725, __PRETTY_FUNCTION__)); | |||
7726 | Var->setTemplateSpecializationKind( | |||
7727 | Var->getTemplateSpecializationKind(), PointOfInstantiation); | |||
7728 | } | |||
7729 | } | |||
7730 | ||||
7731 | // Update the type to the definition's type both here and within the | |||
7732 | // expression. | |||
7733 | if (Def) { | |||
7734 | DRE->setDecl(Def); | |||
7735 | QualType T = Def->getType(); | |||
7736 | DRE->setType(T); | |||
7737 | // FIXME: Update the type on all intervening expressions. | |||
7738 | E->setType(T); | |||
7739 | } | |||
7740 | ||||
7741 | // We still go on to try to complete the type independently, as it | |||
7742 | // may also require instantiations or diagnostics if it remains | |||
7743 | // incomplete. | |||
7744 | } | |||
7745 | } | |||
7746 | } | |||
7747 | } | |||
7748 | ||||
7749 | /// Ensure that the type of the given expression is complete. | |||
7750 | /// | |||
7751 | /// This routine checks whether the expression \p E has a complete type. If the | |||
7752 | /// expression refers to an instantiable construct, that instantiation is | |||
7753 | /// performed as needed to complete its type. Furthermore | |||
7754 | /// Sema::RequireCompleteType is called for the expression's type (or in the | |||
7755 | /// case of a reference type, the referred-to type). | |||
7756 | /// | |||
7757 | /// \param E The expression whose type is required to be complete. | |||
7758 | /// \param Diagnoser The object that will emit a diagnostic if the type is | |||
7759 | /// incomplete. | |||
7760 | /// | |||
7761 | /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false | |||
7762 | /// otherwise. | |||
7763 | bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { | |||
7764 | QualType T = E->getType(); | |||
7765 | ||||
7766 | // Incomplete array types may be completed by the initializer attached to | |||
7767 | // their definitions. For static data members of class templates and for | |||
7768 | // variable templates, we need to instantiate the definition to get this | |||
7769 | // initializer and complete the type. | |||
7770 | if (T->isIncompleteArrayType()) { | |||
7771 | completeExprArrayBound(E); | |||
7772 | T = E->getType(); | |||
7773 | } | |||
7774 | ||||
7775 | // FIXME: Are there other cases which require instantiating something other | |||
7776 | // than the type to complete the type of an expression? | |||
7777 | ||||
7778 | return RequireCompleteType(E->getExprLoc(), T, Diagnoser); | |||
7779 | } | |||
7780 | ||||
7781 | bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { | |||
7782 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
7783 | return RequireCompleteExprType(E, Diagnoser); | |||
7784 | } | |||
7785 | ||||
7786 | /// Ensure that the type T is a complete type. | |||
7787 | /// | |||
7788 | /// This routine checks whether the type @p T is complete in any | |||
7789 | /// context where a complete type is required. If @p T is a complete | |||
7790 | /// type, returns false. If @p T is a class template specialization, | |||
7791 | /// this routine then attempts to perform class template | |||
7792 | /// instantiation. If instantiation fails, or if @p T is incomplete | |||
7793 | /// and cannot be completed, issues the diagnostic @p diag (giving it | |||
7794 | /// the type @p T) and returns true. | |||
7795 | /// | |||
7796 | /// @param Loc The location in the source that the incomplete type | |||
7797 | /// diagnostic should refer to. | |||
7798 | /// | |||
7799 | /// @param T The type that this routine is examining for completeness. | |||
7800 | /// | |||
7801 | /// @returns @c true if @p T is incomplete and a diagnostic was emitted, | |||
7802 | /// @c false otherwise. | |||
7803 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | |||
7804 | TypeDiagnoser &Diagnoser) { | |||
7805 | if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) | |||
7806 | return true; | |||
7807 | if (const TagType *Tag = T->getAs<TagType>()) { | |||
7808 | if (!Tag->getDecl()->isCompleteDefinitionRequired()) { | |||
7809 | Tag->getDecl()->setCompleteDefinitionRequired(); | |||
7810 | Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); | |||
7811 | } | |||
7812 | } | |||
7813 | return false; | |||
7814 | } | |||
7815 | ||||
7816 | bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { | |||
7817 | llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; | |||
7818 | if (!Suggested) | |||
7819 | return false; | |||
7820 | ||||
7821 | // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext | |||
7822 | // and isolate from other C++ specific checks. | |||
7823 | StructuralEquivalenceContext Ctx( | |||
7824 | D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, | |||
7825 | StructuralEquivalenceKind::Default, | |||
7826 | false /*StrictTypeSpelling*/, true /*Complain*/, | |||
7827 | true /*ErrorOnTagTypeMismatch*/); | |||
7828 | return Ctx.IsEquivalent(D, Suggested); | |||
7829 | } | |||
7830 | ||||
7831 | /// Determine whether there is any declaration of \p D that was ever a | |||
7832 | /// definition (perhaps before module merging) and is currently visible. | |||
7833 | /// \param D The definition of the entity. | |||
7834 | /// \param Suggested Filled in with the declaration that should be made visible | |||
7835 | /// in order to provide a definition of this entity. | |||
7836 | /// \param OnlyNeedComplete If \c true, we only need the type to be complete, | |||
7837 | /// not defined. This only matters for enums with a fixed underlying | |||
7838 | /// type, since in all other cases, a type is complete if and only if it | |||
7839 | /// is defined. | |||
7840 | bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, | |||
7841 | bool OnlyNeedComplete) { | |||
7842 | // Easy case: if we don't have modules, all declarations are visible. | |||
7843 | if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) | |||
7844 | return true; | |||
7845 | ||||
7846 | // If this definition was instantiated from a template, map back to the | |||
7847 | // pattern from which it was instantiated. | |||
7848 | if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { | |||
7849 | // We're in the middle of defining it; this definition should be treated | |||
7850 | // as visible. | |||
7851 | return true; | |||
7852 | } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { | |||
7853 | if (auto *Pattern = RD->getTemplateInstantiationPattern()) | |||
7854 | RD = Pattern; | |||
7855 | D = RD->getDefinition(); | |||
7856 | } else if (auto *ED = dyn_cast<EnumDecl>(D)) { | |||
7857 | if (auto *Pattern = ED->getTemplateInstantiationPattern()) | |||
7858 | ED = Pattern; | |||
7859 | if (OnlyNeedComplete && ED->isFixed()) { | |||
7860 | // If the enum has a fixed underlying type, and we're only looking for a | |||
7861 | // complete type (not a definition), any visible declaration of it will | |||
7862 | // do. | |||
7863 | *Suggested = nullptr; | |||
7864 | for (auto *Redecl : ED->redecls()) { | |||
7865 | if (isVisible(Redecl)) | |||
7866 | return true; | |||
7867 | if (Redecl->isThisDeclarationADefinition() || | |||
7868 | (Redecl->isCanonicalDecl() && !*Suggested)) | |||
7869 | *Suggested = Redecl; | |||
7870 | } | |||
7871 | return false; | |||
7872 | } | |||
7873 | D = ED->getDefinition(); | |||
7874 | } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
7875 | if (auto *Pattern = FD->getTemplateInstantiationPattern()) | |||
7876 | FD = Pattern; | |||
7877 | D = FD->getDefinition(); | |||
7878 | } else if (auto *VD = dyn_cast<VarDecl>(D)) { | |||
7879 | if (auto *Pattern = VD->getTemplateInstantiationPattern()) | |||
7880 | VD = Pattern; | |||
7881 | D = VD->getDefinition(); | |||
7882 | } | |||
7883 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 7883, __PRETTY_FUNCTION__)); | |||
7884 | ||||
7885 | *Suggested = D; | |||
7886 | ||||
7887 | auto DefinitionIsVisible = [&] { | |||
7888 | // The (primary) definition might be in a visible module. | |||
7889 | if (isVisible(D)) | |||
7890 | return true; | |||
7891 | ||||
7892 | // A visible module might have a merged definition instead. | |||
7893 | if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) | |||
7894 | : hasVisibleMergedDefinition(D)) { | |||
7895 | if (CodeSynthesisContexts.empty() && | |||
7896 | !getLangOpts().ModulesLocalVisibility) { | |||
7897 | // Cache the fact that this definition is implicitly visible because | |||
7898 | // there is a visible merged definition. | |||
7899 | D->setVisibleDespiteOwningModule(); | |||
7900 | } | |||
7901 | return true; | |||
7902 | } | |||
7903 | ||||
7904 | return false; | |||
7905 | }; | |||
7906 | ||||
7907 | if (DefinitionIsVisible()) | |||
7908 | return true; | |||
7909 | ||||
7910 | // The external source may have additional definitions of this entity that are | |||
7911 | // visible, so complete the redeclaration chain now and ask again. | |||
7912 | if (auto *Source = Context.getExternalSource()) { | |||
7913 | Source->CompleteRedeclChain(D); | |||
7914 | return DefinitionIsVisible(); | |||
7915 | } | |||
7916 | ||||
7917 | return false; | |||
7918 | } | |||
7919 | ||||
7920 | /// Locks in the inheritance model for the given class and all of its bases. | |||
7921 | static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { | |||
7922 | RD = RD->getMostRecentNonInjectedDecl(); | |||
7923 | if (!RD->hasAttr<MSInheritanceAttr>()) { | |||
7924 | MSInheritanceAttr::Spelling IM; | |||
7925 | ||||
7926 | switch (S.MSPointerToMemberRepresentationMethod) { | |||
7927 | case LangOptions::PPTMK_BestCase: | |||
7928 | IM = RD->calculateInheritanceModel(); | |||
7929 | break; | |||
7930 | case LangOptions::PPTMK_FullGeneralitySingleInheritance: | |||
7931 | IM = MSInheritanceAttr::Keyword_single_inheritance; | |||
7932 | break; | |||
7933 | case LangOptions::PPTMK_FullGeneralityMultipleInheritance: | |||
7934 | IM = MSInheritanceAttr::Keyword_multiple_inheritance; | |||
7935 | break; | |||
7936 | case LangOptions::PPTMK_FullGeneralityVirtualInheritance: | |||
7937 | IM = MSInheritanceAttr::Keyword_unspecified_inheritance; | |||
7938 | break; | |||
7939 | } | |||
7940 | ||||
7941 | RD->addAttr(MSInheritanceAttr::CreateImplicit( | |||
7942 | S.getASTContext(), IM, | |||
7943 | /*BestCase=*/S.MSPointerToMemberRepresentationMethod == | |||
7944 | LangOptions::PPTMK_BestCase, | |||
7945 | S.ImplicitMSInheritanceAttrLoc.isValid() | |||
7946 | ? S.ImplicitMSInheritanceAttrLoc | |||
7947 | : RD->getSourceRange())); | |||
7948 | S.Consumer.AssignInheritanceModel(RD); | |||
7949 | } | |||
7950 | } | |||
7951 | ||||
7952 | /// The implementation of RequireCompleteType | |||
7953 | bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, | |||
7954 | TypeDiagnoser *Diagnoser) { | |||
7955 | // FIXME: Add this assertion to make sure we always get instantiation points. | |||
7956 | // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); | |||
7957 | // FIXME: Add this assertion to help us flush out problems with | |||
7958 | // checking for dependent types and type-dependent expressions. | |||
7959 | // | |||
7960 | // assert(!T->isDependentType() && | |||
7961 | // "Can't ask whether a dependent type is complete"); | |||
7962 | ||||
7963 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { | |||
7964 | if (!MPTy->getClass()->isDependentType()) { | |||
7965 | if (getLangOpts().CompleteMemberPointers && | |||
7966 | !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && | |||
7967 | RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), | |||
7968 | diag::err_memptr_incomplete)) | |||
7969 | return true; | |||
7970 | ||||
7971 | // We lock in the inheritance model once somebody has asked us to ensure | |||
7972 | // that a pointer-to-member type is complete. | |||
7973 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
7974 | (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); | |||
7975 | assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); | |||
7976 | } | |||
7977 | } | |||
7978 | } | |||
7979 | ||||
7980 | NamedDecl *Def = nullptr; | |||
7981 | bool Incomplete = T->isIncompleteType(&Def); | |||
7982 | ||||
7983 | // Check that any necessary explicit specializations are visible. For an | |||
7984 | // enum, we just need the declaration, so don't check this. | |||
7985 | if (Def && !isa<EnumDecl>(Def)) | |||
7986 | checkSpecializationVisibility(Loc, Def); | |||
7987 | ||||
7988 | // If we have a complete type, we're done. | |||
7989 | if (!Incomplete) { | |||
7990 | // If we know about the definition but it is not visible, complain. | |||
7991 | NamedDecl *SuggestedDef = nullptr; | |||
7992 | if (Def && | |||
7993 | !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { | |||
7994 | // If the user is going to see an error here, recover by making the | |||
7995 | // definition visible. | |||
7996 | bool TreatAsComplete = Diagnoser && !isSFINAEContext(); | |||
7997 | if (Diagnoser && SuggestedDef) | |||
7998 | diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, | |||
7999 | /*Recover*/TreatAsComplete); | |||
8000 | return !TreatAsComplete; | |||
8001 | } else if (Def && !TemplateInstCallbacks.empty()) { | |||
8002 | CodeSynthesisContext TempInst; | |||
8003 | TempInst.Kind = CodeSynthesisContext::Memoization; | |||
8004 | TempInst.Template = Def; | |||
8005 | TempInst.Entity = Def; | |||
8006 | TempInst.PointOfInstantiation = Loc; | |||
8007 | atTemplateBegin(TemplateInstCallbacks, *this, TempInst); | |||
8008 | atTemplateEnd(TemplateInstCallbacks, *this, TempInst); | |||
8009 | } | |||
8010 | ||||
8011 | return false; | |||
8012 | } | |||
8013 | ||||
8014 | TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); | |||
8015 | ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); | |||
8016 | ||||
8017 | // Give the external source a chance to provide a definition of the type. | |||
8018 | // This is kept separate from completing the redeclaration chain so that | |||
8019 | // external sources such as LLDB can avoid synthesizing a type definition | |||
8020 | // unless it's actually needed. | |||
8021 | if (Tag || IFace) { | |||
8022 | // Avoid diagnosing invalid decls as incomplete. | |||
8023 | if (Def->isInvalidDecl()) | |||
| ||||
8024 | return true; | |||
8025 | ||||
8026 | // Give the external AST source a chance to complete the type. | |||
8027 | if (auto *Source = Context.getExternalSource()) { | |||
8028 | if (Tag && Tag->hasExternalLexicalStorage()) | |||
8029 | Source->CompleteType(Tag); | |||
8030 | if (IFace && IFace->hasExternalLexicalStorage()) | |||
8031 | Source->CompleteType(IFace); | |||
8032 | // If the external source completed the type, go through the motions | |||
8033 | // again to ensure we're allowed to use the completed type. | |||
8034 | if (!T->isIncompleteType()) | |||
8035 | return RequireCompleteTypeImpl(Loc, T, Diagnoser); | |||
8036 | } | |||
8037 | } | |||
8038 | ||||
8039 | // If we have a class template specialization or a class member of a | |||
8040 | // class template specialization, or an array with known size of such, | |||
8041 | // try to instantiate it. | |||
8042 | if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { | |||
8043 | bool Instantiated = false; | |||
8044 | bool Diagnosed = false; | |||
8045 | if (RD->isDependentContext()) { | |||
8046 | // Don't try to instantiate a dependent class (eg, a member template of | |||
8047 | // an instantiated class template specialization). | |||
8048 | // FIXME: Can this ever happen? | |||
8049 | } else if (auto *ClassTemplateSpec = | |||
8050 | dyn_cast<ClassTemplateSpecializationDecl>(RD)) { | |||
8051 | if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { | |||
8052 | Diagnosed = InstantiateClassTemplateSpecialization( | |||
8053 | Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, | |||
8054 | /*Complain=*/Diagnoser); | |||
8055 | Instantiated = true; | |||
8056 | } | |||
8057 | } else { | |||
8058 | CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); | |||
8059 | if (!RD->isBeingDefined() && Pattern) { | |||
8060 | MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); | |||
8061 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 8061, __PRETTY_FUNCTION__)); | |||
8062 | // This record was instantiated from a class within a template. | |||
8063 | if (MSI->getTemplateSpecializationKind() != | |||
8064 | TSK_ExplicitSpecialization) { | |||
8065 | Diagnosed = InstantiateClass(Loc, RD, Pattern, | |||
8066 | getTemplateInstantiationArgs(RD), | |||
8067 | TSK_ImplicitInstantiation, | |||
8068 | /*Complain=*/Diagnoser); | |||
8069 | Instantiated = true; | |||
8070 | } | |||
8071 | } | |||
8072 | } | |||
8073 | ||||
8074 | if (Instantiated) { | |||
8075 | // Instantiate* might have already complained that the template is not | |||
8076 | // defined, if we asked it to. | |||
8077 | if (Diagnoser && Diagnosed) | |||
8078 | return true; | |||
8079 | // If we instantiated a definition, check that it's usable, even if | |||
8080 | // instantiation produced an error, so that repeated calls to this | |||
8081 | // function give consistent answers. | |||
8082 | if (!T->isIncompleteType()) | |||
8083 | return RequireCompleteTypeImpl(Loc, T, Diagnoser); | |||
8084 | } | |||
8085 | } | |||
8086 | ||||
8087 | // FIXME: If we didn't instantiate a definition because of an explicit | |||
8088 | // specialization declaration, check that it's visible. | |||
8089 | ||||
8090 | if (!Diagnoser) | |||
8091 | return true; | |||
8092 | ||||
8093 | Diagnoser->diagnose(*this, Loc, T); | |||
8094 | ||||
8095 | // If the type was a forward declaration of a class/struct/union | |||
8096 | // type, produce a note. | |||
8097 | if (Tag && !Tag->isInvalidDecl()) | |||
8098 | Diag(Tag->getLocation(), | |||
8099 | Tag->isBeingDefined() ? diag::note_type_being_defined | |||
8100 | : diag::note_forward_declaration) | |||
8101 | << Context.getTagDeclType(Tag); | |||
8102 | ||||
8103 | // If the Objective-C class was a forward declaration, produce a note. | |||
8104 | if (IFace && !IFace->isInvalidDecl()) | |||
8105 | Diag(IFace->getLocation(), diag::note_forward_class); | |||
8106 | ||||
8107 | // If we have external information that we can use to suggest a fix, | |||
8108 | // produce a note. | |||
8109 | if (ExternalSource) | |||
8110 | ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); | |||
8111 | ||||
8112 | return true; | |||
8113 | } | |||
8114 | ||||
8115 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | |||
8116 | unsigned DiagID) { | |||
8117 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
8118 | return RequireCompleteType(Loc, T, Diagnoser); | |||
8119 | } | |||
8120 | ||||
8121 | /// Get diagnostic %select index for tag kind for | |||
8122 | /// literal type diagnostic message. | |||
8123 | /// WARNING: Indexes apply to particular diagnostics only! | |||
8124 | /// | |||
8125 | /// \returns diagnostic %select index. | |||
8126 | static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { | |||
8127 | switch (Tag) { | |||
8128 | case TTK_Struct: return 0; | |||
8129 | case TTK_Interface: return 1; | |||
8130 | case TTK_Class: return 2; | |||
8131 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 8131); | |||
8132 | } | |||
8133 | } | |||
8134 | ||||
8135 | /// Ensure that the type T is a literal type. | |||
8136 | /// | |||
8137 | /// This routine checks whether the type @p T is a literal type. If @p T is an | |||
8138 | /// incomplete type, an attempt is made to complete it. If @p T is a literal | |||
8139 | /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, | |||
8140 | /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving | |||
8141 | /// it the type @p T), along with notes explaining why the type is not a | |||
8142 | /// literal type, and returns true. | |||
8143 | /// | |||
8144 | /// @param Loc The location in the source that the non-literal type | |||
8145 | /// diagnostic should refer to. | |||
8146 | /// | |||
8147 | /// @param T The type that this routine is examining for literalness. | |||
8148 | /// | |||
8149 | /// @param Diagnoser Emits a diagnostic if T is not a literal type. | |||
8150 | /// | |||
8151 | /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, | |||
8152 | /// @c false otherwise. | |||
8153 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, | |||
8154 | TypeDiagnoser &Diagnoser) { | |||
8155 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 8155, __PRETTY_FUNCTION__)); | |||
8156 | ||||
8157 | QualType ElemType = Context.getBaseElementType(T); | |||
8158 | if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && | |||
8159 | T->isLiteralType(Context)) | |||
8160 | return false; | |||
8161 | ||||
8162 | Diagnoser.diagnose(*this, Loc, T); | |||
8163 | ||||
8164 | if (T->isVariableArrayType()) | |||
8165 | return true; | |||
8166 | ||||
8167 | const RecordType *RT = ElemType->getAs<RecordType>(); | |||
8168 | if (!RT) | |||
8169 | return true; | |||
8170 | ||||
8171 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
8172 | ||||
8173 | // A partially-defined class type can't be a literal type, because a literal | |||
8174 | // class type must have a trivial destructor (which can't be checked until | |||
8175 | // the class definition is complete). | |||
8176 | if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) | |||
8177 | return true; | |||
8178 | ||||
8179 | // [expr.prim.lambda]p3: | |||
8180 | // This class type is [not] a literal type. | |||
8181 | if (RD->isLambda() && !getLangOpts().CPlusPlus17) { | |||
8182 | Diag(RD->getLocation(), diag::note_non_literal_lambda); | |||
8183 | return true; | |||
8184 | } | |||
8185 | ||||
8186 | // If the class has virtual base classes, then it's not an aggregate, and | |||
8187 | // cannot have any constexpr constructors or a trivial default constructor, | |||
8188 | // so is non-literal. This is better to diagnose than the resulting absence | |||
8189 | // of constexpr constructors. | |||
8190 | if (RD->getNumVBases()) { | |||
8191 | Diag(RD->getLocation(), diag::note_non_literal_virtual_base) | |||
8192 | << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); | |||
8193 | for (const auto &I : RD->vbases()) | |||
8194 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) | |||
8195 | << I.getSourceRange(); | |||
8196 | } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && | |||
8197 | !RD->hasTrivialDefaultConstructor()) { | |||
8198 | Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; | |||
8199 | } else if (RD->hasNonLiteralTypeFieldsOrBases()) { | |||
8200 | for (const auto &I : RD->bases()) { | |||
8201 | if (!I.getType()->isLiteralType(Context)) { | |||
8202 | Diag(I.getBeginLoc(), diag::note_non_literal_base_class) | |||
8203 | << RD << I.getType() << I.getSourceRange(); | |||
8204 | return true; | |||
8205 | } | |||
8206 | } | |||
8207 | for (const auto *I : RD->fields()) { | |||
8208 | if (!I->getType()->isLiteralType(Context) || | |||
8209 | I->getType().isVolatileQualified()) { | |||
8210 | Diag(I->getLocation(), diag::note_non_literal_field) | |||
8211 | << RD << I << I->getType() | |||
8212 | << I->getType().isVolatileQualified(); | |||
8213 | return true; | |||
8214 | } | |||
8215 | } | |||
8216 | } else if (!RD->hasTrivialDestructor()) { | |||
8217 | // All fields and bases are of literal types, so have trivial destructors. | |||
8218 | // If this class's destructor is non-trivial it must be user-declared. | |||
8219 | CXXDestructorDecl *Dtor = RD->getDestructor(); | |||
8220 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 8220, __PRETTY_FUNCTION__)); | |||
8221 | if (!Dtor) | |||
8222 | return true; | |||
8223 | ||||
8224 | Diag(Dtor->getLocation(), Dtor->isUserProvided() ? | |||
8225 | diag::note_non_literal_user_provided_dtor : | |||
8226 | diag::note_non_literal_nontrivial_dtor) << RD; | |||
8227 | if (!Dtor->isUserProvided()) | |||
8228 | SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, | |||
8229 | /*Diagnose*/true); | |||
8230 | } | |||
8231 | ||||
8232 | return true; | |||
8233 | } | |||
8234 | ||||
8235 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { | |||
8236 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
8237 | return RequireLiteralType(Loc, T, Diagnoser); | |||
| ||||
8238 | } | |||
8239 | ||||
8240 | /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified | |||
8241 | /// by the nested-name-specifier contained in SS, and that is (re)declared by | |||
8242 | /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. | |||
8243 | QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, | |||
8244 | const CXXScopeSpec &SS, QualType T, | |||
8245 | TagDecl *OwnedTagDecl) { | |||
8246 | if (T.isNull()) | |||
8247 | return T; | |||
8248 | NestedNameSpecifier *NNS; | |||
8249 | if (SS.isValid()) | |||
8250 | NNS = SS.getScopeRep(); | |||
8251 | else { | |||
8252 | if (Keyword == ETK_None) | |||
8253 | return T; | |||
8254 | NNS = nullptr; | |||
8255 | } | |||
8256 | return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl); | |||
8257 | } | |||
8258 | ||||
8259 | QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { | |||
8260 | assert(!E->hasPlaceholderType() && "unexpected placeholder")((!E->hasPlaceholderType() && "unexpected placeholder" ) ? static_cast<void> (0) : __assert_fail ("!E->hasPlaceholderType() && \"unexpected placeholder\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 8260, __PRETTY_FUNCTION__)); | |||
8261 | ||||
8262 | if (!getLangOpts().CPlusPlus && E->refersToBitField()) | |||
8263 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; | |||
8264 | ||||
8265 | if (!E->isTypeDependent()) { | |||
8266 | QualType T = E->getType(); | |||
8267 | if (const TagType *TT = T->getAs<TagType>()) | |||
8268 | DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); | |||
8269 | } | |||
8270 | return Context.getTypeOfExprType(E); | |||
8271 | } | |||
8272 | ||||
8273 | /// getDecltypeForExpr - Given an expr, will return the decltype for | |||
8274 | /// that expression, according to the rules in C++11 | |||
8275 | /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. | |||
8276 | static QualType getDecltypeForExpr(Sema &S, Expr *E) { | |||
8277 | if (E->isTypeDependent()) | |||
8278 | return S.Context.DependentTy; | |||
8279 | ||||
8280 | // C++11 [dcl.type.simple]p4: | |||
8281 | // The type denoted by decltype(e) is defined as follows: | |||
8282 | // | |||
8283 | // - if e is an unparenthesized id-expression or an unparenthesized class | |||
8284 | // member access (5.2.5), decltype(e) is the type of the entity named | |||
8285 | // by e. If there is no such entity, or if e names a set of overloaded | |||
8286 | // functions, the program is ill-formed; | |||
8287 | // | |||
8288 | // We apply the same rules for Objective-C ivar and property references. | |||
8289 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
8290 | const ValueDecl *VD = DRE->getDecl(); | |||
8291 | return VD->getType(); | |||
8292 | } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
8293 | if (const ValueDecl *VD = ME->getMemberDecl()) | |||
8294 | if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) | |||
8295 | return VD->getType(); | |||
8296 | } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { | |||
8297 | return IR->getDecl()->getType(); | |||
8298 | } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { | |||
8299 | if (PR->isExplicitProperty()) | |||
8300 | return PR->getExplicitProperty()->getType(); | |||
8301 | } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { | |||
8302 | return PE->getType(); | |||
8303 | } | |||
8304 | ||||
8305 | // C++11 [expr.lambda.prim]p18: | |||
8306 | // Every occurrence of decltype((x)) where x is a possibly | |||
8307 | // parenthesized id-expression that names an entity of automatic | |||
8308 | // storage duration is treated as if x were transformed into an | |||
8309 | // access to a corresponding data member of the closure type that | |||
8310 | // would have been declared if x were an odr-use of the denoted | |||
8311 | // entity. | |||
8312 | using namespace sema; | |||
8313 | if (S.getCurLambda()) { | |||
8314 | if (isa<ParenExpr>(E)) { | |||
8315 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
8316 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
8317 | QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); | |||
8318 | if (!T.isNull()) | |||
8319 | return S.Context.getLValueReferenceType(T); | |||
8320 | } | |||
8321 | } | |||
8322 | } | |||
8323 | } | |||
8324 | ||||
8325 | ||||
8326 | // C++11 [dcl.type.simple]p4: | |||
8327 | // [...] | |||
8328 | QualType T = E->getType(); | |||
8329 | switch (E->getValueKind()) { | |||
8330 | // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the | |||
8331 | // type of e; | |||
8332 | case VK_XValue: T = S.Context.getRValueReferenceType(T); break; | |||
8333 | // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the | |||
8334 | // type of e; | |||
8335 | case VK_LValue: T = S.Context.getLValueReferenceType(T); break; | |||
8336 | // - otherwise, decltype(e) is the type of e. | |||
8337 | case VK_RValue: break; | |||
8338 | } | |||
8339 | ||||
8340 | return T; | |||
8341 | } | |||
8342 | ||||
8343 | QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, | |||
8344 | bool AsUnevaluated) { | |||
8345 | assert(!E->hasPlaceholderType() && "unexpected placeholder")((!E->hasPlaceholderType() && "unexpected placeholder" ) ? static_cast<void> (0) : __assert_fail ("!E->hasPlaceholderType() && \"unexpected placeholder\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 8345, __PRETTY_FUNCTION__)); | |||
8346 | ||||
8347 | if (AsUnevaluated && CodeSynthesisContexts.empty() && | |||
8348 | E->HasSideEffects(Context, false)) { | |||
8349 | // The expression operand for decltype is in an unevaluated expression | |||
8350 | // context, so side effects could result in unintended consequences. | |||
8351 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
8352 | } | |||
8353 | ||||
8354 | return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); | |||
8355 | } | |||
8356 | ||||
8357 | QualType Sema::BuildUnaryTransformType(QualType BaseType, | |||
8358 | UnaryTransformType::UTTKind UKind, | |||
8359 | SourceLocation Loc) { | |||
8360 | switch (UKind) { | |||
8361 | case UnaryTransformType::EnumUnderlyingType: | |||
8362 | if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { | |||
8363 | Diag(Loc, diag::err_only_enums_have_underlying_types); | |||
8364 | return QualType(); | |||
8365 | } else { | |||
8366 | QualType Underlying = BaseType; | |||
8367 | if (!BaseType->isDependentType()) { | |||
8368 | // The enum could be incomplete if we're parsing its definition or | |||
8369 | // recovering from an error. | |||
8370 | NamedDecl *FwdDecl = nullptr; | |||
8371 | if (BaseType->isIncompleteType(&FwdDecl)) { | |||
8372 | Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; | |||
8373 | Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; | |||
8374 | return QualType(); | |||
8375 | } | |||
8376 | ||||
8377 | EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); | |||
8378 | 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-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 8378, __PRETTY_FUNCTION__)); | |||
8379 | ||||
8380 | DiagnoseUseOfDecl(ED, Loc); | |||
8381 | ||||
8382 | Underlying = ED->getIntegerType(); | |||
8383 | assert(!Underlying.isNull())((!Underlying.isNull()) ? static_cast<void> (0) : __assert_fail ("!Underlying.isNull()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 8383, __PRETTY_FUNCTION__)); | |||
8384 | } | |||
8385 | return Context.getUnaryTransformType(BaseType, Underlying, | |||
8386 | UnaryTransformType::EnumUnderlyingType); | |||
8387 | } | |||
8388 | } | |||
8389 | llvm_unreachable("unknown unary transform type")::llvm::llvm_unreachable_internal("unknown unary transform type" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaType.cpp" , 8389); | |||
8390 | } | |||
8391 | ||||
8392 | QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { | |||
8393 | if (!T->isDependentType()) { | |||
8394 | // FIXME: It isn't entirely clear whether incomplete atomic types | |||
8395 | // are allowed or not; for simplicity, ban them for the moment. | |||
8396 | if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) | |||
8397 | return QualType(); | |||
8398 | ||||
8399 | int DisallowedKind = -1; | |||
8400 | if (T->isArrayType()) | |||
8401 | DisallowedKind = 1; | |||
8402 | else if (T->isFunctionType()) | |||
8403 | DisallowedKind = 2; | |||
8404 | else if (T->isReferenceType()) | |||
8405 | DisallowedKind = 3; | |||
8406 | else if (T->isAtomicType()) | |||
8407 | DisallowedKind = 4; | |||
8408 | else if (T.hasQualifiers()) | |||
8409 | DisallowedKind = 5; | |||
8410 | else if (!T.isTriviallyCopyableType(Context)) | |||
8411 | // Some other non-trivially-copyable type (probably a C++ class) | |||
8412 | DisallowedKind = 6; | |||
8413 | ||||
8414 | if (DisallowedKind != -1) { | |||
8415 | Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; | |||
8416 | return QualType(); | |||
8417 | } | |||
8418 | ||||
8419 | // FIXME: Do we need any handling for ARC here? | |||
8420 | } | |||
8421 | ||||
8422 | // Build the pointer type. | |||
8423 | return Context.getAtomicType(T); | |||
8424 | } |
1 | //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines the Sema class, which performs semantic analysis and |
10 | // builds ASTs. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_CLANG_SEMA_SEMA_H |
15 | #define LLVM_CLANG_SEMA_SEMA_H |
16 | |
17 | #include "clang/AST/Attr.h" |
18 | #include "clang/AST/Availability.h" |
19 | #include "clang/AST/ComparisonCategories.h" |
20 | #include "clang/AST/DeclTemplate.h" |
21 | #include "clang/AST/DeclarationName.h" |
22 | #include "clang/AST/Expr.h" |
23 | #include "clang/AST/ExprCXX.h" |
24 | #include "clang/AST/ExprObjC.h" |
25 | #include "clang/AST/ExternalASTSource.h" |
26 | #include "clang/AST/LocInfoType.h" |
27 | #include "clang/AST/MangleNumberingContext.h" |
28 | #include "clang/AST/NSAPI.h" |
29 | #include "clang/AST/PrettyPrinter.h" |
30 | #include "clang/AST/StmtCXX.h" |
31 | #include "clang/AST/TypeLoc.h" |
32 | #include "clang/AST/TypeOrdering.h" |
33 | #include "clang/Basic/ExpressionTraits.h" |
34 | #include "clang/Basic/Module.h" |
35 | #include "clang/Basic/OpenMPKinds.h" |
36 | #include "clang/Basic/PragmaKinds.h" |
37 | #include "clang/Basic/Specifiers.h" |
38 | #include "clang/Basic/TemplateKinds.h" |
39 | #include "clang/Basic/TypeTraits.h" |
40 | #include "clang/Sema/AnalysisBasedWarnings.h" |
41 | #include "clang/Sema/CleanupInfo.h" |
42 | #include "clang/Sema/DeclSpec.h" |
43 | #include "clang/Sema/ExternalSemaSource.h" |
44 | #include "clang/Sema/IdentifierResolver.h" |
45 | #include "clang/Sema/ObjCMethodList.h" |
46 | #include "clang/Sema/Ownership.h" |
47 | #include "clang/Sema/Scope.h" |
48 | #include "clang/Sema/TypoCorrection.h" |
49 | #include "clang/Sema/Weak.h" |
50 | #include "llvm/ADT/ArrayRef.h" |
51 | #include "llvm/ADT/Optional.h" |
52 | #include "llvm/ADT/SetVector.h" |
53 | #include "llvm/ADT/SmallBitVector.h" |
54 | #include "llvm/ADT/SmallPtrSet.h" |
55 | #include "llvm/ADT/SmallVector.h" |
56 | #include "llvm/ADT/TinyPtrVector.h" |
57 | #include <deque> |
58 | #include <memory> |
59 | #include <string> |
60 | #include <vector> |
61 | |
62 | namespace llvm { |
63 | class APSInt; |
64 | template <typename ValueT> struct DenseMapInfo; |
65 | template <typename ValueT, typename ValueInfoT> class DenseSet; |
66 | class SmallBitVector; |
67 | struct InlineAsmIdentifierInfo; |
68 | } |
69 | |
70 | namespace clang { |
71 | class ADLResult; |
72 | class ASTConsumer; |
73 | class ASTContext; |
74 | class ASTMutationListener; |
75 | class ASTReader; |
76 | class ASTWriter; |
77 | class ArrayType; |
78 | class ParsedAttr; |
79 | class BindingDecl; |
80 | class BlockDecl; |
81 | class CapturedDecl; |
82 | class CXXBasePath; |
83 | class CXXBasePaths; |
84 | class CXXBindTemporaryExpr; |
85 | typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; |
86 | class CXXConstructorDecl; |
87 | class CXXConversionDecl; |
88 | class CXXDeleteExpr; |
89 | class CXXDestructorDecl; |
90 | class CXXFieldCollector; |
91 | class CXXMemberCallExpr; |
92 | class CXXMethodDecl; |
93 | class CXXScopeSpec; |
94 | class CXXTemporary; |
95 | class CXXTryStmt; |
96 | class CallExpr; |
97 | class ClassTemplateDecl; |
98 | class ClassTemplatePartialSpecializationDecl; |
99 | class ClassTemplateSpecializationDecl; |
100 | class VarTemplatePartialSpecializationDecl; |
101 | class CodeCompleteConsumer; |
102 | class CodeCompletionAllocator; |
103 | class CodeCompletionTUInfo; |
104 | class CodeCompletionResult; |
105 | class CoroutineBodyStmt; |
106 | class Decl; |
107 | class DeclAccessPair; |
108 | class DeclContext; |
109 | class DeclRefExpr; |
110 | class DeclaratorDecl; |
111 | class DeducedTemplateArgument; |
112 | class DependentDiagnostic; |
113 | class DesignatedInitExpr; |
114 | class Designation; |
115 | class EnableIfAttr; |
116 | class EnumConstantDecl; |
117 | class Expr; |
118 | class ExtVectorType; |
119 | class FormatAttr; |
120 | class FriendDecl; |
121 | class FunctionDecl; |
122 | class FunctionProtoType; |
123 | class FunctionTemplateDecl; |
124 | class ImplicitConversionSequence; |
125 | typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; |
126 | class InitListExpr; |
127 | class InitializationKind; |
128 | class InitializationSequence; |
129 | class InitializedEntity; |
130 | class IntegerLiteral; |
131 | class LabelStmt; |
132 | class LambdaExpr; |
133 | class LangOptions; |
134 | class LocalInstantiationScope; |
135 | class LookupResult; |
136 | class MacroInfo; |
137 | typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; |
138 | class ModuleLoader; |
139 | class MultiLevelTemplateArgumentList; |
140 | class NamedDecl; |
141 | class ObjCCategoryDecl; |
142 | class ObjCCategoryImplDecl; |
143 | class ObjCCompatibleAliasDecl; |
144 | class ObjCContainerDecl; |
145 | class ObjCImplDecl; |
146 | class ObjCImplementationDecl; |
147 | class ObjCInterfaceDecl; |
148 | class ObjCIvarDecl; |
149 | template <class T> class ObjCList; |
150 | class ObjCMessageExpr; |
151 | class ObjCMethodDecl; |
152 | class ObjCPropertyDecl; |
153 | class ObjCProtocolDecl; |
154 | class OMPThreadPrivateDecl; |
155 | class OMPRequiresDecl; |
156 | class OMPDeclareReductionDecl; |
157 | class OMPDeclareSimdDecl; |
158 | class OMPClause; |
159 | struct OMPVarListLocTy; |
160 | struct OverloadCandidate; |
161 | class OverloadCandidateSet; |
162 | class OverloadExpr; |
163 | class ParenListExpr; |
164 | class ParmVarDecl; |
165 | class Preprocessor; |
166 | class PseudoDestructorTypeStorage; |
167 | class PseudoObjectExpr; |
168 | class QualType; |
169 | class StandardConversionSequence; |
170 | class Stmt; |
171 | class StringLiteral; |
172 | class SwitchStmt; |
173 | class TemplateArgument; |
174 | class TemplateArgumentList; |
175 | class TemplateArgumentLoc; |
176 | class TemplateDecl; |
177 | class TemplateInstantiationCallback; |
178 | class TemplateParameterList; |
179 | class TemplatePartialOrderingContext; |
180 | class TemplateTemplateParmDecl; |
181 | class Token; |
182 | class TypeAliasDecl; |
183 | class TypedefDecl; |
184 | class TypedefNameDecl; |
185 | class TypeLoc; |
186 | class TypoCorrectionConsumer; |
187 | class UnqualifiedId; |
188 | class UnresolvedLookupExpr; |
189 | class UnresolvedMemberExpr; |
190 | class UnresolvedSetImpl; |
191 | class UnresolvedSetIterator; |
192 | class UsingDecl; |
193 | class UsingShadowDecl; |
194 | class ValueDecl; |
195 | class VarDecl; |
196 | class VarTemplateSpecializationDecl; |
197 | class VisibilityAttr; |
198 | class VisibleDeclConsumer; |
199 | class IndirectFieldDecl; |
200 | struct DeductionFailureInfo; |
201 | class TemplateSpecCandidateSet; |
202 | |
203 | namespace sema { |
204 | class AccessedEntity; |
205 | class BlockScopeInfo; |
206 | class Capture; |
207 | class CapturedRegionScopeInfo; |
208 | class CapturingScopeInfo; |
209 | class CompoundScopeInfo; |
210 | class DelayedDiagnostic; |
211 | class DelayedDiagnosticPool; |
212 | class FunctionScopeInfo; |
213 | class LambdaScopeInfo; |
214 | class PossiblyUnreachableDiag; |
215 | class SemaPPCallbacks; |
216 | class TemplateDeductionInfo; |
217 | } |
218 | |
219 | namespace threadSafety { |
220 | class BeforeSet; |
221 | void threadSafetyCleanup(BeforeSet* Cache); |
222 | } |
223 | |
224 | // FIXME: No way to easily map from TemplateTypeParmTypes to |
225 | // TemplateTypeParmDecls, so we have this horrible PointerUnion. |
226 | typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, |
227 | SourceLocation> UnexpandedParameterPack; |
228 | |
229 | /// Describes whether we've seen any nullability information for the given |
230 | /// file. |
231 | struct FileNullability { |
232 | /// The first pointer declarator (of any pointer kind) in the file that does |
233 | /// not have a corresponding nullability annotation. |
234 | SourceLocation PointerLoc; |
235 | |
236 | /// The end location for the first pointer declarator in the file. Used for |
237 | /// placing fix-its. |
238 | SourceLocation PointerEndLoc; |
239 | |
240 | /// Which kind of pointer declarator we saw. |
241 | uint8_t PointerKind; |
242 | |
243 | /// Whether we saw any type nullability annotations in the given file. |
244 | bool SawTypeNullability = false; |
245 | }; |
246 | |
247 | /// A mapping from file IDs to a record of whether we've seen nullability |
248 | /// information in that file. |
249 | class FileNullabilityMap { |
250 | /// A mapping from file IDs to the nullability information for each file ID. |
251 | llvm::DenseMap<FileID, FileNullability> Map; |
252 | |
253 | /// A single-element cache based on the file ID. |
254 | struct { |
255 | FileID File; |
256 | FileNullability Nullability; |
257 | } Cache; |
258 | |
259 | public: |
260 | FileNullability &operator[](FileID file) { |
261 | // Check the single-element cache. |
262 | if (file == Cache.File) |
263 | return Cache.Nullability; |
264 | |
265 | // It's not in the single-element cache; flush the cache if we have one. |
266 | if (!Cache.File.isInvalid()) { |
267 | Map[Cache.File] = Cache.Nullability; |
268 | } |
269 | |
270 | // Pull this entry into the cache. |
271 | Cache.File = file; |
272 | Cache.Nullability = Map[file]; |
273 | return Cache.Nullability; |
274 | } |
275 | }; |
276 | |
277 | /// Keeps track of expected type during expression parsing. The type is tied to |
278 | /// a particular token, all functions that update or consume the type take a |
279 | /// start location of the token they are looking at as a parameter. This allows |
280 | /// to avoid updating the type on hot paths in the parser. |
281 | class PreferredTypeBuilder { |
282 | public: |
283 | PreferredTypeBuilder() = default; |
284 | explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} |
285 | |
286 | void enterCondition(Sema &S, SourceLocation Tok); |
287 | void enterReturn(Sema &S, SourceLocation Tok); |
288 | void enterVariableInit(SourceLocation Tok, Decl *D); |
289 | /// Computing a type for the function argument may require running |
290 | /// overloading, so we postpone its computation until it is actually needed. |
291 | /// |
292 | /// Clients should be very careful when using this funciton, as it stores a |
293 | /// function_ref, clients should make sure all calls to get() with the same |
294 | /// location happen while function_ref is alive. |
295 | void enterFunctionArgument(SourceLocation Tok, |
296 | llvm::function_ref<QualType()> ComputeType); |
297 | |
298 | void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); |
299 | void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, |
300 | SourceLocation OpLoc); |
301 | void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); |
302 | void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); |
303 | void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); |
304 | /// Handles all type casts, including C-style cast, C++ casts, etc. |
305 | void enterTypeCast(SourceLocation Tok, QualType CastType); |
306 | |
307 | QualType get(SourceLocation Tok) const { |
308 | if (Tok != ExpectedLoc) |
309 | return QualType(); |
310 | if (!Type.isNull()) |
311 | return Type; |
312 | if (ComputeType) |
313 | return ComputeType(); |
314 | return QualType(); |
315 | } |
316 | |
317 | private: |
318 | /// Start position of a token for which we store expected type. |
319 | SourceLocation ExpectedLoc; |
320 | /// Expected type for a token starting at ExpectedLoc. |
321 | QualType Type; |
322 | /// A function to compute expected type at ExpectedLoc. It is only considered |
323 | /// if Type is null. |
324 | llvm::function_ref<QualType()> ComputeType; |
325 | }; |
326 | |
327 | /// Sema - This implements semantic analysis and AST building for C. |
328 | class Sema { |
329 | Sema(const Sema &) = delete; |
330 | void operator=(const Sema &) = delete; |
331 | |
332 | ///Source of additional semantic information. |
333 | ExternalSemaSource *ExternalSource; |
334 | |
335 | ///Whether Sema has generated a multiplexer and has to delete it. |
336 | bool isMultiplexExternalSource; |
337 | |
338 | static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); |
339 | |
340 | bool isVisibleSlow(const NamedDecl *D); |
341 | |
342 | /// Determine whether two declarations should be linked together, given that |
343 | /// the old declaration might not be visible and the new declaration might |
344 | /// not have external linkage. |
345 | bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, |
346 | const NamedDecl *New) { |
347 | if (isVisible(Old)) |
348 | return true; |
349 | // See comment in below overload for why it's safe to compute the linkage |
350 | // of the new declaration here. |
351 | if (New->isExternallyDeclarable()) { |
352 | assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl" ) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 353, __PRETTY_FUNCTION__)) |
353 | "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl" ) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 353, __PRETTY_FUNCTION__)); |
354 | return true; |
355 | } |
356 | return false; |
357 | } |
358 | bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); |
359 | |
360 | void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, |
361 | QualType ResultTy, |
362 | ArrayRef<QualType> Args); |
363 | |
364 | public: |
365 | typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; |
366 | typedef OpaquePtr<TemplateName> TemplateTy; |
367 | typedef OpaquePtr<QualType> TypeTy; |
368 | |
369 | OpenCLOptions OpenCLFeatures; |
370 | FPOptions FPFeatures; |
371 | |
372 | const LangOptions &LangOpts; |
373 | Preprocessor &PP; |
374 | ASTContext &Context; |
375 | ASTConsumer &Consumer; |
376 | DiagnosticsEngine &Diags; |
377 | SourceManager &SourceMgr; |
378 | |
379 | /// Flag indicating whether or not to collect detailed statistics. |
380 | bool CollectStats; |
381 | |
382 | /// Code-completion consumer. |
383 | CodeCompleteConsumer *CodeCompleter; |
384 | |
385 | /// CurContext - This is the current declaration context of parsing. |
386 | DeclContext *CurContext; |
387 | |
388 | /// Generally null except when we temporarily switch decl contexts, |
389 | /// like in \see ActOnObjCTemporaryExitContainerContext. |
390 | DeclContext *OriginalLexicalContext; |
391 | |
392 | /// VAListTagName - The declaration name corresponding to __va_list_tag. |
393 | /// This is used as part of a hack to omit that class from ADL results. |
394 | DeclarationName VAListTagName; |
395 | |
396 | bool MSStructPragmaOn; // True when \#pragma ms_struct on |
397 | |
398 | /// Controls member pointer representation format under the MS ABI. |
399 | LangOptions::PragmaMSPointersToMembersKind |
400 | MSPointerToMemberRepresentationMethod; |
401 | |
402 | /// Stack of active SEH __finally scopes. Can be empty. |
403 | SmallVector<Scope*, 2> CurrentSEHFinally; |
404 | |
405 | /// Source location for newly created implicit MSInheritanceAttrs |
406 | SourceLocation ImplicitMSInheritanceAttrLoc; |
407 | |
408 | /// pragma clang section kind |
409 | enum PragmaClangSectionKind { |
410 | PCSK_Invalid = 0, |
411 | PCSK_BSS = 1, |
412 | PCSK_Data = 2, |
413 | PCSK_Rodata = 3, |
414 | PCSK_Text = 4 |
415 | }; |
416 | |
417 | enum PragmaClangSectionAction { |
418 | PCSA_Set = 0, |
419 | PCSA_Clear = 1 |
420 | }; |
421 | |
422 | struct PragmaClangSection { |
423 | std::string SectionName; |
424 | bool Valid = false; |
425 | SourceLocation PragmaLocation; |
426 | |
427 | void Act(SourceLocation PragmaLocation, |
428 | PragmaClangSectionAction Action, |
429 | StringLiteral* Name); |
430 | }; |
431 | |
432 | PragmaClangSection PragmaClangBSSSection; |
433 | PragmaClangSection PragmaClangDataSection; |
434 | PragmaClangSection PragmaClangRodataSection; |
435 | PragmaClangSection PragmaClangTextSection; |
436 | |
437 | enum PragmaMsStackAction { |
438 | PSK_Reset = 0x0, // #pragma () |
439 | PSK_Set = 0x1, // #pragma (value) |
440 | PSK_Push = 0x2, // #pragma (push[, id]) |
441 | PSK_Pop = 0x4, // #pragma (pop[, id]) |
442 | PSK_Show = 0x8, // #pragma (show) -- only for "pack"! |
443 | PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) |
444 | PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) |
445 | }; |
446 | |
447 | template<typename ValueType> |
448 | struct PragmaStack { |
449 | struct Slot { |
450 | llvm::StringRef StackSlotLabel; |
451 | ValueType Value; |
452 | SourceLocation PragmaLocation; |
453 | SourceLocation PragmaPushLocation; |
454 | Slot(llvm::StringRef StackSlotLabel, ValueType Value, |
455 | SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) |
456 | : StackSlotLabel(StackSlotLabel), Value(Value), |
457 | PragmaLocation(PragmaLocation), |
458 | PragmaPushLocation(PragmaPushLocation) {} |
459 | }; |
460 | void Act(SourceLocation PragmaLocation, |
461 | PragmaMsStackAction Action, |
462 | llvm::StringRef StackSlotLabel, |
463 | ValueType Value); |
464 | |
465 | // MSVC seems to add artificial slots to #pragma stacks on entering a C++ |
466 | // method body to restore the stacks on exit, so it works like this: |
467 | // |
468 | // struct S { |
469 | // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) |
470 | // void Method {} |
471 | // #pragma <name>(pop, InternalPragmaSlot) |
472 | // }; |
473 | // |
474 | // It works even with #pragma vtordisp, although MSVC doesn't support |
475 | // #pragma vtordisp(push [, id], n) |
476 | // syntax. |
477 | // |
478 | // Push / pop a named sentinel slot. |
479 | void SentinelAction(PragmaMsStackAction Action, StringRef Label) { |
480 | assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!" ) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 481, __PRETTY_FUNCTION__)) |
481 | "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!" ) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 481, __PRETTY_FUNCTION__)); |
482 | Act(CurrentPragmaLocation, Action, Label, CurrentValue); |
483 | } |
484 | |
485 | // Constructors. |
486 | explicit PragmaStack(const ValueType &Default) |
487 | : DefaultValue(Default), CurrentValue(Default) {} |
488 | |
489 | bool hasValue() const { return CurrentValue != DefaultValue; } |
490 | |
491 | SmallVector<Slot, 2> Stack; |
492 | ValueType DefaultValue; // Value used for PSK_Reset action. |
493 | ValueType CurrentValue; |
494 | SourceLocation CurrentPragmaLocation; |
495 | }; |
496 | // FIXME: We should serialize / deserialize these if they occur in a PCH (but |
497 | // we shouldn't do so if they're in a module). |
498 | |
499 | /// Whether to insert vtordisps prior to virtual bases in the Microsoft |
500 | /// C++ ABI. Possible values are 0, 1, and 2, which mean: |
501 | /// |
502 | /// 0: Suppress all vtordisps |
503 | /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial |
504 | /// structors |
505 | /// 2: Always insert vtordisps to support RTTI on partially constructed |
506 | /// objects |
507 | PragmaStack<MSVtorDispAttr::Mode> VtorDispStack; |
508 | // #pragma pack. |
509 | // Sentinel to represent when the stack is set to mac68k alignment. |
510 | static const unsigned kMac68kAlignmentSentinel = ~0U; |
511 | PragmaStack<unsigned> PackStack; |
512 | // The current #pragma pack values and locations at each #include. |
513 | struct PackIncludeState { |
514 | unsigned CurrentValue; |
515 | SourceLocation CurrentPragmaLocation; |
516 | bool HasNonDefaultValue, ShouldWarnOnInclude; |
517 | }; |
518 | SmallVector<PackIncludeState, 8> PackIncludeStack; |
519 | // Segment #pragmas. |
520 | PragmaStack<StringLiteral *> DataSegStack; |
521 | PragmaStack<StringLiteral *> BSSSegStack; |
522 | PragmaStack<StringLiteral *> ConstSegStack; |
523 | PragmaStack<StringLiteral *> CodeSegStack; |
524 | |
525 | // RAII object to push / pop sentinel slots for all MS #pragma stacks. |
526 | // Actions should be performed only if we enter / exit a C++ method body. |
527 | class PragmaStackSentinelRAII { |
528 | public: |
529 | PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); |
530 | ~PragmaStackSentinelRAII(); |
531 | |
532 | private: |
533 | Sema &S; |
534 | StringRef SlotLabel; |
535 | bool ShouldAct; |
536 | }; |
537 | |
538 | /// A mapping that describes the nullability we've seen in each header file. |
539 | FileNullabilityMap NullabilityMap; |
540 | |
541 | /// Last section used with #pragma init_seg. |
542 | StringLiteral *CurInitSeg; |
543 | SourceLocation CurInitSegLoc; |
544 | |
545 | /// VisContext - Manages the stack for \#pragma GCC visibility. |
546 | void *VisContext; // Really a "PragmaVisStack*" |
547 | |
548 | /// This an attribute introduced by \#pragma clang attribute. |
549 | struct PragmaAttributeEntry { |
550 | SourceLocation Loc; |
551 | ParsedAttr *Attribute; |
552 | SmallVector<attr::SubjectMatchRule, 4> MatchRules; |
553 | bool IsUsed; |
554 | }; |
555 | |
556 | /// A push'd group of PragmaAttributeEntries. |
557 | struct PragmaAttributeGroup { |
558 | /// The location of the push attribute. |
559 | SourceLocation Loc; |
560 | /// The namespace of this push group. |
561 | const IdentifierInfo *Namespace; |
562 | SmallVector<PragmaAttributeEntry, 2> Entries; |
563 | }; |
564 | |
565 | SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; |
566 | |
567 | /// The declaration that is currently receiving an attribute from the |
568 | /// #pragma attribute stack. |
569 | const Decl *PragmaAttributeCurrentTargetDecl; |
570 | |
571 | /// This represents the last location of a "#pragma clang optimize off" |
572 | /// directive if such a directive has not been closed by an "on" yet. If |
573 | /// optimizations are currently "on", this is set to an invalid location. |
574 | SourceLocation OptimizeOffPragmaLocation; |
575 | |
576 | /// Flag indicating if Sema is building a recovery call expression. |
577 | /// |
578 | /// This flag is used to avoid building recovery call expressions |
579 | /// if Sema is already doing so, which would cause infinite recursions. |
580 | bool IsBuildingRecoveryCallExpr; |
581 | |
582 | /// Used to control the generation of ExprWithCleanups. |
583 | CleanupInfo Cleanup; |
584 | |
585 | /// ExprCleanupObjects - This is the stack of objects requiring |
586 | /// cleanup that are created by the current full expression. The |
587 | /// element type here is ExprWithCleanups::Object. |
588 | SmallVector<BlockDecl*, 8> ExprCleanupObjects; |
589 | |
590 | /// Store a set of either DeclRefExprs or MemberExprs that contain a reference |
591 | /// to a variable (constant) that may or may not be odr-used in this Expr, and |
592 | /// we won't know until all lvalue-to-rvalue and discarded value conversions |
593 | /// have been applied to all subexpressions of the enclosing full expression. |
594 | /// This is cleared at the end of each full expression. |
595 | using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>; |
596 | MaybeODRUseExprSet MaybeODRUseExprs; |
597 | |
598 | std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; |
599 | |
600 | /// Stack containing information about each of the nested |
601 | /// function, block, and method scopes that are currently active. |
602 | SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; |
603 | |
604 | typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, |
605 | &ExternalSemaSource::ReadExtVectorDecls, 2, 2> |
606 | ExtVectorDeclsType; |
607 | |
608 | /// ExtVectorDecls - This is a list all the extended vector types. This allows |
609 | /// us to associate a raw vector type with one of the ext_vector type names. |
610 | /// This is only necessary for issuing pretty diagnostics. |
611 | ExtVectorDeclsType ExtVectorDecls; |
612 | |
613 | /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. |
614 | std::unique_ptr<CXXFieldCollector> FieldCollector; |
615 | |
616 | typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; |
617 | |
618 | /// Set containing all declared private fields that are not used. |
619 | NamedDeclSetType UnusedPrivateFields; |
620 | |
621 | /// Set containing all typedefs that are likely unused. |
622 | llvm::SmallSetVector<const TypedefNameDecl *, 4> |
623 | UnusedLocalTypedefNameCandidates; |
624 | |
625 | /// Delete-expressions to be analyzed at the end of translation unit |
626 | /// |
627 | /// This list contains class members, and locations of delete-expressions |
628 | /// that could not be proven as to whether they mismatch with new-expression |
629 | /// used in initializer of the field. |
630 | typedef std::pair<SourceLocation, bool> DeleteExprLoc; |
631 | typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; |
632 | llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; |
633 | |
634 | typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; |
635 | |
636 | /// PureVirtualClassDiagSet - a set of class declarations which we have |
637 | /// emitted a list of pure virtual functions. Used to prevent emitting the |
638 | /// same list more than once. |
639 | std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; |
640 | |
641 | /// ParsingInitForAutoVars - a set of declarations with auto types for which |
642 | /// we are currently parsing the initializer. |
643 | llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; |
644 | |
645 | /// Look for a locally scoped extern "C" declaration by the given name. |
646 | NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); |
647 | |
648 | typedef LazyVector<VarDecl *, ExternalSemaSource, |
649 | &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> |
650 | TentativeDefinitionsType; |
651 | |
652 | /// All the tentative definitions encountered in the TU. |
653 | TentativeDefinitionsType TentativeDefinitions; |
654 | |
655 | typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, |
656 | &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> |
657 | UnusedFileScopedDeclsType; |
658 | |
659 | /// The set of file scoped decls seen so far that have not been used |
660 | /// and must warn if not used. Only contains the first declaration. |
661 | UnusedFileScopedDeclsType UnusedFileScopedDecls; |
662 | |
663 | typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, |
664 | &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> |
665 | DelegatingCtorDeclsType; |
666 | |
667 | /// All the delegating constructors seen so far in the file, used for |
668 | /// cycle detection at the end of the TU. |
669 | DelegatingCtorDeclsType DelegatingCtorDecls; |
670 | |
671 | /// All the overriding functions seen during a class definition |
672 | /// that had their exception spec checks delayed, plus the overridden |
673 | /// function. |
674 | SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> |
675 | DelayedOverridingExceptionSpecChecks; |
676 | |
677 | /// All the function redeclarations seen during a class definition that had |
678 | /// their exception spec checks delayed, plus the prior declaration they |
679 | /// should be checked against. Except during error recovery, the new decl |
680 | /// should always be a friend declaration, as that's the only valid way to |
681 | /// redeclare a special member before its class is complete. |
682 | SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> |
683 | DelayedEquivalentExceptionSpecChecks; |
684 | |
685 | typedef llvm::MapVector<const FunctionDecl *, |
686 | std::unique_ptr<LateParsedTemplate>> |
687 | LateParsedTemplateMapT; |
688 | LateParsedTemplateMapT LateParsedTemplateMap; |
689 | |
690 | /// Callback to the parser to parse templated functions when needed. |
691 | typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); |
692 | typedef void LateTemplateParserCleanupCB(void *P); |
693 | LateTemplateParserCB *LateTemplateParser; |
694 | LateTemplateParserCleanupCB *LateTemplateParserCleanup; |
695 | void *OpaqueParser; |
696 | |
697 | void SetLateTemplateParser(LateTemplateParserCB *LTP, |
698 | LateTemplateParserCleanupCB *LTPCleanup, |
699 | void *P) { |
700 | LateTemplateParser = LTP; |
701 | LateTemplateParserCleanup = LTPCleanup; |
702 | OpaqueParser = P; |
703 | } |
704 | |
705 | class DelayedDiagnostics; |
706 | |
707 | class DelayedDiagnosticsState { |
708 | sema::DelayedDiagnosticPool *SavedPool; |
709 | friend class Sema::DelayedDiagnostics; |
710 | }; |
711 | typedef DelayedDiagnosticsState ParsingDeclState; |
712 | typedef DelayedDiagnosticsState ProcessingContextState; |
713 | |
714 | /// A class which encapsulates the logic for delaying diagnostics |
715 | /// during parsing and other processing. |
716 | class DelayedDiagnostics { |
717 | /// The current pool of diagnostics into which delayed |
718 | /// diagnostics should go. |
719 | sema::DelayedDiagnosticPool *CurPool; |
720 | |
721 | public: |
722 | DelayedDiagnostics() : CurPool(nullptr) {} |
723 | |
724 | /// Adds a delayed diagnostic. |
725 | void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h |
726 | |
727 | /// Determines whether diagnostics should be delayed. |
728 | bool shouldDelayDiagnostics() { return CurPool != nullptr; } |
729 | |
730 | /// Returns the current delayed-diagnostics pool. |
731 | sema::DelayedDiagnosticPool *getCurrentPool() const { |
732 | return CurPool; |
733 | } |
734 | |
735 | /// Enter a new scope. Access and deprecation diagnostics will be |
736 | /// collected in this pool. |
737 | DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { |
738 | DelayedDiagnosticsState state; |
739 | state.SavedPool = CurPool; |
740 | CurPool = &pool; |
741 | return state; |
742 | } |
743 | |
744 | /// Leave a delayed-diagnostic state that was previously pushed. |
745 | /// Do not emit any of the diagnostics. This is performed as part |
746 | /// of the bookkeeping of popping a pool "properly". |
747 | void popWithoutEmitting(DelayedDiagnosticsState state) { |
748 | CurPool = state.SavedPool; |
749 | } |
750 | |
751 | /// Enter a new scope where access and deprecation diagnostics are |
752 | /// not delayed. |
753 | DelayedDiagnosticsState pushUndelayed() { |
754 | DelayedDiagnosticsState state; |
755 | state.SavedPool = CurPool; |
756 | CurPool = nullptr; |
757 | return state; |
758 | } |
759 | |
760 | /// Undo a previous pushUndelayed(). |
761 | void popUndelayed(DelayedDiagnosticsState state) { |
762 | assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail ("CurPool == nullptr", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 762, __PRETTY_FUNCTION__)); |
763 | CurPool = state.SavedPool; |
764 | } |
765 | } DelayedDiagnostics; |
766 | |
767 | /// A RAII object to temporarily push a declaration context. |
768 | class ContextRAII { |
769 | private: |
770 | Sema &S; |
771 | DeclContext *SavedContext; |
772 | ProcessingContextState SavedContextState; |
773 | QualType SavedCXXThisTypeOverride; |
774 | |
775 | public: |
776 | ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) |
777 | : S(S), SavedContext(S.CurContext), |
778 | SavedContextState(S.DelayedDiagnostics.pushUndelayed()), |
779 | SavedCXXThisTypeOverride(S.CXXThisTypeOverride) |
780 | { |
781 | assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast <void> (0) : __assert_fail ("ContextToPush && \"pushing null context\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 781, __PRETTY_FUNCTION__)); |
782 | S.CurContext = ContextToPush; |
783 | if (NewThisContext) |
784 | S.CXXThisTypeOverride = QualType(); |
785 | } |
786 | |
787 | void pop() { |
788 | if (!SavedContext) return; |
789 | S.CurContext = SavedContext; |
790 | S.DelayedDiagnostics.popUndelayed(SavedContextState); |
791 | S.CXXThisTypeOverride = SavedCXXThisTypeOverride; |
792 | SavedContext = nullptr; |
793 | } |
794 | |
795 | ~ContextRAII() { |
796 | pop(); |
797 | } |
798 | }; |
799 | |
800 | /// RAII object to handle the state changes required to synthesize |
801 | /// a function body. |
802 | class SynthesizedFunctionScope { |
803 | Sema &S; |
804 | Sema::ContextRAII SavedContext; |
805 | bool PushedCodeSynthesisContext = false; |
806 | |
807 | public: |
808 | SynthesizedFunctionScope(Sema &S, DeclContext *DC) |
809 | : S(S), SavedContext(S, DC) { |
810 | S.PushFunctionScope(); |
811 | S.PushExpressionEvaluationContext( |
812 | Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
813 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) |
814 | FD->setWillHaveBody(true); |
815 | else |
816 | assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0 ) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 816, __PRETTY_FUNCTION__)); |
817 | } |
818 | |
819 | void addContextNote(SourceLocation UseLoc) { |
820 | assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) : __assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 820, __PRETTY_FUNCTION__)); |
821 | |
822 | Sema::CodeSynthesisContext Ctx; |
823 | Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; |
824 | Ctx.PointOfInstantiation = UseLoc; |
825 | Ctx.Entity = cast<Decl>(S.CurContext); |
826 | S.pushCodeSynthesisContext(Ctx); |
827 | |
828 | PushedCodeSynthesisContext = true; |
829 | } |
830 | |
831 | ~SynthesizedFunctionScope() { |
832 | if (PushedCodeSynthesisContext) |
833 | S.popCodeSynthesisContext(); |
834 | if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) |
835 | FD->setWillHaveBody(false); |
836 | S.PopExpressionEvaluationContext(); |
837 | S.PopFunctionScopeInfo(); |
838 | } |
839 | }; |
840 | |
841 | /// WeakUndeclaredIdentifiers - Identifiers contained in |
842 | /// \#pragma weak before declared. rare. may alias another |
843 | /// identifier, declared or undeclared |
844 | llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; |
845 | |
846 | /// ExtnameUndeclaredIdentifiers - Identifiers contained in |
847 | /// \#pragma redefine_extname before declared. Used in Solaris system headers |
848 | /// to define functions that occur in multiple standards to call the version |
849 | /// in the currently selected standard. |
850 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; |
851 | |
852 | |
853 | /// Load weak undeclared identifiers from the external source. |
854 | void LoadExternalWeakUndeclaredIdentifiers(); |
855 | |
856 | /// WeakTopLevelDecl - Translation-unit scoped declarations generated by |
857 | /// \#pragma weak during processing of other Decls. |
858 | /// I couldn't figure out a clean way to generate these in-line, so |
859 | /// we store them here and handle separately -- which is a hack. |
860 | /// It would be best to refactor this. |
861 | SmallVector<Decl*,2> WeakTopLevelDecl; |
862 | |
863 | IdentifierResolver IdResolver; |
864 | |
865 | /// Translation Unit Scope - useful to Objective-C actions that need |
866 | /// to lookup file scope declarations in the "ordinary" C decl namespace. |
867 | /// For example, user-defined classes, built-in "id" type, etc. |
868 | Scope *TUScope; |
869 | |
870 | /// The C++ "std" namespace, where the standard library resides. |
871 | LazyDeclPtr StdNamespace; |
872 | |
873 | /// The C++ "std::bad_alloc" class, which is defined by the C++ |
874 | /// standard library. |
875 | LazyDeclPtr StdBadAlloc; |
876 | |
877 | /// The C++ "std::align_val_t" enum class, which is defined by the C++ |
878 | /// standard library. |
879 | LazyDeclPtr StdAlignValT; |
880 | |
881 | /// The C++ "std::experimental" namespace, where the experimental parts |
882 | /// of the standard library resides. |
883 | NamespaceDecl *StdExperimentalNamespaceCache; |
884 | |
885 | /// The C++ "std::initializer_list" template, which is defined in |
886 | /// \<initializer_list>. |
887 | ClassTemplateDecl *StdInitializerList; |
888 | |
889 | /// The C++ "std::coroutine_traits" template, which is defined in |
890 | /// \<coroutine_traits> |
891 | ClassTemplateDecl *StdCoroutineTraitsCache; |
892 | |
893 | /// The C++ "type_info" declaration, which is defined in \<typeinfo>. |
894 | RecordDecl *CXXTypeInfoDecl; |
895 | |
896 | /// The MSVC "_GUID" struct, which is defined in MSVC header files. |
897 | RecordDecl *MSVCGuidDecl; |
898 | |
899 | /// Caches identifiers/selectors for NSFoundation APIs. |
900 | std::unique_ptr<NSAPI> NSAPIObj; |
901 | |
902 | /// The declaration of the Objective-C NSNumber class. |
903 | ObjCInterfaceDecl *NSNumberDecl; |
904 | |
905 | /// The declaration of the Objective-C NSValue class. |
906 | ObjCInterfaceDecl *NSValueDecl; |
907 | |
908 | /// Pointer to NSNumber type (NSNumber *). |
909 | QualType NSNumberPointer; |
910 | |
911 | /// Pointer to NSValue type (NSValue *). |
912 | QualType NSValuePointer; |
913 | |
914 | /// The Objective-C NSNumber methods used to create NSNumber literals. |
915 | ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; |
916 | |
917 | /// The declaration of the Objective-C NSString class. |
918 | ObjCInterfaceDecl *NSStringDecl; |
919 | |
920 | /// Pointer to NSString type (NSString *). |
921 | QualType NSStringPointer; |
922 | |
923 | /// The declaration of the stringWithUTF8String: method. |
924 | ObjCMethodDecl *StringWithUTF8StringMethod; |
925 | |
926 | /// The declaration of the valueWithBytes:objCType: method. |
927 | ObjCMethodDecl *ValueWithBytesObjCTypeMethod; |
928 | |
929 | /// The declaration of the Objective-C NSArray class. |
930 | ObjCInterfaceDecl *NSArrayDecl; |
931 | |
932 | /// The declaration of the arrayWithObjects:count: method. |
933 | ObjCMethodDecl *ArrayWithObjectsMethod; |
934 | |
935 | /// The declaration of the Objective-C NSDictionary class. |
936 | ObjCInterfaceDecl *NSDictionaryDecl; |
937 | |
938 | /// The declaration of the dictionaryWithObjects:forKeys:count: method. |
939 | ObjCMethodDecl *DictionaryWithObjectsMethod; |
940 | |
941 | /// id<NSCopying> type. |
942 | QualType QIDNSCopying; |
943 | |
944 | /// will hold 'respondsToSelector:' |
945 | Selector RespondsToSelectorSel; |
946 | |
947 | /// A flag to remember whether the implicit forms of operator new and delete |
948 | /// have been declared. |
949 | bool GlobalNewDeleteDeclared; |
950 | |
951 | /// A flag to indicate that we're in a context that permits abstract |
952 | /// references to fields. This is really a |
953 | bool AllowAbstractFieldReference; |
954 | |
955 | /// Describes how the expressions currently being parsed are |
956 | /// evaluated at run-time, if at all. |
957 | enum class ExpressionEvaluationContext { |
958 | /// The current expression and its subexpressions occur within an |
959 | /// unevaluated operand (C++11 [expr]p7), such as the subexpression of |
960 | /// \c sizeof, where the type of the expression may be significant but |
961 | /// no code will be generated to evaluate the value of the expression at |
962 | /// run time. |
963 | Unevaluated, |
964 | |
965 | /// The current expression occurs within a braced-init-list within |
966 | /// an unevaluated operand. This is mostly like a regular unevaluated |
967 | /// context, except that we still instantiate constexpr functions that are |
968 | /// referenced here so that we can perform narrowing checks correctly. |
969 | UnevaluatedList, |
970 | |
971 | /// The current expression occurs within a discarded statement. |
972 | /// This behaves largely similarly to an unevaluated operand in preventing |
973 | /// definitions from being required, but not in other ways. |
974 | DiscardedStatement, |
975 | |
976 | /// The current expression occurs within an unevaluated |
977 | /// operand that unconditionally permits abstract references to |
978 | /// fields, such as a SIZE operator in MS-style inline assembly. |
979 | UnevaluatedAbstract, |
980 | |
981 | /// The current context is "potentially evaluated" in C++11 terms, |
982 | /// but the expression is evaluated at compile-time (like the values of |
983 | /// cases in a switch statement). |
984 | ConstantEvaluated, |
985 | |
986 | /// The current expression is potentially evaluated at run time, |
987 | /// which means that code may be generated to evaluate the value of the |
988 | /// expression at run time. |
989 | PotentiallyEvaluated, |
990 | |
991 | /// The current expression is potentially evaluated, but any |
992 | /// declarations referenced inside that expression are only used if |
993 | /// in fact the current expression is used. |
994 | /// |
995 | /// This value is used when parsing default function arguments, for which |
996 | /// we would like to provide diagnostics (e.g., passing non-POD arguments |
997 | /// through varargs) but do not want to mark declarations as "referenced" |
998 | /// until the default argument is used. |
999 | PotentiallyEvaluatedIfUsed |
1000 | }; |
1001 | |
1002 | /// Data structure used to record current or nested |
1003 | /// expression evaluation contexts. |
1004 | struct ExpressionEvaluationContextRecord { |
1005 | /// The expression evaluation context. |
1006 | ExpressionEvaluationContext Context; |
1007 | |
1008 | /// Whether the enclosing context needed a cleanup. |
1009 | CleanupInfo ParentCleanup; |
1010 | |
1011 | /// Whether we are in a decltype expression. |
1012 | bool IsDecltype; |
1013 | |
1014 | /// The number of active cleanup objects when we entered |
1015 | /// this expression evaluation context. |
1016 | unsigned NumCleanupObjects; |
1017 | |
1018 | /// The number of typos encountered during this expression evaluation |
1019 | /// context (i.e. the number of TypoExprs created). |
1020 | unsigned NumTypos; |
1021 | |
1022 | MaybeODRUseExprSet SavedMaybeODRUseExprs; |
1023 | |
1024 | /// The lambdas that are present within this context, if it |
1025 | /// is indeed an unevaluated context. |
1026 | SmallVector<LambdaExpr *, 2> Lambdas; |
1027 | |
1028 | /// The declaration that provides context for lambda expressions |
1029 | /// and block literals if the normal declaration context does not |
1030 | /// suffice, e.g., in a default function argument. |
1031 | Decl *ManglingContextDecl; |
1032 | |
1033 | /// The context information used to mangle lambda expressions |
1034 | /// and block literals within this context. |
1035 | /// |
1036 | /// This mangling information is allocated lazily, since most contexts |
1037 | /// do not have lambda expressions or block literals. |
1038 | std::unique_ptr<MangleNumberingContext> MangleNumbering; |
1039 | |
1040 | /// If we are processing a decltype type, a set of call expressions |
1041 | /// for which we have deferred checking the completeness of the return type. |
1042 | SmallVector<CallExpr *, 8> DelayedDecltypeCalls; |
1043 | |
1044 | /// If we are processing a decltype type, a set of temporary binding |
1045 | /// expressions for which we have deferred checking the destructor. |
1046 | SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; |
1047 | |
1048 | llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; |
1049 | |
1050 | /// \brief Describes whether we are in an expression constext which we have |
1051 | /// to handle differently. |
1052 | enum ExpressionKind { |
1053 | EK_Decltype, EK_TemplateArgument, EK_Other |
1054 | } ExprContext; |
1055 | |
1056 | ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, |
1057 | unsigned NumCleanupObjects, |
1058 | CleanupInfo ParentCleanup, |
1059 | Decl *ManglingContextDecl, |
1060 | ExpressionKind ExprContext) |
1061 | : Context(Context), ParentCleanup(ParentCleanup), |
1062 | NumCleanupObjects(NumCleanupObjects), NumTypos(0), |
1063 | ManglingContextDecl(ManglingContextDecl), MangleNumbering(), |
1064 | ExprContext(ExprContext) {} |
1065 | |
1066 | /// Retrieve the mangling numbering context, used to consistently |
1067 | /// number constructs like lambdas for mangling. |
1068 | MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx); |
1069 | |
1070 | bool isUnevaluated() const { |
1071 | return Context == ExpressionEvaluationContext::Unevaluated || |
1072 | Context == ExpressionEvaluationContext::UnevaluatedAbstract || |
1073 | Context == ExpressionEvaluationContext::UnevaluatedList; |
1074 | } |
1075 | bool isConstantEvaluated() const { |
1076 | return Context == ExpressionEvaluationContext::ConstantEvaluated; |
1077 | } |
1078 | }; |
1079 | |
1080 | /// A stack of expression evaluation contexts. |
1081 | SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; |
1082 | |
1083 | /// Emit a warning for all pending noderef expressions that we recorded. |
1084 | void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); |
1085 | |
1086 | /// Compute the mangling number context for a lambda expression or |
1087 | /// block literal. |
1088 | /// |
1089 | /// \param DC - The DeclContext containing the lambda expression or |
1090 | /// block literal. |
1091 | /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl |
1092 | /// associated with the context, if relevant. |
1093 | MangleNumberingContext *getCurrentMangleNumberContext( |
1094 | const DeclContext *DC, |
1095 | Decl *&ManglingContextDecl); |
1096 | |
1097 | |
1098 | /// SpecialMemberOverloadResult - The overloading result for a special member |
1099 | /// function. |
1100 | /// |
1101 | /// This is basically a wrapper around PointerIntPair. The lowest bits of the |
1102 | /// integer are used to determine whether overload resolution succeeded. |
1103 | class SpecialMemberOverloadResult { |
1104 | public: |
1105 | enum Kind { |
1106 | NoMemberOrDeleted, |
1107 | Ambiguous, |
1108 | Success |
1109 | }; |
1110 | |
1111 | private: |
1112 | llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; |
1113 | |
1114 | public: |
1115 | SpecialMemberOverloadResult() : Pair() {} |
1116 | SpecialMemberOverloadResult(CXXMethodDecl *MD) |
1117 | : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} |
1118 | |
1119 | CXXMethodDecl *getMethod() const { return Pair.getPointer(); } |
1120 | void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } |
1121 | |
1122 | Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } |
1123 | void setKind(Kind K) { Pair.setInt(K); } |
1124 | }; |
1125 | |
1126 | class SpecialMemberOverloadResultEntry |
1127 | : public llvm::FastFoldingSetNode, |
1128 | public SpecialMemberOverloadResult { |
1129 | public: |
1130 | SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) |
1131 | : FastFoldingSetNode(ID) |
1132 | {} |
1133 | }; |
1134 | |
1135 | /// A cache of special member function overload resolution results |
1136 | /// for C++ records. |
1137 | llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; |
1138 | |
1139 | /// A cache of the flags available in enumerations with the flag_bits |
1140 | /// attribute. |
1141 | mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; |
1142 | |
1143 | /// The kind of translation unit we are processing. |
1144 | /// |
1145 | /// When we're processing a complete translation unit, Sema will perform |
1146 | /// end-of-translation-unit semantic tasks (such as creating |
1147 | /// initializers for tentative definitions in C) once parsing has |
1148 | /// completed. Modules and precompiled headers perform different kinds of |
1149 | /// checks. |
1150 | TranslationUnitKind TUKind; |
1151 | |
1152 | llvm::BumpPtrAllocator BumpAlloc; |
1153 | |
1154 | /// The number of SFINAE diagnostics that have been trapped. |
1155 | unsigned NumSFINAEErrors; |
1156 | |
1157 | typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> |
1158 | UnparsedDefaultArgInstantiationsMap; |
1159 | |
1160 | /// A mapping from parameters with unparsed default arguments to the |
1161 | /// set of instantiations of each parameter. |
1162 | /// |
1163 | /// This mapping is a temporary data structure used when parsing |
1164 | /// nested class templates or nested classes of class templates, |
1165 | /// where we might end up instantiating an inner class before the |
1166 | /// default arguments of its methods have been parsed. |
1167 | UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; |
1168 | |
1169 | // Contains the locations of the beginning of unparsed default |
1170 | // argument locations. |
1171 | llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; |
1172 | |
1173 | /// UndefinedInternals - all the used, undefined objects which require a |
1174 | /// definition in this translation unit. |
1175 | llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; |
1176 | |
1177 | /// Determine if VD, which must be a variable or function, is an external |
1178 | /// symbol that nonetheless can't be referenced from outside this translation |
1179 | /// unit because its type has no linkage and it's not extern "C". |
1180 | bool isExternalWithNoLinkageType(ValueDecl *VD); |
1181 | |
1182 | /// Obtain a sorted list of functions that are undefined but ODR-used. |
1183 | void getUndefinedButUsed( |
1184 | SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); |
1185 | |
1186 | /// Retrieves list of suspicious delete-expressions that will be checked at |
1187 | /// the end of translation unit. |
1188 | const llvm::MapVector<FieldDecl *, DeleteLocs> & |
1189 | getMismatchingDeleteExpressions() const; |
1190 | |
1191 | typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; |
1192 | typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; |
1193 | |
1194 | /// Method Pool - allows efficient lookup when typechecking messages to "id". |
1195 | /// We need to maintain a list, since selectors can have differing signatures |
1196 | /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% |
1197 | /// of selectors are "overloaded"). |
1198 | /// At the head of the list it is recorded whether there were 0, 1, or >= 2 |
1199 | /// methods inside categories with a particular selector. |
1200 | GlobalMethodPool MethodPool; |
1201 | |
1202 | /// Method selectors used in a \@selector expression. Used for implementation |
1203 | /// of -Wselector. |
1204 | llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; |
1205 | |
1206 | /// List of SourceLocations where 'self' is implicitly retained inside a |
1207 | /// block. |
1208 | llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> |
1209 | ImplicitlyRetainedSelfLocs; |
1210 | |
1211 | /// Kinds of C++ special members. |
1212 | enum CXXSpecialMember { |
1213 | CXXDefaultConstructor, |
1214 | CXXCopyConstructor, |
1215 | CXXMoveConstructor, |
1216 | CXXCopyAssignment, |
1217 | CXXMoveAssignment, |
1218 | CXXDestructor, |
1219 | CXXInvalid |
1220 | }; |
1221 | |
1222 | typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> |
1223 | SpecialMemberDecl; |
1224 | |
1225 | /// The C++ special members which we are currently in the process of |
1226 | /// declaring. If this process recursively triggers the declaration of the |
1227 | /// same special member, we should act as if it is not yet declared. |
1228 | llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; |
1229 | |
1230 | /// The function definitions which were renamed as part of typo-correction |
1231 | /// to match their respective declarations. We want to keep track of them |
1232 | /// to ensure that we don't emit a "redefinition" error if we encounter a |
1233 | /// correctly named definition after the renamed definition. |
1234 | llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; |
1235 | |
1236 | /// Stack of types that correspond to the parameter entities that are |
1237 | /// currently being copy-initialized. Can be empty. |
1238 | llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; |
1239 | |
1240 | void ReadMethodPool(Selector Sel); |
1241 | void updateOutOfDateSelector(Selector Sel); |
1242 | |
1243 | /// Private Helper predicate to check for 'self'. |
1244 | bool isSelfExpr(Expr *RExpr); |
1245 | bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); |
1246 | |
1247 | /// Cause the active diagnostic on the DiagosticsEngine to be |
1248 | /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and |
1249 | /// should not be used elsewhere. |
1250 | void EmitCurrentDiagnostic(unsigned DiagID); |
1251 | |
1252 | /// Records and restores the FP_CONTRACT state on entry/exit of compound |
1253 | /// statements. |
1254 | class FPContractStateRAII { |
1255 | public: |
1256 | FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {} |
1257 | ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; } |
1258 | |
1259 | private: |
1260 | Sema& S; |
1261 | FPOptions OldFPFeaturesState; |
1262 | }; |
1263 | |
1264 | void addImplicitTypedef(StringRef Name, QualType T); |
1265 | |
1266 | public: |
1267 | Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, |
1268 | TranslationUnitKind TUKind = TU_Complete, |
1269 | CodeCompleteConsumer *CompletionConsumer = nullptr); |
1270 | ~Sema(); |
1271 | |
1272 | /// Perform initialization that occurs after the parser has been |
1273 | /// initialized but before it parses anything. |
1274 | void Initialize(); |
1275 | |
1276 | const LangOptions &getLangOpts() const { return LangOpts; } |
1277 | OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } |
1278 | FPOptions &getFPOptions() { return FPFeatures; } |
1279 | |
1280 | DiagnosticsEngine &getDiagnostics() const { return Diags; } |
1281 | SourceManager &getSourceManager() const { return SourceMgr; } |
1282 | Preprocessor &getPreprocessor() const { return PP; } |
1283 | ASTContext &getASTContext() const { return Context; } |
1284 | ASTConsumer &getASTConsumer() const { return Consumer; } |
1285 | ASTMutationListener *getASTMutationListener() const; |
1286 | ExternalSemaSource* getExternalSource() const { return ExternalSource; } |
1287 | |
1288 | ///Registers an external source. If an external source already exists, |
1289 | /// creates a multiplex external source and appends to it. |
1290 | /// |
1291 | ///\param[in] E - A non-null external sema source. |
1292 | /// |
1293 | void addExternalSource(ExternalSemaSource *E); |
1294 | |
1295 | void PrintStats() const; |
1296 | |
1297 | /// Helper class that creates diagnostics with optional |
1298 | /// template instantiation stacks. |
1299 | /// |
1300 | /// This class provides a wrapper around the basic DiagnosticBuilder |
1301 | /// class that emits diagnostics. SemaDiagnosticBuilder is |
1302 | /// responsible for emitting the diagnostic (as DiagnosticBuilder |
1303 | /// does) and, if the diagnostic comes from inside a template |
1304 | /// instantiation, printing the template instantiation stack as |
1305 | /// well. |
1306 | class SemaDiagnosticBuilder : public DiagnosticBuilder { |
1307 | Sema &SemaRef; |
1308 | unsigned DiagID; |
1309 | |
1310 | public: |
1311 | SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) |
1312 | : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } |
1313 | |
1314 | // This is a cunning lie. DiagnosticBuilder actually performs move |
1315 | // construction in its copy constructor (but due to varied uses, it's not |
1316 | // possible to conveniently express this as actual move construction). So |
1317 | // the default copy ctor here is fine, because the base class disables the |
1318 | // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op |
1319 | // in that case anwyay. |
1320 | SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; |
1321 | |
1322 | ~SemaDiagnosticBuilder() { |
1323 | // If we aren't active, there is nothing to do. |
1324 | if (!isActive()) return; |
1325 | |
1326 | // Otherwise, we need to emit the diagnostic. First flush the underlying |
1327 | // DiagnosticBuilder data, and clear the diagnostic builder itself so it |
1328 | // won't emit the diagnostic in its own destructor. |
1329 | // |
1330 | // This seems wasteful, in that as written the DiagnosticBuilder dtor will |
1331 | // do its own needless checks to see if the diagnostic needs to be |
1332 | // emitted. However, because we take care to ensure that the builder |
1333 | // objects never escape, a sufficiently smart compiler will be able to |
1334 | // eliminate that code. |
1335 | FlushCounts(); |
1336 | Clear(); |
1337 | |
1338 | // Dispatch to Sema to emit the diagnostic. |
1339 | SemaRef.EmitCurrentDiagnostic(DiagID); |
1340 | } |
1341 | |
1342 | /// Teach operator<< to produce an object of the correct type. |
1343 | template<typename T> |
1344 | friend const SemaDiagnosticBuilder &operator<<( |
1345 | const SemaDiagnosticBuilder &Diag, const T &Value) { |
1346 | const DiagnosticBuilder &BaseDiag = Diag; |
1347 | BaseDiag << Value; |
1348 | return Diag; |
1349 | } |
1350 | }; |
1351 | |
1352 | /// Emit a diagnostic. |
1353 | SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { |
1354 | DiagnosticBuilder DB = Diags.Report(Loc, DiagID); |
1355 | return SemaDiagnosticBuilder(DB, *this, DiagID); |
1356 | } |
1357 | |
1358 | /// Emit a partial diagnostic. |
1359 | SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); |
1360 | |
1361 | /// Build a partial diagnostic. |
1362 | PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h |
1363 | |
1364 | bool findMacroSpelling(SourceLocation &loc, StringRef name); |
1365 | |
1366 | /// Get a string to suggest for zero-initialization of a type. |
1367 | std::string |
1368 | getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; |
1369 | std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; |
1370 | |
1371 | /// Calls \c Lexer::getLocForEndOfToken() |
1372 | SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); |
1373 | |
1374 | /// Retrieve the module loader associated with the preprocessor. |
1375 | ModuleLoader &getModuleLoader() const; |
1376 | |
1377 | void emitAndClearUnusedLocalTypedefWarnings(); |
1378 | |
1379 | enum TUFragmentKind { |
1380 | /// The global module fragment, between 'module;' and a module-declaration. |
1381 | Global, |
1382 | /// A normal translation unit fragment. For a non-module unit, this is the |
1383 | /// entire translation unit. Otherwise, it runs from the module-declaration |
1384 | /// to the private-module-fragment (if any) or the end of the TU (if not). |
1385 | Normal, |
1386 | /// The private module fragment, between 'module :private;' and the end of |
1387 | /// the translation unit. |
1388 | Private |
1389 | }; |
1390 | |
1391 | void ActOnStartOfTranslationUnit(); |
1392 | void ActOnEndOfTranslationUnit(); |
1393 | void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); |
1394 | |
1395 | void CheckDelegatingCtorCycles(); |
1396 | |
1397 | Scope *getScopeForContext(DeclContext *Ctx); |
1398 | |
1399 | void PushFunctionScope(); |
1400 | void PushBlockScope(Scope *BlockScope, BlockDecl *Block); |
1401 | sema::LambdaScopeInfo *PushLambdaScope(); |
1402 | |
1403 | /// This is used to inform Sema what the current TemplateParameterDepth |
1404 | /// is during Parsing. Currently it is used to pass on the depth |
1405 | /// when parsing generic lambda 'auto' parameters. |
1406 | void RecordParsingTemplateParameterDepth(unsigned Depth); |
1407 | |
1408 | void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, |
1409 | RecordDecl *RD, |
1410 | CapturedRegionKind K); |
1411 | |
1412 | /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short |
1413 | /// time after they've been popped. |
1414 | class PoppedFunctionScopeDeleter { |
1415 | Sema *Self; |
1416 | |
1417 | public: |
1418 | explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} |
1419 | void operator()(sema::FunctionScopeInfo *Scope) const; |
1420 | }; |
1421 | |
1422 | using PoppedFunctionScopePtr = |
1423 | std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; |
1424 | |
1425 | PoppedFunctionScopePtr |
1426 | PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, |
1427 | const Decl *D = nullptr, |
1428 | QualType BlockType = QualType()); |
1429 | |
1430 | sema::FunctionScopeInfo *getCurFunction() const { |
1431 | return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); |
1432 | } |
1433 | |
1434 | sema::FunctionScopeInfo *getEnclosingFunction() const; |
1435 | |
1436 | void setFunctionHasBranchIntoScope(); |
1437 | void setFunctionHasBranchProtectedScope(); |
1438 | void setFunctionHasIndirectGoto(); |
1439 | |
1440 | void PushCompoundScope(bool IsStmtExpr); |
1441 | void PopCompoundScope(); |
1442 | |
1443 | sema::CompoundScopeInfo &getCurCompoundScope() const; |
1444 | |
1445 | bool hasAnyUnrecoverableErrorsInThisFunction() const; |
1446 | |
1447 | /// Retrieve the current block, if any. |
1448 | sema::BlockScopeInfo *getCurBlock(); |
1449 | |
1450 | /// Retrieve the current lambda scope info, if any. |
1451 | /// \param IgnoreNonLambdaCapturingScope true if should find the top-most |
1452 | /// lambda scope info ignoring all inner capturing scopes that are not |
1453 | /// lambda scopes. |
1454 | sema::LambdaScopeInfo * |
1455 | getCurLambda(bool IgnoreNonLambdaCapturingScope = false); |
1456 | |
1457 | /// Retrieve the current generic lambda info, if any. |
1458 | sema::LambdaScopeInfo *getCurGenericLambda(); |
1459 | |
1460 | /// Retrieve the current captured region, if any. |
1461 | sema::CapturedRegionScopeInfo *getCurCapturedRegion(); |
1462 | |
1463 | /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls |
1464 | SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } |
1465 | |
1466 | void ActOnComment(SourceRange Comment); |
1467 | |
1468 | //===--------------------------------------------------------------------===// |
1469 | // Type Analysis / Processing: SemaType.cpp. |
1470 | // |
1471 | |
1472 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, |
1473 | const DeclSpec *DS = nullptr); |
1474 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, |
1475 | const DeclSpec *DS = nullptr); |
1476 | QualType BuildPointerType(QualType T, |
1477 | SourceLocation Loc, DeclarationName Entity); |
1478 | QualType BuildReferenceType(QualType T, bool LValueRef, |
1479 | SourceLocation Loc, DeclarationName Entity); |
1480 | QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, |
1481 | Expr *ArraySize, unsigned Quals, |
1482 | SourceRange Brackets, DeclarationName Entity); |
1483 | QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); |
1484 | QualType BuildExtVectorType(QualType T, Expr *ArraySize, |
1485 | SourceLocation AttrLoc); |
1486 | QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, |
1487 | SourceLocation AttrLoc); |
1488 | |
1489 | /// Same as above, but constructs the AddressSpace index if not provided. |
1490 | QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, |
1491 | SourceLocation AttrLoc); |
1492 | |
1493 | bool CheckFunctionReturnType(QualType T, SourceLocation Loc); |
1494 | |
1495 | /// Build a function type. |
1496 | /// |
1497 | /// This routine checks the function type according to C++ rules and |
1498 | /// under the assumption that the result type and parameter types have |
1499 | /// just been instantiated from a template. It therefore duplicates |
1500 | /// some of the behavior of GetTypeForDeclarator, but in a much |
1501 | /// simpler form that is only suitable for this narrow use case. |
1502 | /// |
1503 | /// \param T The return type of the function. |
1504 | /// |
1505 | /// \param ParamTypes The parameter types of the function. This array |
1506 | /// will be modified to account for adjustments to the types of the |
1507 | /// function parameters. |
1508 | /// |
1509 | /// \param Loc The location of the entity whose type involves this |
1510 | /// function type or, if there is no such entity, the location of the |
1511 | /// type that will have function type. |
1512 | /// |
1513 | /// \param Entity The name of the entity that involves the function |
1514 | /// type, if known. |
1515 | /// |
1516 | /// \param EPI Extra information about the function type. Usually this will |
1517 | /// be taken from an existing function with the same prototype. |
1518 | /// |
1519 | /// \returns A suitable function type, if there are no errors. The |
1520 | /// unqualified type will always be a FunctionProtoType. |
1521 | /// Otherwise, returns a NULL type. |
1522 | QualType BuildFunctionType(QualType T, |
1523 | MutableArrayRef<QualType> ParamTypes, |
1524 | SourceLocation Loc, DeclarationName Entity, |
1525 | const FunctionProtoType::ExtProtoInfo &EPI); |
1526 | |
1527 | QualType BuildMemberPointerType(QualType T, QualType Class, |
1528 | SourceLocation Loc, |
1529 | DeclarationName Entity); |
1530 | QualType BuildBlockPointerType(QualType T, |
1531 | SourceLocation Loc, DeclarationName Entity); |
1532 | QualType BuildParenType(QualType T); |
1533 | QualType BuildAtomicType(QualType T, SourceLocation Loc); |
1534 | QualType BuildReadPipeType(QualType T, |
1535 | SourceLocation Loc); |
1536 | QualType BuildWritePipeType(QualType T, |
1537 | SourceLocation Loc); |
1538 | |
1539 | TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); |
1540 | TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); |
1541 | |
1542 | /// Package the given type and TSI into a ParsedType. |
1543 | ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); |
1544 | DeclarationNameInfo GetNameForDeclarator(Declarator &D); |
1545 | DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); |
1546 | static QualType GetTypeFromParser(ParsedType Ty, |
1547 | TypeSourceInfo **TInfo = nullptr); |
1548 | CanThrowResult canThrow(const Expr *E); |
1549 | const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, |
1550 | const FunctionProtoType *FPT); |
1551 | void UpdateExceptionSpec(FunctionDecl *FD, |
1552 | const FunctionProtoType::ExceptionSpecInfo &ESI); |
1553 | bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); |
1554 | bool CheckDistantExceptionSpec(QualType T); |
1555 | bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); |
1556 | bool CheckEquivalentExceptionSpec( |
1557 | const FunctionProtoType *Old, SourceLocation OldLoc, |
1558 | const FunctionProtoType *New, SourceLocation NewLoc); |
1559 | bool CheckEquivalentExceptionSpec( |
1560 | const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, |
1561 | const FunctionProtoType *Old, SourceLocation OldLoc, |
1562 | const FunctionProtoType *New, SourceLocation NewLoc); |
1563 | bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); |
1564 | bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, |
1565 | const PartialDiagnostic &NestedDiagID, |
1566 | const PartialDiagnostic &NoteID, |
1567 | const PartialDiagnostic &NoThrowDiagID, |
1568 | const FunctionProtoType *Superset, |
1569 | SourceLocation SuperLoc, |
1570 | const FunctionProtoType *Subset, |
1571 | SourceLocation SubLoc); |
1572 | bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, |
1573 | const PartialDiagnostic &NoteID, |
1574 | const FunctionProtoType *Target, |
1575 | SourceLocation TargetLoc, |
1576 | const FunctionProtoType *Source, |
1577 | SourceLocation SourceLoc); |
1578 | |
1579 | TypeResult ActOnTypeName(Scope *S, Declarator &D); |
1580 | |
1581 | /// The parser has parsed the context-sensitive type 'instancetype' |
1582 | /// in an Objective-C message declaration. Return the appropriate type. |
1583 | ParsedType ActOnObjCInstanceType(SourceLocation Loc); |
1584 | |
1585 | /// Abstract class used to diagnose incomplete types. |
1586 | struct TypeDiagnoser { |
1587 | TypeDiagnoser() {} |
1588 | |
1589 | virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; |
1590 | virtual ~TypeDiagnoser() {} |
1591 | }; |
1592 | |
1593 | static int getPrintable(int I) { return I; } |
1594 | static unsigned getPrintable(unsigned I) { return I; } |
1595 | static bool getPrintable(bool B) { return B; } |
1596 | static const char * getPrintable(const char *S) { return S; } |
1597 | static StringRef getPrintable(StringRef S) { return S; } |
1598 | static const std::string &getPrintable(const std::string &S) { return S; } |
1599 | static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { |
1600 | return II; |
1601 | } |
1602 | static DeclarationName getPrintable(DeclarationName N) { return N; } |
1603 | static QualType getPrintable(QualType T) { return T; } |
1604 | static SourceRange getPrintable(SourceRange R) { return R; } |
1605 | static SourceRange getPrintable(SourceLocation L) { return L; } |
1606 | static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } |
1607 | static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} |
1608 | |
1609 | template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { |
1610 | unsigned DiagID; |
1611 | std::tuple<const Ts &...> Args; |
1612 | |
1613 | template <std::size_t... Is> |
1614 | void emit(const SemaDiagnosticBuilder &DB, |
1615 | llvm::index_sequence<Is...>) const { |
1616 | // Apply all tuple elements to the builder in order. |
1617 | bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; |
1618 | (void)Dummy; |
1619 | } |
1620 | |
1621 | public: |
1622 | BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) |
1623 | : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { |
1624 | assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ? static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 1624, __PRETTY_FUNCTION__)); |
1625 | } |
1626 | |
1627 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
1628 | const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); |
1629 | emit(DB, llvm::index_sequence_for<Ts...>()); |
1630 | DB << T; |
1631 | } |
1632 | }; |
1633 | |
1634 | private: |
1635 | /// Methods for marking which expressions involve dereferencing a pointer |
1636 | /// marked with the 'noderef' attribute. Expressions are checked bottom up as |
1637 | /// they are parsed, meaning that a noderef pointer may not be accessed. For |
1638 | /// example, in `&*p` where `p` is a noderef pointer, we will first parse the |
1639 | /// `*p`, but need to check that `address of` is called on it. This requires |
1640 | /// keeping a container of all pending expressions and checking if the address |
1641 | /// of them are eventually taken. |
1642 | void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); |
1643 | void CheckAddressOfNoDeref(const Expr *E); |
1644 | void CheckMemberAccessOfNoDeref(const MemberExpr *E); |
1645 | |
1646 | bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, |
1647 | TypeDiagnoser *Diagnoser); |
1648 | |
1649 | struct ModuleScope { |
1650 | SourceLocation BeginLoc; |
1651 | clang::Module *Module = nullptr; |
1652 | bool ModuleInterface = false; |
1653 | bool ImplicitGlobalModuleFragment = false; |
1654 | VisibleModuleSet OuterVisibleModules; |
1655 | }; |
1656 | /// The modules we're currently parsing. |
1657 | llvm::SmallVector<ModuleScope, 16> ModuleScopes; |
1658 | |
1659 | /// Namespace definitions that we will export when they finish. |
1660 | llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; |
1661 | |
1662 | /// Get the module whose scope we are currently within. |
1663 | Module *getCurrentModule() const { |
1664 | return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; |
1665 | } |
1666 | |
1667 | VisibleModuleSet VisibleModules; |
1668 | |
1669 | public: |
1670 | /// Get the module owning an entity. |
1671 | Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); } |
1672 | |
1673 | /// Make a merged definition of an existing hidden definition \p ND |
1674 | /// visible at the specified location. |
1675 | void makeMergedDefinitionVisible(NamedDecl *ND); |
1676 | |
1677 | bool isModuleVisible(const Module *M, bool ModulePrivate = false); |
1678 | |
1679 | /// Determine whether a declaration is visible to name lookup. |
1680 | bool isVisible(const NamedDecl *D) { |
1681 | return !D->isHidden() || isVisibleSlow(D); |
1682 | } |
1683 | |
1684 | /// Determine whether any declaration of an entity is visible. |
1685 | bool |
1686 | hasVisibleDeclaration(const NamedDecl *D, |
1687 | llvm::SmallVectorImpl<Module *> *Modules = nullptr) { |
1688 | return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); |
1689 | } |
1690 | bool hasVisibleDeclarationSlow(const NamedDecl *D, |
1691 | llvm::SmallVectorImpl<Module *> *Modules); |
1692 | |
1693 | bool hasVisibleMergedDefinition(NamedDecl *Def); |
1694 | bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); |
1695 | |
1696 | /// Determine if \p D and \p Suggested have a structurally compatible |
1697 | /// layout as described in C11 6.2.7/1. |
1698 | bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); |
1699 | |
1700 | /// Determine if \p D has a visible definition. If not, suggest a declaration |
1701 | /// that should be made visible to expose the definition. |
1702 | bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, |
1703 | bool OnlyNeedComplete = false); |
1704 | bool hasVisibleDefinition(const NamedDecl *D) { |
1705 | NamedDecl *Hidden; |
1706 | return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); |
1707 | } |
1708 | |
1709 | /// Determine if the template parameter \p D has a visible default argument. |
1710 | bool |
1711 | hasVisibleDefaultArgument(const NamedDecl *D, |
1712 | llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
1713 | |
1714 | /// Determine if there is a visible declaration of \p D that is an explicit |
1715 | /// specialization declaration for a specialization of a template. (For a |
1716 | /// member specialization, use hasVisibleMemberSpecialization.) |
1717 | bool hasVisibleExplicitSpecialization( |
1718 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
1719 | |
1720 | /// Determine if there is a visible declaration of \p D that is a member |
1721 | /// specialization declaration (as opposed to an instantiated declaration). |
1722 | bool hasVisibleMemberSpecialization( |
1723 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
1724 | |
1725 | /// Determine if \p A and \p B are equivalent internal linkage declarations |
1726 | /// from different modules, and thus an ambiguity error can be downgraded to |
1727 | /// an extension warning. |
1728 | bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, |
1729 | const NamedDecl *B); |
1730 | void diagnoseEquivalentInternalLinkageDeclarations( |
1731 | SourceLocation Loc, const NamedDecl *D, |
1732 | ArrayRef<const NamedDecl *> Equiv); |
1733 | |
1734 | bool isUsualDeallocationFunction(const CXXMethodDecl *FD); |
1735 | |
1736 | bool isCompleteType(SourceLocation Loc, QualType T) { |
1737 | return !RequireCompleteTypeImpl(Loc, T, nullptr); |
1738 | } |
1739 | bool RequireCompleteType(SourceLocation Loc, QualType T, |
1740 | TypeDiagnoser &Diagnoser); |
1741 | bool RequireCompleteType(SourceLocation Loc, QualType T, |
1742 | unsigned DiagID); |
1743 | |
1744 | template <typename... Ts> |
1745 | bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, |
1746 | const Ts &...Args) { |
1747 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
1748 | return RequireCompleteType(Loc, T, Diagnoser); |
1749 | } |
1750 | |
1751 | void completeExprArrayBound(Expr *E); |
1752 | bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); |
1753 | bool RequireCompleteExprType(Expr *E, unsigned DiagID); |
1754 | |
1755 | template <typename... Ts> |
1756 | bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { |
1757 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
1758 | return RequireCompleteExprType(E, Diagnoser); |
1759 | } |
1760 | |
1761 | bool RequireLiteralType(SourceLocation Loc, QualType T, |
1762 | TypeDiagnoser &Diagnoser); |
1763 | bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); |
1764 | |
1765 | template <typename... Ts> |
1766 | bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, |
1767 | const Ts &...Args) { |
1768 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
1769 | return RequireLiteralType(Loc, T, Diagnoser); |
1770 | } |
1771 | |
1772 | QualType getElaboratedType(ElaboratedTypeKeyword Keyword, |
1773 | const CXXScopeSpec &SS, QualType T, |
1774 | TagDecl *OwnedTagDecl = nullptr); |
1775 | |
1776 | QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); |
1777 | /// If AsUnevaluated is false, E is treated as though it were an evaluated |
1778 | /// context, such as when building a type for decltype(auto). |
1779 | QualType BuildDecltypeType(Expr *E, SourceLocation Loc, |
1780 | bool AsUnevaluated = true); |
1781 | QualType BuildUnaryTransformType(QualType BaseType, |
1782 | UnaryTransformType::UTTKind UKind, |
1783 | SourceLocation Loc); |
1784 | |
1785 | //===--------------------------------------------------------------------===// |
1786 | // Symbol table / Decl tracking callbacks: SemaDecl.cpp. |
1787 | // |
1788 | |
1789 | struct SkipBodyInfo { |
1790 | SkipBodyInfo() |
1791 | : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), |
1792 | New(nullptr) {} |
1793 | bool ShouldSkip; |
1794 | bool CheckSameAsPrevious; |
1795 | NamedDecl *Previous; |
1796 | NamedDecl *New; |
1797 | }; |
1798 | |
1799 | DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); |
1800 | |
1801 | void DiagnoseUseOfUnimplementedSelectors(); |
1802 | |
1803 | bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; |
1804 | |
1805 | ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, |
1806 | Scope *S, CXXScopeSpec *SS = nullptr, |
1807 | bool isClassName = false, bool HasTrailingDot = false, |
1808 | ParsedType ObjectType = nullptr, |
1809 | bool IsCtorOrDtorName = false, |
1810 | bool WantNontrivialTypeSourceInfo = false, |
1811 | bool IsClassTemplateDeductionContext = true, |
1812 | IdentifierInfo **CorrectedII = nullptr); |
1813 | TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); |
1814 | bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); |
1815 | void DiagnoseUnknownTypeName(IdentifierInfo *&II, |
1816 | SourceLocation IILoc, |
1817 | Scope *S, |
1818 | CXXScopeSpec *SS, |
1819 | ParsedType &SuggestedType, |
1820 | bool IsTemplateName = false); |
1821 | |
1822 | /// Attempt to behave like MSVC in situations where lookup of an unqualified |
1823 | /// type name has failed in a dependent context. In these situations, we |
1824 | /// automatically form a DependentTypeName that will retry lookup in a related |
1825 | /// scope during instantiation. |
1826 | ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, |
1827 | SourceLocation NameLoc, |
1828 | bool IsTemplateTypeArg); |
1829 | |
1830 | /// Describes the result of the name lookup and resolution performed |
1831 | /// by \c ClassifyName(). |
1832 | enum NameClassificationKind { |
1833 | NC_Unknown, |
1834 | NC_Error, |
1835 | NC_Keyword, |
1836 | NC_Type, |
1837 | NC_Expression, |
1838 | NC_NestedNameSpecifier, |
1839 | NC_TypeTemplate, |
1840 | NC_VarTemplate, |
1841 | NC_FunctionTemplate, |
1842 | NC_UndeclaredTemplate, |
1843 | }; |
1844 | |
1845 | class NameClassification { |
1846 | NameClassificationKind Kind; |
1847 | ExprResult Expr; |
1848 | TemplateName Template; |
1849 | ParsedType Type; |
1850 | |
1851 | explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} |
1852 | |
1853 | public: |
1854 | NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} |
1855 | |
1856 | NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} |
1857 | |
1858 | NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} |
1859 | |
1860 | static NameClassification Error() { |
1861 | return NameClassification(NC_Error); |
1862 | } |
1863 | |
1864 | static NameClassification Unknown() { |
1865 | return NameClassification(NC_Unknown); |
1866 | } |
1867 | |
1868 | static NameClassification NestedNameSpecifier() { |
1869 | return NameClassification(NC_NestedNameSpecifier); |
1870 | } |
1871 | |
1872 | static NameClassification TypeTemplate(TemplateName Name) { |
1873 | NameClassification Result(NC_TypeTemplate); |
1874 | Result.Template = Name; |
1875 | return Result; |
1876 | } |
1877 | |
1878 | static NameClassification VarTemplate(TemplateName Name) { |
1879 | NameClassification Result(NC_VarTemplate); |
1880 | Result.Template = Name; |
1881 | return Result; |
1882 | } |
1883 | |
1884 | static NameClassification FunctionTemplate(TemplateName Name) { |
1885 | NameClassification Result(NC_FunctionTemplate); |
1886 | Result.Template = Name; |
1887 | return Result; |
1888 | } |
1889 | |
1890 | static NameClassification UndeclaredTemplate(TemplateName Name) { |
1891 | NameClassification Result(NC_UndeclaredTemplate); |
1892 | Result.Template = Name; |
1893 | return Result; |
1894 | } |
1895 | |
1896 | NameClassificationKind getKind() const { return Kind; } |
1897 | |
1898 | ParsedType getType() const { |
1899 | assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail ("Kind == NC_Type", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 1899, __PRETTY_FUNCTION__)); |
1900 | return Type; |
1901 | } |
1902 | |
1903 | ExprResult getExpression() const { |
1904 | assert(Kind == NC_Expression)((Kind == NC_Expression) ? static_cast<void> (0) : __assert_fail ("Kind == NC_Expression", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 1904, __PRETTY_FUNCTION__)); |
1905 | return Expr; |
1906 | } |
1907 | |
1908 | TemplateName getTemplateName() const { |
1909 | assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast <void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 1910, __PRETTY_FUNCTION__)) |
1910 | Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast <void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 1910, __PRETTY_FUNCTION__)); |
1911 | return Template; |
1912 | } |
1913 | |
1914 | TemplateNameKind getTemplateNameKind() const { |
1915 | switch (Kind) { |
1916 | case NC_TypeTemplate: |
1917 | return TNK_Type_template; |
1918 | case NC_FunctionTemplate: |
1919 | return TNK_Function_template; |
1920 | case NC_VarTemplate: |
1921 | return TNK_Var_template; |
1922 | case NC_UndeclaredTemplate: |
1923 | return TNK_Undeclared_template; |
1924 | default: |
1925 | llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification." , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 1925); |
1926 | } |
1927 | } |
1928 | }; |
1929 | |
1930 | /// Perform name lookup on the given name, classifying it based on |
1931 | /// the results of name lookup and the following token. |
1932 | /// |
1933 | /// This routine is used by the parser to resolve identifiers and help direct |
1934 | /// parsing. When the identifier cannot be found, this routine will attempt |
1935 | /// to correct the typo and classify based on the resulting name. |
1936 | /// |
1937 | /// \param S The scope in which we're performing name lookup. |
1938 | /// |
1939 | /// \param SS The nested-name-specifier that precedes the name. |
1940 | /// |
1941 | /// \param Name The identifier. If typo correction finds an alternative name, |
1942 | /// this pointer parameter will be updated accordingly. |
1943 | /// |
1944 | /// \param NameLoc The location of the identifier. |
1945 | /// |
1946 | /// \param NextToken The token following the identifier. Used to help |
1947 | /// disambiguate the name. |
1948 | /// |
1949 | /// \param IsAddressOfOperand True if this name is the operand of a unary |
1950 | /// address of ('&') expression, assuming it is classified as an |
1951 | /// expression. |
1952 | /// |
1953 | /// \param CCC The correction callback, if typo correction is desired. |
1954 | NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, |
1955 | IdentifierInfo *&Name, SourceLocation NameLoc, |
1956 | const Token &NextToken, |
1957 | bool IsAddressOfOperand, |
1958 | CorrectionCandidateCallback *CCC = nullptr); |
1959 | |
1960 | /// Describes the detailed kind of a template name. Used in diagnostics. |
1961 | enum class TemplateNameKindForDiagnostics { |
1962 | ClassTemplate, |
1963 | FunctionTemplate, |
1964 | VarTemplate, |
1965 | AliasTemplate, |
1966 | TemplateTemplateParam, |
1967 | DependentTemplate |
1968 | }; |
1969 | TemplateNameKindForDiagnostics |
1970 | getTemplateNameKindForDiagnostics(TemplateName Name); |
1971 | |
1972 | /// Determine whether it's plausible that E was intended to be a |
1973 | /// template-name. |
1974 | bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { |
1975 | if (!getLangOpts().CPlusPlus || E.isInvalid()) |
1976 | return false; |
1977 | Dependent = false; |
1978 | if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) |
1979 | return !DRE->hasExplicitTemplateArgs(); |
1980 | if (auto *ME = dyn_cast<MemberExpr>(E.get())) |
1981 | return !ME->hasExplicitTemplateArgs(); |
1982 | Dependent = true; |
1983 | if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) |
1984 | return !DSDRE->hasExplicitTemplateArgs(); |
1985 | if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) |
1986 | return !DSME->hasExplicitTemplateArgs(); |
1987 | // Any additional cases recognized here should also be handled by |
1988 | // diagnoseExprIntendedAsTemplateName. |
1989 | return false; |
1990 | } |
1991 | void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, |
1992 | SourceLocation Less, |
1993 | SourceLocation Greater); |
1994 | |
1995 | Decl *ActOnDeclarator(Scope *S, Declarator &D); |
1996 | |
1997 | NamedDecl *HandleDeclarator(Scope *S, Declarator &D, |
1998 | MultiTemplateParamsArg TemplateParameterLists); |
1999 | void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); |
2000 | bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); |
2001 | bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, |
2002 | DeclarationName Name, SourceLocation Loc, |
2003 | bool IsTemplateId); |
2004 | void |
2005 | diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, |
2006 | SourceLocation FallbackLoc, |
2007 | SourceLocation ConstQualLoc = SourceLocation(), |
2008 | SourceLocation VolatileQualLoc = SourceLocation(), |
2009 | SourceLocation RestrictQualLoc = SourceLocation(), |
2010 | SourceLocation AtomicQualLoc = SourceLocation(), |
2011 | SourceLocation UnalignedQualLoc = SourceLocation()); |
2012 | |
2013 | static bool adjustContextForLocalExternDecl(DeclContext *&DC); |
2014 | void DiagnoseFunctionSpecifiers(const DeclSpec &DS); |
2015 | NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, |
2016 | const LookupResult &R); |
2017 | NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); |
2018 | void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, |
2019 | const LookupResult &R); |
2020 | void CheckShadow(Scope *S, VarDecl *D); |
2021 | |
2022 | /// Warn if 'E', which is an expression that is about to be modified, refers |
2023 | /// to a shadowing declaration. |
2024 | void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); |
2025 | |
2026 | void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); |
2027 | |
2028 | private: |
2029 | /// Map of current shadowing declarations to shadowed declarations. Warn if |
2030 | /// it looks like the user is trying to modify the shadowing declaration. |
2031 | llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; |
2032 | |
2033 | public: |
2034 | void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); |
2035 | void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); |
2036 | void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, |
2037 | TypedefNameDecl *NewTD); |
2038 | void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); |
2039 | NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, |
2040 | TypeSourceInfo *TInfo, |
2041 | LookupResult &Previous); |
2042 | NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, |
2043 | LookupResult &Previous, bool &Redeclaration); |
2044 | NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, |
2045 | TypeSourceInfo *TInfo, |
2046 | LookupResult &Previous, |
2047 | MultiTemplateParamsArg TemplateParamLists, |
2048 | bool &AddToScope, |
2049 | ArrayRef<BindingDecl *> Bindings = None); |
2050 | NamedDecl * |
2051 | ActOnDecompositionDeclarator(Scope *S, Declarator &D, |
2052 | MultiTemplateParamsArg TemplateParamLists); |
2053 | // Returns true if the variable declaration is a redeclaration |
2054 | bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); |
2055 | void CheckVariableDeclarationType(VarDecl *NewVD); |
2056 | bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, |
2057 | Expr *Init); |
2058 | void CheckCompleteVariableDeclaration(VarDecl *VD); |
2059 | void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); |
2060 | void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); |
2061 | |
2062 | NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, |
2063 | TypeSourceInfo *TInfo, |
2064 | LookupResult &Previous, |
2065 | MultiTemplateParamsArg TemplateParamLists, |
2066 | bool &AddToScope); |
2067 | bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); |
2068 | |
2069 | bool CheckConstexprFunctionDecl(const FunctionDecl *FD); |
2070 | bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); |
2071 | |
2072 | void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); |
2073 | void FindHiddenVirtualMethods(CXXMethodDecl *MD, |
2074 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); |
2075 | void NoteHiddenVirtualMethods(CXXMethodDecl *MD, |
2076 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); |
2077 | // Returns true if the function declaration is a redeclaration |
2078 | bool CheckFunctionDeclaration(Scope *S, |
2079 | FunctionDecl *NewFD, LookupResult &Previous, |
2080 | bool IsMemberSpecialization); |
2081 | bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); |
2082 | bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, |
2083 | QualType NewT, QualType OldT); |
2084 | void CheckMain(FunctionDecl *FD, const DeclSpec &D); |
2085 | void CheckMSVCRTEntryPoint(FunctionDecl *FD); |
2086 | Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); |
2087 | Decl *ActOnParamDeclarator(Scope *S, Declarator &D); |
2088 | ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, |
2089 | SourceLocation Loc, |
2090 | QualType T); |
2091 | ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, |
2092 | SourceLocation NameLoc, IdentifierInfo *Name, |
2093 | QualType T, TypeSourceInfo *TSInfo, |
2094 | StorageClass SC); |
2095 | void ActOnParamDefaultArgument(Decl *param, |
2096 | SourceLocation EqualLoc, |
2097 | Expr *defarg); |
2098 | void ActOnParamUnparsedDefaultArgument(Decl *param, |
2099 | SourceLocation EqualLoc, |
2100 | SourceLocation ArgLoc); |
2101 | void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); |
2102 | bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, |
2103 | SourceLocation EqualLoc); |
2104 | |
2105 | void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); |
2106 | void ActOnUninitializedDecl(Decl *dcl); |
2107 | void ActOnInitializerError(Decl *Dcl); |
2108 | |
2109 | void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); |
2110 | void ActOnCXXForRangeDecl(Decl *D); |
2111 | StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, |
2112 | IdentifierInfo *Ident, |
2113 | ParsedAttributes &Attrs, |
2114 | SourceLocation AttrEnd); |
2115 | void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); |
2116 | void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); |
2117 | void CheckStaticLocalForDllExport(VarDecl *VD); |
2118 | void FinalizeDeclaration(Decl *D); |
2119 | DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, |
2120 | ArrayRef<Decl *> Group); |
2121 | DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); |
2122 | |
2123 | /// Should be called on all declarations that might have attached |
2124 | /// documentation comments. |
2125 | void ActOnDocumentableDecl(Decl *D); |
2126 | void ActOnDocumentableDecls(ArrayRef<Decl *> Group); |
2127 | |
2128 | void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, |
2129 | SourceLocation LocAfterDecls); |
2130 | void CheckForFunctionRedefinition( |
2131 | FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, |
2132 | SkipBodyInfo *SkipBody = nullptr); |
2133 | Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, |
2134 | MultiTemplateParamsArg TemplateParamLists, |
2135 | SkipBodyInfo *SkipBody = nullptr); |
2136 | Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, |
2137 | SkipBodyInfo *SkipBody = nullptr); |
2138 | void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); |
2139 | bool isObjCMethodDecl(Decl *D) { |
2140 | return D && isa<ObjCMethodDecl>(D); |
2141 | } |
2142 | |
2143 | /// Determine whether we can delay parsing the body of a function or |
2144 | /// function template until it is used, assuming we don't care about emitting |
2145 | /// code for that function. |
2146 | /// |
2147 | /// This will be \c false if we may need the body of the function in the |
2148 | /// middle of parsing an expression (where it's impractical to switch to |
2149 | /// parsing a different function), for instance, if it's constexpr in C++11 |
2150 | /// or has an 'auto' return type in C++14. These cases are essentially bugs. |
2151 | bool canDelayFunctionBody(const Declarator &D); |
2152 | |
2153 | /// Determine whether we can skip parsing the body of a function |
2154 | /// definition, assuming we don't care about analyzing its body or emitting |
2155 | /// code for that function. |
2156 | /// |
2157 | /// This will be \c false only if we may need the body of the function in |
2158 | /// order to parse the rest of the program (for instance, if it is |
2159 | /// \c constexpr in C++11 or has an 'auto' return type in C++14). |
2160 | bool canSkipFunctionBody(Decl *D); |
2161 | |
2162 | void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); |
2163 | Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); |
2164 | Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); |
2165 | Decl *ActOnSkippedFunctionBody(Decl *Decl); |
2166 | void ActOnFinishInlineFunctionDef(FunctionDecl *D); |
2167 | |
2168 | /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an |
2169 | /// attribute for which parsing is delayed. |
2170 | void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); |
2171 | |
2172 | /// Diagnose any unused parameters in the given sequence of |
2173 | /// ParmVarDecl pointers. |
2174 | void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); |
2175 | |
2176 | /// Diagnose whether the size of parameters or return value of a |
2177 | /// function or obj-c method definition is pass-by-value and larger than a |
2178 | /// specified threshold. |
2179 | void |
2180 | DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, |
2181 | QualType ReturnTy, NamedDecl *D); |
2182 | |
2183 | void DiagnoseInvalidJumps(Stmt *Body); |
2184 | Decl *ActOnFileScopeAsmDecl(Expr *expr, |
2185 | SourceLocation AsmLoc, |
2186 | SourceLocation RParenLoc); |
2187 | |
2188 | /// Handle a C++11 empty-declaration and attribute-declaration. |
2189 | Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, |
2190 | SourceLocation SemiLoc); |
2191 | |
2192 | enum class ModuleDeclKind { |
2193 | Interface, ///< 'export module X;' |
2194 | Implementation, ///< 'module X;' |
2195 | }; |
2196 | |
2197 | /// The parser has processed a module-declaration that begins the definition |
2198 | /// of a module interface or implementation. |
2199 | DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, |
2200 | SourceLocation ModuleLoc, ModuleDeclKind MDK, |
2201 | ModuleIdPath Path, bool IsFirstDecl); |
2202 | |
2203 | /// The parser has processed a global-module-fragment declaration that begins |
2204 | /// the definition of the global module fragment of the current module unit. |
2205 | /// \param ModuleLoc The location of the 'module' keyword. |
2206 | DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); |
2207 | |
2208 | /// The parser has processed a private-module-fragment declaration that begins |
2209 | /// the definition of the private module fragment of the current module unit. |
2210 | /// \param ModuleLoc The location of the 'module' keyword. |
2211 | /// \param PrivateLoc The location of the 'private' keyword. |
2212 | DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, |
2213 | SourceLocation PrivateLoc); |
2214 | |
2215 | /// The parser has processed a module import declaration. |
2216 | /// |
2217 | /// \param StartLoc The location of the first token in the declaration. This |
2218 | /// could be the location of an '@', 'export', or 'import'. |
2219 | /// \param ExportLoc The location of the 'export' keyword, if any. |
2220 | /// \param ImportLoc The location of the 'import' keyword. |
2221 | /// \param Path The module access path. |
2222 | DeclResult ActOnModuleImport(SourceLocation StartLoc, |
2223 | SourceLocation ExportLoc, |
2224 | SourceLocation ImportLoc, ModuleIdPath Path); |
2225 | DeclResult ActOnModuleImport(SourceLocation StartLoc, |
2226 | SourceLocation ExportLoc, |
2227 | SourceLocation ImportLoc, Module *M, |
2228 | ModuleIdPath Path = {}); |
2229 | |
2230 | /// The parser has processed a module import translated from a |
2231 | /// #include or similar preprocessing directive. |
2232 | void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); |
2233 | void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); |
2234 | |
2235 | /// The parsed has entered a submodule. |
2236 | void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); |
2237 | /// The parser has left a submodule. |
2238 | void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); |
2239 | |
2240 | /// Create an implicit import of the given module at the given |
2241 | /// source location, for error recovery, if possible. |
2242 | /// |
2243 | /// This routine is typically used when an entity found by name lookup |
2244 | /// is actually hidden within a module that we know about but the user |
2245 | /// has forgotten to import. |
2246 | void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, |
2247 | Module *Mod); |
2248 | |
2249 | /// Kinds of missing import. Note, the values of these enumerators correspond |
2250 | /// to %select values in diagnostics. |
2251 | enum class MissingImportKind { |
2252 | Declaration, |
2253 | Definition, |
2254 | DefaultArgument, |
2255 | ExplicitSpecialization, |
2256 | PartialSpecialization |
2257 | }; |
2258 | |
2259 | /// Diagnose that the specified declaration needs to be visible but |
2260 | /// isn't, and suggest a module import that would resolve the problem. |
2261 | void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, |
2262 | MissingImportKind MIK, bool Recover = true); |
2263 | void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, |
2264 | SourceLocation DeclLoc, ArrayRef<Module *> Modules, |
2265 | MissingImportKind MIK, bool Recover); |
2266 | |
2267 | Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, |
2268 | SourceLocation LBraceLoc); |
2269 | Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, |
2270 | SourceLocation RBraceLoc); |
2271 | |
2272 | /// We've found a use of a templated declaration that would trigger an |
2273 | /// implicit instantiation. Check that any relevant explicit specializations |
2274 | /// and partial specializations are visible, and diagnose if not. |
2275 | void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); |
2276 | |
2277 | /// We've found a use of a template specialization that would select a |
2278 | /// partial specialization. Check that the partial specialization is visible, |
2279 | /// and diagnose if not. |
2280 | void checkPartialSpecializationVisibility(SourceLocation Loc, |
2281 | NamedDecl *Spec); |
2282 | |
2283 | /// Retrieve a suitable printing policy for diagnostics. |
2284 | PrintingPolicy getPrintingPolicy() const { |
2285 | return getPrintingPolicy(Context, PP); |
2286 | } |
2287 | |
2288 | /// Retrieve a suitable printing policy for diagnostics. |
2289 | static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, |
2290 | const Preprocessor &PP); |
2291 | |
2292 | /// Scope actions. |
2293 | void ActOnPopScope(SourceLocation Loc, Scope *S); |
2294 | void ActOnTranslationUnitScope(Scope *S); |
2295 | |
2296 | Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
2297 | RecordDecl *&AnonRecord); |
2298 | Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
2299 | MultiTemplateParamsArg TemplateParams, |
2300 | bool IsExplicitInstantiation, |
2301 | RecordDecl *&AnonRecord); |
2302 | |
2303 | Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, |
2304 | AccessSpecifier AS, |
2305 | RecordDecl *Record, |
2306 | const PrintingPolicy &Policy); |
2307 | |
2308 | Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, |
2309 | RecordDecl *Record); |
2310 | |
2311 | /// Common ways to introduce type names without a tag for use in diagnostics. |
2312 | /// Keep in sync with err_tag_reference_non_tag. |
2313 | enum NonTagKind { |
2314 | NTK_NonStruct, |
2315 | NTK_NonClass, |
2316 | NTK_NonUnion, |
2317 | NTK_NonEnum, |
2318 | NTK_Typedef, |
2319 | NTK_TypeAlias, |
2320 | NTK_Template, |
2321 | NTK_TypeAliasTemplate, |
2322 | NTK_TemplateTemplateArgument, |
2323 | }; |
2324 | |
2325 | /// Given a non-tag type declaration, returns an enum useful for indicating |
2326 | /// what kind of non-tag type this is. |
2327 | NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); |
2328 | |
2329 | bool isAcceptableTagRedeclaration(const TagDecl *Previous, |
2330 | TagTypeKind NewTag, bool isDefinition, |
2331 | SourceLocation NewTagLoc, |
2332 | const IdentifierInfo *Name); |
2333 | |
2334 | enum TagUseKind { |
2335 | TUK_Reference, // Reference to a tag: 'struct foo *X;' |
2336 | TUK_Declaration, // Fwd decl of a tag: 'struct foo;' |
2337 | TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' |
2338 | TUK_Friend // Friend declaration: 'friend struct foo;' |
2339 | }; |
2340 | |
2341 | Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, |
2342 | SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, |
2343 | SourceLocation NameLoc, const ParsedAttributesView &Attr, |
2344 | AccessSpecifier AS, SourceLocation ModulePrivateLoc, |
2345 | MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, |
2346 | bool &IsDependent, SourceLocation ScopedEnumKWLoc, |
2347 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, |
2348 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, |
2349 | SkipBodyInfo *SkipBody = nullptr); |
2350 | |
2351 | Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, |
2352 | unsigned TagSpec, SourceLocation TagLoc, |
2353 | CXXScopeSpec &SS, IdentifierInfo *Name, |
2354 | SourceLocation NameLoc, |
2355 | const ParsedAttributesView &Attr, |
2356 | MultiTemplateParamsArg TempParamLists); |
2357 | |
2358 | TypeResult ActOnDependentTag(Scope *S, |
2359 | unsigned TagSpec, |
2360 | TagUseKind TUK, |
2361 | const CXXScopeSpec &SS, |
2362 | IdentifierInfo *Name, |
2363 | SourceLocation TagLoc, |
2364 | SourceLocation NameLoc); |
2365 | |
2366 | void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, |
2367 | IdentifierInfo *ClassName, |
2368 | SmallVectorImpl<Decl *> &Decls); |
2369 | Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, |
2370 | Declarator &D, Expr *BitfieldWidth); |
2371 | |
2372 | FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, |
2373 | Declarator &D, Expr *BitfieldWidth, |
2374 | InClassInitStyle InitStyle, |
2375 | AccessSpecifier AS); |
2376 | MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, |
2377 | SourceLocation DeclStart, Declarator &D, |
2378 | Expr *BitfieldWidth, |
2379 | InClassInitStyle InitStyle, |
2380 | AccessSpecifier AS, |
2381 | const ParsedAttr &MSPropertyAttr); |
2382 | |
2383 | FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, |
2384 | TypeSourceInfo *TInfo, |
2385 | RecordDecl *Record, SourceLocation Loc, |
2386 | bool Mutable, Expr *BitfieldWidth, |
2387 | InClassInitStyle InitStyle, |
2388 | SourceLocation TSSL, |
2389 | AccessSpecifier AS, NamedDecl *PrevDecl, |
2390 | Declarator *D = nullptr); |
2391 | |
2392 | bool CheckNontrivialField(FieldDecl *FD); |
2393 | void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); |
2394 | |
2395 | enum TrivialABIHandling { |
2396 | /// The triviality of a method unaffected by "trivial_abi". |
2397 | TAH_IgnoreTrivialABI, |
2398 | |
2399 | /// The triviality of a method affected by "trivial_abi". |
2400 | TAH_ConsiderTrivialABI |
2401 | }; |
2402 | |
2403 | bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, |
2404 | TrivialABIHandling TAH = TAH_IgnoreTrivialABI, |
2405 | bool Diagnose = false); |
2406 | CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); |
2407 | void ActOnLastBitfield(SourceLocation DeclStart, |
2408 | SmallVectorImpl<Decl *> &AllIvarDecls); |
2409 | Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, |
2410 | Declarator &D, Expr *BitfieldWidth, |
2411 | tok::ObjCKeywordKind visibility); |
2412 | |
2413 | // This is used for both record definitions and ObjC interface declarations. |
2414 | void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, |
2415 | ArrayRef<Decl *> Fields, SourceLocation LBrac, |
2416 | SourceLocation RBrac, const ParsedAttributesView &AttrList); |
2417 | |
2418 | /// ActOnTagStartDefinition - Invoked when we have entered the |
2419 | /// scope of a tag's definition (e.g., for an enumeration, class, |
2420 | /// struct, or union). |
2421 | void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); |
2422 | |
2423 | /// Perform ODR-like check for C/ObjC when merging tag types from modules. |
2424 | /// Differently from C++, actually parse the body and reject / error out |
2425 | /// in case of a structural mismatch. |
2426 | bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, |
2427 | SkipBodyInfo &SkipBody); |
2428 | |
2429 | typedef void *SkippedDefinitionContext; |
2430 | |
2431 | /// Invoked when we enter a tag definition that we're skipping. |
2432 | SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); |
2433 | |
2434 | Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); |
2435 | |
2436 | /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a |
2437 | /// C++ record definition's base-specifiers clause and are starting its |
2438 | /// member declarations. |
2439 | void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, |
2440 | SourceLocation FinalLoc, |
2441 | bool IsFinalSpelledSealed, |
2442 | SourceLocation LBraceLoc); |
2443 | |
2444 | /// ActOnTagFinishDefinition - Invoked once we have finished parsing |
2445 | /// the definition of a tag (enumeration, class, struct, or union). |
2446 | void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, |
2447 | SourceRange BraceRange); |
2448 | |
2449 | void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); |
2450 | |
2451 | void ActOnObjCContainerFinishDefinition(); |
2452 | |
2453 | /// Invoked when we must temporarily exit the objective-c container |
2454 | /// scope for parsing/looking-up C constructs. |
2455 | /// |
2456 | /// Must be followed by a call to \see ActOnObjCReenterContainerContext |
2457 | void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); |
2458 | void ActOnObjCReenterContainerContext(DeclContext *DC); |
2459 | |
2460 | /// ActOnTagDefinitionError - Invoked when there was an unrecoverable |
2461 | /// error parsing the definition of a tag. |
2462 | void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); |
2463 | |
2464 | EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, |
2465 | EnumConstantDecl *LastEnumConst, |
2466 | SourceLocation IdLoc, |
2467 | IdentifierInfo *Id, |
2468 | Expr *val); |
2469 | bool CheckEnumUnderlyingType(TypeSourceInfo *TI); |
2470 | bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, |
2471 | QualType EnumUnderlyingTy, bool IsFixed, |
2472 | const EnumDecl *Prev); |
2473 | |
2474 | /// Determine whether the body of an anonymous enumeration should be skipped. |
2475 | /// \param II The name of the first enumerator. |
2476 | SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, |
2477 | SourceLocation IILoc); |
2478 | |
2479 | Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, |
2480 | SourceLocation IdLoc, IdentifierInfo *Id, |
2481 | const ParsedAttributesView &Attrs, |
2482 | SourceLocation EqualLoc, Expr *Val); |
2483 | void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, |
2484 | Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, |
2485 | const ParsedAttributesView &Attr); |
2486 | |
2487 | DeclContext *getContainingDC(DeclContext *DC); |
2488 | |
2489 | /// Set the current declaration context until it gets popped. |
2490 | void PushDeclContext(Scope *S, DeclContext *DC); |
2491 | void PopDeclContext(); |
2492 | |
2493 | /// EnterDeclaratorContext - Used when we must lookup names in the context |
2494 | /// of a declarator's nested name specifier. |
2495 | void EnterDeclaratorContext(Scope *S, DeclContext *DC); |
2496 | void ExitDeclaratorContext(Scope *S); |
2497 | |
2498 | /// Push the parameters of D, which must be a function, into scope. |
2499 | void ActOnReenterFunctionContext(Scope* S, Decl* D); |
2500 | void ActOnExitFunctionContext(); |
2501 | |
2502 | DeclContext *getFunctionLevelDeclContext(); |
2503 | |
2504 | /// getCurFunctionDecl - If inside of a function body, this returns a pointer |
2505 | /// to the function decl for the function being parsed. If we're currently |
2506 | /// in a 'block', this returns the containing context. |
2507 | FunctionDecl *getCurFunctionDecl(); |
2508 | |
2509 | /// getCurMethodDecl - If inside of a method body, this returns a pointer to |
2510 | /// the method decl for the method being parsed. If we're currently |
2511 | /// in a 'block', this returns the containing context. |
2512 | ObjCMethodDecl *getCurMethodDecl(); |
2513 | |
2514 | /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method |
2515 | /// or C function we're in, otherwise return null. If we're currently |
2516 | /// in a 'block', this returns the containing context. |
2517 | NamedDecl *getCurFunctionOrMethodDecl(); |
2518 | |
2519 | /// Add this decl to the scope shadowed decl chains. |
2520 | void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); |
2521 | |
2522 | /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true |
2523 | /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns |
2524 | /// true if 'D' belongs to the given declaration context. |
2525 | /// |
2526 | /// \param AllowInlineNamespace If \c true, allow the declaration to be in the |
2527 | /// enclosing namespace set of the context, rather than contained |
2528 | /// directly within it. |
2529 | bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, |
2530 | bool AllowInlineNamespace = false); |
2531 | |
2532 | /// Finds the scope corresponding to the given decl context, if it |
2533 | /// happens to be an enclosing scope. Otherwise return NULL. |
2534 | static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); |
2535 | |
2536 | /// Subroutines of ActOnDeclarator(). |
2537 | TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, |
2538 | TypeSourceInfo *TInfo); |
2539 | bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); |
2540 | |
2541 | /// Describes the kind of merge to perform for availability |
2542 | /// attributes (including "deprecated", "unavailable", and "availability"). |
2543 | enum AvailabilityMergeKind { |
2544 | /// Don't merge availability attributes at all. |
2545 | AMK_None, |
2546 | /// Merge availability attributes for a redeclaration, which requires |
2547 | /// an exact match. |
2548 | AMK_Redeclaration, |
2549 | /// Merge availability attributes for an override, which requires |
2550 | /// an exact match or a weakening of constraints. |
2551 | AMK_Override, |
2552 | /// Merge availability attributes for an implementation of |
2553 | /// a protocol requirement. |
2554 | AMK_ProtocolImplementation, |
2555 | }; |
2556 | |
2557 | /// Describes the kind of priority given to an availability attribute. |
2558 | /// |
2559 | /// The sum of priorities deteremines the final priority of the attribute. |
2560 | /// The final priority determines how the attribute will be merged. |
2561 | /// An attribute with a lower priority will always remove higher priority |
2562 | /// attributes for the specified platform when it is being applied. An |
2563 | /// attribute with a higher priority will not be applied if the declaration |
2564 | /// already has an availability attribute with a lower priority for the |
2565 | /// specified platform. The final prirority values are not expected to match |
2566 | /// the values in this enumeration, but instead should be treated as a plain |
2567 | /// integer value. This enumeration just names the priority weights that are |
2568 | /// used to calculate that final vaue. |
2569 | enum AvailabilityPriority : int { |
2570 | /// The availability attribute was specified explicitly next to the |
2571 | /// declaration. |
2572 | AP_Explicit = 0, |
2573 | |
2574 | /// The availability attribute was applied using '#pragma clang attribute'. |
2575 | AP_PragmaClangAttribute = 1, |
2576 | |
2577 | /// The availability attribute for a specific platform was inferred from |
2578 | /// an availability attribute for another platform. |
2579 | AP_InferredFromOtherPlatform = 2 |
2580 | }; |
2581 | |
2582 | /// Attribute merging methods. Return true if a new attribute was added. |
2583 | AvailabilityAttr *mergeAvailabilityAttr( |
2584 | NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit, |
2585 | VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, |
2586 | bool IsUnavailable, StringRef Message, bool IsStrict, |
2587 | StringRef Replacement, AvailabilityMergeKind AMK, int Priority, |
2588 | unsigned AttrSpellingListIndex); |
2589 | TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, |
2590 | TypeVisibilityAttr::VisibilityType Vis, |
2591 | unsigned AttrSpellingListIndex); |
2592 | VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, |
2593 | VisibilityAttr::VisibilityType Vis, |
2594 | unsigned AttrSpellingListIndex); |
2595 | UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range, |
2596 | unsigned AttrSpellingListIndex, StringRef Uuid); |
2597 | DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range, |
2598 | unsigned AttrSpellingListIndex); |
2599 | DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range, |
2600 | unsigned AttrSpellingListIndex); |
2601 | MSInheritanceAttr * |
2602 | mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, |
2603 | unsigned AttrSpellingListIndex, |
2604 | MSInheritanceAttr::Spelling SemanticSpelling); |
2605 | FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, |
2606 | IdentifierInfo *Format, int FormatIdx, |
2607 | int FirstArg, unsigned AttrSpellingListIndex); |
2608 | SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, |
2609 | unsigned AttrSpellingListIndex); |
2610 | CodeSegAttr *mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name, |
2611 | unsigned AttrSpellingListIndex); |
2612 | AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range, |
2613 | IdentifierInfo *Ident, |
2614 | unsigned AttrSpellingListIndex); |
2615 | MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range, |
2616 | unsigned AttrSpellingListIndex); |
2617 | NoSpeculativeLoadHardeningAttr * |
2618 | mergeNoSpeculativeLoadHardeningAttr(Decl *D, |
2619 | const NoSpeculativeLoadHardeningAttr &AL); |
2620 | SpeculativeLoadHardeningAttr * |
2621 | mergeSpeculativeLoadHardeningAttr(Decl *D, |
2622 | const SpeculativeLoadHardeningAttr &AL); |
2623 | OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range, |
2624 | unsigned AttrSpellingListIndex); |
2625 | InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); |
2626 | InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, |
2627 | const InternalLinkageAttr &AL); |
2628 | CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); |
2629 | CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); |
2630 | |
2631 | void mergeDeclAttributes(NamedDecl *New, Decl *Old, |
2632 | AvailabilityMergeKind AMK = AMK_Redeclaration); |
2633 | void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, |
2634 | LookupResult &OldDecls); |
2635 | bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, |
2636 | bool MergeTypeWithOld); |
2637 | bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, |
2638 | Scope *S, bool MergeTypeWithOld); |
2639 | void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); |
2640 | void MergeVarDecl(VarDecl *New, LookupResult &Previous); |
2641 | void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); |
2642 | void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); |
2643 | bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); |
2644 | void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); |
2645 | bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); |
2646 | |
2647 | // AssignmentAction - This is used by all the assignment diagnostic functions |
2648 | // to represent what is actually causing the operation |
2649 | enum AssignmentAction { |
2650 | AA_Assigning, |
2651 | AA_Passing, |
2652 | AA_Returning, |
2653 | AA_Converting, |
2654 | AA_Initializing, |
2655 | AA_Sending, |
2656 | AA_Casting, |
2657 | AA_Passing_CFAudited |
2658 | }; |
2659 | |
2660 | /// C++ Overloading. |
2661 | enum OverloadKind { |
2662 | /// This is a legitimate overload: the existing declarations are |
2663 | /// functions or function templates with different signatures. |
2664 | Ovl_Overload, |
2665 | |
2666 | /// This is not an overload because the signature exactly matches |
2667 | /// an existing declaration. |
2668 | Ovl_Match, |
2669 | |
2670 | /// This is not an overload because the lookup results contain a |
2671 | /// non-function. |
2672 | Ovl_NonFunction |
2673 | }; |
2674 | OverloadKind CheckOverload(Scope *S, |
2675 | FunctionDecl *New, |
2676 | const LookupResult &OldDecls, |
2677 | NamedDecl *&OldDecl, |
2678 | bool IsForUsingDecl); |
2679 | bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, |
2680 | bool ConsiderCudaAttrs = true); |
2681 | |
2682 | ImplicitConversionSequence |
2683 | TryImplicitConversion(Expr *From, QualType ToType, |
2684 | bool SuppressUserConversions, |
2685 | bool AllowExplicit, |
2686 | bool InOverloadResolution, |
2687 | bool CStyle, |
2688 | bool AllowObjCWritebackConversion); |
2689 | |
2690 | bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); |
2691 | bool IsFloatingPointPromotion(QualType FromType, QualType ToType); |
2692 | bool IsComplexPromotion(QualType FromType, QualType ToType); |
2693 | bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, |
2694 | bool InOverloadResolution, |
2695 | QualType& ConvertedType, bool &IncompatibleObjC); |
2696 | bool isObjCPointerConversion(QualType FromType, QualType ToType, |
2697 | QualType& ConvertedType, bool &IncompatibleObjC); |
2698 | bool isObjCWritebackConversion(QualType FromType, QualType ToType, |
2699 | QualType &ConvertedType); |
2700 | bool IsBlockPointerConversion(QualType FromType, QualType ToType, |
2701 | QualType& ConvertedType); |
2702 | bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, |
2703 | const FunctionProtoType *NewType, |
2704 | unsigned *ArgPos = nullptr); |
2705 | void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, |
2706 | QualType FromType, QualType ToType); |
2707 | |
2708 | void maybeExtendBlockObject(ExprResult &E); |
2709 | CastKind PrepareCastToObjCObjectPointer(ExprResult &E); |
2710 | bool CheckPointerConversion(Expr *From, QualType ToType, |
2711 | CastKind &Kind, |
2712 | CXXCastPath& BasePath, |
2713 | bool IgnoreBaseAccess, |
2714 | bool Diagnose = true); |
2715 | bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, |
2716 | bool InOverloadResolution, |
2717 | QualType &ConvertedType); |
2718 | bool CheckMemberPointerConversion(Expr *From, QualType ToType, |
2719 | CastKind &Kind, |
2720 | CXXCastPath &BasePath, |
2721 | bool IgnoreBaseAccess); |
2722 | bool IsQualificationConversion(QualType FromType, QualType ToType, |
2723 | bool CStyle, bool &ObjCLifetimeConversion); |
2724 | bool IsFunctionConversion(QualType FromType, QualType ToType, |
2725 | QualType &ResultTy); |
2726 | bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); |
2727 | bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); |
2728 | |
2729 | ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, |
2730 | const VarDecl *NRVOCandidate, |
2731 | QualType ResultType, |
2732 | Expr *Value, |
2733 | bool AllowNRVO = true); |
2734 | |
2735 | bool CanPerformCopyInitialization(const InitializedEntity &Entity, |
2736 | ExprResult Init); |
2737 | ExprResult PerformCopyInitialization(const InitializedEntity &Entity, |
2738 | SourceLocation EqualLoc, |
2739 | ExprResult Init, |
2740 | bool TopLevelOfInitList = false, |
2741 | bool AllowExplicit = false); |
2742 | ExprResult PerformObjectArgumentInitialization(Expr *From, |
2743 | NestedNameSpecifier *Qualifier, |
2744 | NamedDecl *FoundDecl, |
2745 | CXXMethodDecl *Method); |
2746 | |
2747 | /// Check that the lifetime of the initializer (and its subobjects) is |
2748 | /// sufficient for initializing the entity, and perform lifetime extension |
2749 | /// (when permitted) if not. |
2750 | void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); |
2751 | |
2752 | ExprResult PerformContextuallyConvertToBool(Expr *From); |
2753 | ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); |
2754 | |
2755 | /// Contexts in which a converted constant expression is required. |
2756 | enum CCEKind { |
2757 | CCEK_CaseValue, ///< Expression in a case label. |
2758 | CCEK_Enumerator, ///< Enumerator value with fixed underlying type. |
2759 | CCEK_TemplateArg, ///< Value of a non-type template parameter. |
2760 | CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. |
2761 | CCEK_ConstexprIf, ///< Condition in a constexpr if statement. |
2762 | CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. |
2763 | }; |
2764 | ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, |
2765 | llvm::APSInt &Value, CCEKind CCE); |
2766 | ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, |
2767 | APValue &Value, CCEKind CCE); |
2768 | |
2769 | /// Abstract base class used to perform a contextual implicit |
2770 | /// conversion from an expression to any type passing a filter. |
2771 | class ContextualImplicitConverter { |
2772 | public: |
2773 | bool Suppress; |
2774 | bool SuppressConversion; |
2775 | |
2776 | ContextualImplicitConverter(bool Suppress = false, |
2777 | bool SuppressConversion = false) |
2778 | : Suppress(Suppress), SuppressConversion(SuppressConversion) {} |
2779 | |
2780 | /// Determine whether the specified type is a valid destination type |
2781 | /// for this conversion. |
2782 | virtual bool match(QualType T) = 0; |
2783 | |
2784 | /// Emits a diagnostic complaining that the expression does not have |
2785 | /// integral or enumeration type. |
2786 | virtual SemaDiagnosticBuilder |
2787 | diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; |
2788 | |
2789 | /// Emits a diagnostic when the expression has incomplete class type. |
2790 | virtual SemaDiagnosticBuilder |
2791 | diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; |
2792 | |
2793 | /// Emits a diagnostic when the only matching conversion function |
2794 | /// is explicit. |
2795 | virtual SemaDiagnosticBuilder diagnoseExplicitConv( |
2796 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; |
2797 | |
2798 | /// Emits a note for the explicit conversion function. |
2799 | virtual SemaDiagnosticBuilder |
2800 | noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; |
2801 | |
2802 | /// Emits a diagnostic when there are multiple possible conversion |
2803 | /// functions. |
2804 | virtual SemaDiagnosticBuilder |
2805 | diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; |
2806 | |
2807 | /// Emits a note for one of the candidate conversions. |
2808 | virtual SemaDiagnosticBuilder |
2809 | noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; |
2810 | |
2811 | /// Emits a diagnostic when we picked a conversion function |
2812 | /// (for cases when we are not allowed to pick a conversion function). |
2813 | virtual SemaDiagnosticBuilder diagnoseConversion( |
2814 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; |
2815 | |
2816 | virtual ~ContextualImplicitConverter() {} |
2817 | }; |
2818 | |
2819 | class ICEConvertDiagnoser : public ContextualImplicitConverter { |
2820 | bool AllowScopedEnumerations; |
2821 | |
2822 | public: |
2823 | ICEConvertDiagnoser(bool AllowScopedEnumerations, |
2824 | bool Suppress, bool SuppressConversion) |
2825 | : ContextualImplicitConverter(Suppress, SuppressConversion), |
2826 | AllowScopedEnumerations(AllowScopedEnumerations) {} |
2827 | |
2828 | /// Match an integral or (possibly scoped) enumeration type. |
2829 | bool match(QualType T) override; |
2830 | |
2831 | SemaDiagnosticBuilder |
2832 | diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { |
2833 | return diagnoseNotInt(S, Loc, T); |
2834 | } |
2835 | |
2836 | /// Emits a diagnostic complaining that the expression does not have |
2837 | /// integral or enumeration type. |
2838 | virtual SemaDiagnosticBuilder |
2839 | diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; |
2840 | }; |
2841 | |
2842 | /// Perform a contextual implicit conversion. |
2843 | ExprResult PerformContextualImplicitConversion( |
2844 | SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); |
2845 | |
2846 | |
2847 | enum ObjCSubscriptKind { |
2848 | OS_Array, |
2849 | OS_Dictionary, |
2850 | OS_Error |
2851 | }; |
2852 | ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); |
2853 | |
2854 | // Note that LK_String is intentionally after the other literals, as |
2855 | // this is used for diagnostics logic. |
2856 | enum ObjCLiteralKind { |
2857 | LK_Array, |
2858 | LK_Dictionary, |
2859 | LK_Numeric, |
2860 | LK_Boxed, |
2861 | LK_String, |
2862 | LK_Block, |
2863 | LK_None |
2864 | }; |
2865 | ObjCLiteralKind CheckLiteralKind(Expr *FromE); |
2866 | |
2867 | ExprResult PerformObjectMemberConversion(Expr *From, |
2868 | NestedNameSpecifier *Qualifier, |
2869 | NamedDecl *FoundDecl, |
2870 | NamedDecl *Member); |
2871 | |
2872 | // Members have to be NamespaceDecl* or TranslationUnitDecl*. |
2873 | // TODO: make this is a typesafe union. |
2874 | typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; |
2875 | typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; |
2876 | |
2877 | using ADLCallKind = CallExpr::ADLCallKind; |
2878 | |
2879 | void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, |
2880 | ArrayRef<Expr *> Args, |
2881 | OverloadCandidateSet &CandidateSet, |
2882 | bool SuppressUserConversions = false, |
2883 | bool PartialOverloading = false, |
2884 | bool AllowExplicit = true, |
2885 | bool AllowExplicitConversion = false, |
2886 | ADLCallKind IsADLCandidate = ADLCallKind::NotADL, |
2887 | ConversionSequenceList EarlyConversions = None); |
2888 | void AddFunctionCandidates(const UnresolvedSetImpl &Functions, |
2889 | ArrayRef<Expr *> Args, |
2890 | OverloadCandidateSet &CandidateSet, |
2891 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, |
2892 | bool SuppressUserConversions = false, |
2893 | bool PartialOverloading = false, |
2894 | bool FirstArgumentIsBase = false); |
2895 | void AddMethodCandidate(DeclAccessPair FoundDecl, |
2896 | QualType ObjectType, |
2897 | Expr::Classification ObjectClassification, |
2898 | ArrayRef<Expr *> Args, |
2899 | OverloadCandidateSet& CandidateSet, |
2900 | bool SuppressUserConversion = false); |
2901 | void AddMethodCandidate(CXXMethodDecl *Method, |
2902 | DeclAccessPair FoundDecl, |
2903 | CXXRecordDecl *ActingContext, QualType ObjectType, |
2904 | Expr::Classification ObjectClassification, |
2905 | ArrayRef<Expr *> Args, |
2906 | OverloadCandidateSet& CandidateSet, |
2907 | bool SuppressUserConversions = false, |
2908 | bool PartialOverloading = false, |
2909 | ConversionSequenceList EarlyConversions = None); |
2910 | void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, |
2911 | DeclAccessPair FoundDecl, |
2912 | CXXRecordDecl *ActingContext, |
2913 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
2914 | QualType ObjectType, |
2915 | Expr::Classification ObjectClassification, |
2916 | ArrayRef<Expr *> Args, |
2917 | OverloadCandidateSet& CandidateSet, |
2918 | bool SuppressUserConversions = false, |
2919 | bool PartialOverloading = false); |
2920 | void AddTemplateOverloadCandidate( |
2921 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
2922 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
2923 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, |
2924 | bool PartialOverloading = false, bool AllowExplicit = true, |
2925 | ADLCallKind IsADLCandidate = ADLCallKind::NotADL); |
2926 | bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, |
2927 | ArrayRef<QualType> ParamTypes, |
2928 | ArrayRef<Expr *> Args, |
2929 | OverloadCandidateSet &CandidateSet, |
2930 | ConversionSequenceList &Conversions, |
2931 | bool SuppressUserConversions, |
2932 | CXXRecordDecl *ActingContext = nullptr, |
2933 | QualType ObjectType = QualType(), |
2934 | Expr::Classification |
2935 | ObjectClassification = {}); |
2936 | void AddConversionCandidate( |
2937 | CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, |
2938 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, |
2939 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
2940 | bool AllowExplicit, bool AllowResultConversion = true); |
2941 | void AddTemplateConversionCandidate( |
2942 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, |
2943 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, |
2944 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, |
2945 | bool AllowExplicit, bool AllowResultConversion = true); |
2946 | void AddSurrogateCandidate(CXXConversionDecl *Conversion, |
2947 | DeclAccessPair FoundDecl, |
2948 | CXXRecordDecl *ActingContext, |
2949 | const FunctionProtoType *Proto, |
2950 | Expr *Object, ArrayRef<Expr *> Args, |
2951 | OverloadCandidateSet& CandidateSet); |
2952 | void AddMemberOperatorCandidates(OverloadedOperatorKind Op, |
2953 | SourceLocation OpLoc, ArrayRef<Expr *> Args, |
2954 | OverloadCandidateSet& CandidateSet, |
2955 | SourceRange OpRange = SourceRange()); |
2956 | void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, |
2957 | OverloadCandidateSet& CandidateSet, |
2958 | bool IsAssignmentOperator = false, |
2959 | unsigned NumContextualBoolArguments = 0); |
2960 | void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, |
2961 | SourceLocation OpLoc, ArrayRef<Expr *> Args, |
2962 | OverloadCandidateSet& CandidateSet); |
2963 | void AddArgumentDependentLookupCandidates(DeclarationName Name, |
2964 | SourceLocation Loc, |
2965 | ArrayRef<Expr *> Args, |
2966 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
2967 | OverloadCandidateSet& CandidateSet, |
2968 | bool PartialOverloading = false); |
2969 | |
2970 | // Emit as a 'note' the specific overload candidate |
2971 | void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, |
2972 | QualType DestType = QualType(), |
2973 | bool TakingAddress = false); |
2974 | |
2975 | // Emit as a series of 'note's all template and non-templates identified by |
2976 | // the expression Expr |
2977 | void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), |
2978 | bool TakingAddress = false); |
2979 | |
2980 | /// Check the enable_if expressions on the given function. Returns the first |
2981 | /// failing attribute, or NULL if they were all successful. |
2982 | EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, |
2983 | bool MissingImplicitThis = false); |
2984 | |
2985 | /// Find the failed Boolean condition within a given Boolean |
2986 | /// constant expression, and describe it with a string. |
2987 | std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); |
2988 | |
2989 | /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any |
2990 | /// non-ArgDependent DiagnoseIfAttrs. |
2991 | /// |
2992 | /// Argument-dependent diagnose_if attributes should be checked each time a |
2993 | /// function is used as a direct callee of a function call. |
2994 | /// |
2995 | /// Returns true if any errors were emitted. |
2996 | bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, |
2997 | const Expr *ThisArg, |
2998 | ArrayRef<const Expr *> Args, |
2999 | SourceLocation Loc); |
3000 | |
3001 | /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any |
3002 | /// ArgDependent DiagnoseIfAttrs. |
3003 | /// |
3004 | /// Argument-independent diagnose_if attributes should be checked on every use |
3005 | /// of a function. |
3006 | /// |
3007 | /// Returns true if any errors were emitted. |
3008 | bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, |
3009 | SourceLocation Loc); |
3010 | |
3011 | /// Returns whether the given function's address can be taken or not, |
3012 | /// optionally emitting a diagnostic if the address can't be taken. |
3013 | /// |
3014 | /// Returns false if taking the address of the function is illegal. |
3015 | bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, |
3016 | bool Complain = false, |
3017 | SourceLocation Loc = SourceLocation()); |
3018 | |
3019 | // [PossiblyAFunctionType] --> [Return] |
3020 | // NonFunctionType --> NonFunctionType |
3021 | // R (A) --> R(A) |
3022 | // R (*)(A) --> R (A) |
3023 | // R (&)(A) --> R (A) |
3024 | // R (S::*)(A) --> R (A) |
3025 | QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); |
3026 | |
3027 | FunctionDecl * |
3028 | ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, |
3029 | QualType TargetType, |
3030 | bool Complain, |
3031 | DeclAccessPair &Found, |
3032 | bool *pHadMultipleCandidates = nullptr); |
3033 | |
3034 | FunctionDecl * |
3035 | resolveAddressOfOnlyViableOverloadCandidate(Expr *E, |
3036 | DeclAccessPair &FoundResult); |
3037 | |
3038 | bool resolveAndFixAddressOfOnlyViableOverloadCandidate( |
3039 | ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); |
3040 | |
3041 | FunctionDecl * |
3042 | ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, |
3043 | bool Complain = false, |
3044 | DeclAccessPair *Found = nullptr); |
3045 | |
3046 | bool ResolveAndFixSingleFunctionTemplateSpecialization( |
3047 | ExprResult &SrcExpr, |
3048 | bool DoFunctionPointerConverion = false, |
3049 | bool Complain = false, |
3050 | SourceRange OpRangeForComplaining = SourceRange(), |
3051 | QualType DestTypeForComplaining = QualType(), |
3052 | unsigned DiagIDForComplaining = 0); |
3053 | |
3054 | |
3055 | Expr *FixOverloadedFunctionReference(Expr *E, |
3056 | DeclAccessPair FoundDecl, |
3057 | FunctionDecl *Fn); |
3058 | ExprResult FixOverloadedFunctionReference(ExprResult, |
3059 | DeclAccessPair FoundDecl, |
3060 | FunctionDecl *Fn); |
3061 | |
3062 | void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, |
3063 | ArrayRef<Expr *> Args, |
3064 | OverloadCandidateSet &CandidateSet, |
3065 | bool PartialOverloading = false); |
3066 | |
3067 | // An enum used to represent the different possible results of building a |
3068 | // range-based for loop. |
3069 | enum ForRangeStatus { |
3070 | FRS_Success, |
3071 | FRS_NoViableFunction, |
3072 | FRS_DiagnosticIssued |
3073 | }; |
3074 | |
3075 | ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, |
3076 | SourceLocation RangeLoc, |
3077 | const DeclarationNameInfo &NameInfo, |
3078 | LookupResult &MemberLookup, |
3079 | OverloadCandidateSet *CandidateSet, |
3080 | Expr *Range, ExprResult *CallExpr); |
3081 | |
3082 | ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, |
3083 | UnresolvedLookupExpr *ULE, |
3084 | SourceLocation LParenLoc, |
3085 | MultiExprArg Args, |
3086 | SourceLocation RParenLoc, |
3087 | Expr *ExecConfig, |
3088 | bool AllowTypoCorrection=true, |
3089 | bool CalleesAddressIsTaken=false); |
3090 | |
3091 | bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, |
3092 | MultiExprArg Args, SourceLocation RParenLoc, |
3093 | OverloadCandidateSet *CandidateSet, |
3094 | ExprResult *Result); |
3095 | |
3096 | ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, |
3097 | UnaryOperatorKind Opc, |
3098 | const UnresolvedSetImpl &Fns, |
3099 | Expr *input, bool RequiresADL = true); |
3100 | |
3101 | ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, |
3102 | BinaryOperatorKind Opc, |
3103 | const UnresolvedSetImpl &Fns, |
3104 | Expr *LHS, Expr *RHS, |
3105 | bool RequiresADL = true); |
3106 | |
3107 | ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, |
3108 | SourceLocation RLoc, |
3109 | Expr *Base,Expr *Idx); |
3110 | |
3111 | ExprResult |
3112 | BuildCallToMemberFunction(Scope *S, Expr *MemExpr, |
3113 | SourceLocation LParenLoc, |
3114 | MultiExprArg Args, |
3115 | SourceLocation RParenLoc); |
3116 | ExprResult |
3117 | BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, |
3118 | MultiExprArg Args, |
3119 | SourceLocation RParenLoc); |
3120 | |
3121 | ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, |
3122 | SourceLocation OpLoc, |
3123 | bool *NoArrowOperatorFound = nullptr); |
3124 | |
3125 | /// CheckCallReturnType - Checks that a call expression's return type is |
3126 | /// complete. Returns true on failure. The location passed in is the location |
3127 | /// that best represents the call. |
3128 | bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, |
3129 | CallExpr *CE, FunctionDecl *FD); |
3130 | |
3131 | /// Helpers for dealing with blocks and functions. |
3132 | bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, |
3133 | bool CheckParameterNames); |
3134 | void CheckCXXDefaultArguments(FunctionDecl *FD); |
3135 | void CheckExtraCXXDefaultArguments(Declarator &D); |
3136 | Scope *getNonFieldDeclScope(Scope *S); |
3137 | |
3138 | /// \name Name lookup |
3139 | /// |
3140 | /// These routines provide name lookup that is used during semantic |
3141 | /// analysis to resolve the various kinds of names (identifiers, |
3142 | /// overloaded operator names, constructor names, etc.) into zero or |
3143 | /// more declarations within a particular scope. The major entry |
3144 | /// points are LookupName, which performs unqualified name lookup, |
3145 | /// and LookupQualifiedName, which performs qualified name lookup. |
3146 | /// |
3147 | /// All name lookup is performed based on some specific criteria, |
3148 | /// which specify what names will be visible to name lookup and how |
3149 | /// far name lookup should work. These criteria are important both |
3150 | /// for capturing language semantics (certain lookups will ignore |
3151 | /// certain names, for example) and for performance, since name |
3152 | /// lookup is often a bottleneck in the compilation of C++. Name |
3153 | /// lookup criteria is specified via the LookupCriteria enumeration. |
3154 | /// |
3155 | /// The results of name lookup can vary based on the kind of name |
3156 | /// lookup performed, the current language, and the translation |
3157 | /// unit. In C, for example, name lookup will either return nothing |
3158 | /// (no entity found) or a single declaration. In C++, name lookup |
3159 | /// can additionally refer to a set of overloaded functions or |
3160 | /// result in an ambiguity. All of the possible results of name |
3161 | /// lookup are captured by the LookupResult class, which provides |
3162 | /// the ability to distinguish among them. |
3163 | //@{ |
3164 | |
3165 | /// Describes the kind of name lookup to perform. |
3166 | enum LookupNameKind { |
3167 | /// Ordinary name lookup, which finds ordinary names (functions, |
3168 | /// variables, typedefs, etc.) in C and most kinds of names |
3169 | /// (functions, variables, members, types, etc.) in C++. |
3170 | LookupOrdinaryName = 0, |
3171 | /// Tag name lookup, which finds the names of enums, classes, |
3172 | /// structs, and unions. |
3173 | LookupTagName, |
3174 | /// Label name lookup. |
3175 | LookupLabel, |
3176 | /// Member name lookup, which finds the names of |
3177 | /// class/struct/union members. |
3178 | LookupMemberName, |
3179 | /// Look up of an operator name (e.g., operator+) for use with |
3180 | /// operator overloading. This lookup is similar to ordinary name |
3181 | /// lookup, but will ignore any declarations that are class members. |
3182 | LookupOperatorName, |
3183 | /// Look up of a name that precedes the '::' scope resolution |
3184 | /// operator in C++. This lookup completely ignores operator, object, |
3185 | /// function, and enumerator names (C++ [basic.lookup.qual]p1). |
3186 | LookupNestedNameSpecifierName, |
3187 | /// Look up a namespace name within a C++ using directive or |
3188 | /// namespace alias definition, ignoring non-namespace names (C++ |
3189 | /// [basic.lookup.udir]p1). |
3190 | LookupNamespaceName, |
3191 | /// Look up all declarations in a scope with the given name, |
3192 | /// including resolved using declarations. This is appropriate |
3193 | /// for checking redeclarations for a using declaration. |
3194 | LookupUsingDeclName, |
3195 | /// Look up an ordinary name that is going to be redeclared as a |
3196 | /// name with linkage. This lookup ignores any declarations that |
3197 | /// are outside of the current scope unless they have linkage. See |
3198 | /// C99 6.2.2p4-5 and C++ [basic.link]p6. |
3199 | LookupRedeclarationWithLinkage, |
3200 | /// Look up a friend of a local class. This lookup does not look |
3201 | /// outside the innermost non-class scope. See C++11 [class.friend]p11. |
3202 | LookupLocalFriendName, |
3203 | /// Look up the name of an Objective-C protocol. |
3204 | LookupObjCProtocolName, |
3205 | /// Look up implicit 'self' parameter of an objective-c method. |
3206 | LookupObjCImplicitSelfParam, |
3207 | /// Look up the name of an OpenMP user-defined reduction operation. |
3208 | LookupOMPReductionName, |
3209 | /// Look up the name of an OpenMP user-defined mapper. |
3210 | LookupOMPMapperName, |
3211 | /// Look up any declaration with any name. |
3212 | LookupAnyName |
3213 | }; |
3214 | |
3215 | /// Specifies whether (or how) name lookup is being performed for a |
3216 | /// redeclaration (vs. a reference). |
3217 | enum RedeclarationKind { |
3218 | /// The lookup is a reference to this name that is not for the |
3219 | /// purpose of redeclaring the name. |
3220 | NotForRedeclaration = 0, |
3221 | /// The lookup results will be used for redeclaration of a name, |
3222 | /// if an entity by that name already exists and is visible. |
3223 | ForVisibleRedeclaration, |
3224 | /// The lookup results will be used for redeclaration of a name |
3225 | /// with external linkage; non-visible lookup results with external linkage |
3226 | /// may also be found. |
3227 | ForExternalRedeclaration |
3228 | }; |
3229 | |
3230 | RedeclarationKind forRedeclarationInCurContext() { |
3231 | // A declaration with an owning module for linkage can never link against |
3232 | // anything that is not visible. We don't need to check linkage here; if |
3233 | // the context has internal linkage, redeclaration lookup won't find things |
3234 | // from other TUs, and we can't safely compute linkage yet in general. |
3235 | if (cast<Decl>(CurContext) |
3236 | ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) |
3237 | return ForVisibleRedeclaration; |
3238 | return ForExternalRedeclaration; |
3239 | } |
3240 | |
3241 | /// The possible outcomes of name lookup for a literal operator. |
3242 | enum LiteralOperatorLookupResult { |
3243 | /// The lookup resulted in an error. |
3244 | LOLR_Error, |
3245 | /// The lookup found no match but no diagnostic was issued. |
3246 | LOLR_ErrorNoDiagnostic, |
3247 | /// The lookup found a single 'cooked' literal operator, which |
3248 | /// expects a normal literal to be built and passed to it. |
3249 | LOLR_Cooked, |
3250 | /// The lookup found a single 'raw' literal operator, which expects |
3251 | /// a string literal containing the spelling of the literal token. |
3252 | LOLR_Raw, |
3253 | /// The lookup found an overload set of literal operator templates, |
3254 | /// which expect the characters of the spelling of the literal token to be |
3255 | /// passed as a non-type template argument pack. |
3256 | LOLR_Template, |
3257 | /// The lookup found an overload set of literal operator templates, |
3258 | /// which expect the character type and characters of the spelling of the |
3259 | /// string literal token to be passed as template arguments. |
3260 | LOLR_StringTemplate |
3261 | }; |
3262 | |
3263 | SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, |
3264 | CXXSpecialMember SM, |
3265 | bool ConstArg, |
3266 | bool VolatileArg, |
3267 | bool RValueThis, |
3268 | bool ConstThis, |
3269 | bool VolatileThis); |
3270 | |
3271 | typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; |
3272 | typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> |
3273 | TypoRecoveryCallback; |
3274 | |
3275 | private: |
3276 | bool CppLookupName(LookupResult &R, Scope *S); |
3277 | |
3278 | struct TypoExprState { |
3279 | std::unique_ptr<TypoCorrectionConsumer> Consumer; |
3280 | TypoDiagnosticGenerator DiagHandler; |
3281 | TypoRecoveryCallback RecoveryHandler; |
3282 | TypoExprState(); |
3283 | TypoExprState(TypoExprState &&other) noexcept; |
3284 | TypoExprState &operator=(TypoExprState &&other) noexcept; |
3285 | }; |
3286 | |
3287 | /// The set of unhandled TypoExprs and their associated state. |
3288 | llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; |
3289 | |
3290 | /// Creates a new TypoExpr AST node. |
3291 | TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, |
3292 | TypoDiagnosticGenerator TDG, |
3293 | TypoRecoveryCallback TRC); |
3294 | |
3295 | // The set of known/encountered (unique, canonicalized) NamespaceDecls. |
3296 | // |
3297 | // The boolean value will be true to indicate that the namespace was loaded |
3298 | // from an AST/PCH file, or false otherwise. |
3299 | llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; |
3300 | |
3301 | /// Whether we have already loaded known namespaces from an extenal |
3302 | /// source. |
3303 | bool LoadedExternalKnownNamespaces; |
3304 | |
3305 | /// Helper for CorrectTypo and CorrectTypoDelayed used to create and |
3306 | /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction |
3307 | /// should be skipped entirely. |
3308 | std::unique_ptr<TypoCorrectionConsumer> |
3309 | makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, |
3310 | Sema::LookupNameKind LookupKind, Scope *S, |
3311 | CXXScopeSpec *SS, |
3312 | CorrectionCandidateCallback &CCC, |
3313 | DeclContext *MemberContext, bool EnteringContext, |
3314 | const ObjCObjectPointerType *OPT, |
3315 | bool ErrorRecovery); |
3316 | |
3317 | public: |
3318 | const TypoExprState &getTypoExprState(TypoExpr *TE) const; |
3319 | |
3320 | /// Clears the state of the given TypoExpr. |
3321 | void clearDelayedTypo(TypoExpr *TE); |
3322 | |
3323 | /// Look up a name, looking for a single declaration. Return |
3324 | /// null if the results were absent, ambiguous, or overloaded. |
3325 | /// |
3326 | /// It is preferable to use the elaborated form and explicitly handle |
3327 | /// ambiguity and overloaded. |
3328 | NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, |
3329 | SourceLocation Loc, |
3330 | LookupNameKind NameKind, |
3331 | RedeclarationKind Redecl |
3332 | = NotForRedeclaration); |
3333 | bool LookupName(LookupResult &R, Scope *S, |
3334 | bool AllowBuiltinCreation = false); |
3335 | bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, |
3336 | bool InUnqualifiedLookup = false); |
3337 | bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, |
3338 | CXXScopeSpec &SS); |
3339 | bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, |
3340 | bool AllowBuiltinCreation = false, |
3341 | bool EnteringContext = false); |
3342 | ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, |
3343 | RedeclarationKind Redecl |
3344 | = NotForRedeclaration); |
3345 | bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); |
3346 | |
3347 | void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, |
3348 | QualType T1, QualType T2, |
3349 | UnresolvedSetImpl &Functions); |
3350 | |
3351 | LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, |
3352 | SourceLocation GnuLabelLoc = SourceLocation()); |
3353 | |
3354 | DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); |
3355 | CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); |
3356 | CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, |
3357 | unsigned Quals); |
3358 | CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, |
3359 | bool RValueThis, unsigned ThisQuals); |
3360 | CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, |
3361 | unsigned Quals); |
3362 | CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, |
3363 | bool RValueThis, unsigned ThisQuals); |
3364 | CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); |
3365 | |
3366 | bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); |
3367 | LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, |
3368 | ArrayRef<QualType> ArgTys, |
3369 | bool AllowRaw, |
3370 | bool AllowTemplate, |
3371 | bool AllowStringTemplate, |
3372 | bool DiagnoseMissing); |
3373 | bool isKnownName(StringRef name); |
3374 | |
3375 | void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, |
3376 | ArrayRef<Expr *> Args, ADLResult &Functions); |
3377 | |
3378 | void LookupVisibleDecls(Scope *S, LookupNameKind Kind, |
3379 | VisibleDeclConsumer &Consumer, |
3380 | bool IncludeGlobalScope = true, |
3381 | bool LoadExternal = true); |
3382 | void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, |
3383 | VisibleDeclConsumer &Consumer, |
3384 | bool IncludeGlobalScope = true, |
3385 | bool IncludeDependentBases = false, |
3386 | bool LoadExternal = true); |
3387 | |
3388 | enum CorrectTypoKind { |
3389 | CTK_NonError, // CorrectTypo used in a non error recovery situation. |
3390 | CTK_ErrorRecovery // CorrectTypo used in normal error recovery. |
3391 | }; |
3392 | |
3393 | TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, |
3394 | Sema::LookupNameKind LookupKind, |
3395 | Scope *S, CXXScopeSpec *SS, |
3396 | CorrectionCandidateCallback &CCC, |
3397 | CorrectTypoKind Mode, |
3398 | DeclContext *MemberContext = nullptr, |
3399 | bool EnteringContext = false, |
3400 | const ObjCObjectPointerType *OPT = nullptr, |
3401 | bool RecordFailure = true); |
3402 | |
3403 | TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, |
3404 | Sema::LookupNameKind LookupKind, Scope *S, |
3405 | CXXScopeSpec *SS, |
3406 | CorrectionCandidateCallback &CCC, |
3407 | TypoDiagnosticGenerator TDG, |
3408 | TypoRecoveryCallback TRC, CorrectTypoKind Mode, |
3409 | DeclContext *MemberContext = nullptr, |
3410 | bool EnteringContext = false, |
3411 | const ObjCObjectPointerType *OPT = nullptr); |
3412 | |
3413 | /// Process any TypoExprs in the given Expr and its children, |
3414 | /// generating diagnostics as appropriate and returning a new Expr if there |
3415 | /// were typos that were all successfully corrected and ExprError if one or |
3416 | /// more typos could not be corrected. |
3417 | /// |
3418 | /// \param E The Expr to check for TypoExprs. |
3419 | /// |
3420 | /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its |
3421 | /// initializer. |
3422 | /// |
3423 | /// \param Filter A function applied to a newly rebuilt Expr to determine if |
3424 | /// it is an acceptable/usable result from a single combination of typo |
3425 | /// corrections. As long as the filter returns ExprError, different |
3426 | /// combinations of corrections will be tried until all are exhausted. |
3427 | ExprResult |
3428 | CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr, |
3429 | llvm::function_ref<ExprResult(Expr *)> Filter = |
3430 | [](Expr *E) -> ExprResult { return E; }); |
3431 | |
3432 | ExprResult |
3433 | CorrectDelayedTyposInExpr(Expr *E, |
3434 | llvm::function_ref<ExprResult(Expr *)> Filter) { |
3435 | return CorrectDelayedTyposInExpr(E, nullptr, Filter); |
3436 | } |
3437 | |
3438 | ExprResult |
3439 | CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr, |
3440 | llvm::function_ref<ExprResult(Expr *)> Filter = |
3441 | [](Expr *E) -> ExprResult { return E; }) { |
3442 | return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); |
3443 | } |
3444 | |
3445 | ExprResult |
3446 | CorrectDelayedTyposInExpr(ExprResult ER, |
3447 | llvm::function_ref<ExprResult(Expr *)> Filter) { |
3448 | return CorrectDelayedTyposInExpr(ER, nullptr, Filter); |
3449 | } |
3450 | |
3451 | void diagnoseTypo(const TypoCorrection &Correction, |
3452 | const PartialDiagnostic &TypoDiag, |
3453 | bool ErrorRecovery = true); |
3454 | |
3455 | void diagnoseTypo(const TypoCorrection &Correction, |
3456 | const PartialDiagnostic &TypoDiag, |
3457 | const PartialDiagnostic &PrevNote, |
3458 | bool ErrorRecovery = true); |
3459 | |
3460 | void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); |
3461 | |
3462 | void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, |
3463 | ArrayRef<Expr *> Args, |
3464 | AssociatedNamespaceSet &AssociatedNamespaces, |
3465 | AssociatedClassSet &AssociatedClasses); |
3466 | |
3467 | void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, |
3468 | bool ConsiderLinkage, bool AllowInlineNamespace); |
3469 | |
3470 | bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); |
3471 | |
3472 | void DiagnoseAmbiguousLookup(LookupResult &Result); |
3473 | //@} |
3474 | |
3475 | ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, |
3476 | SourceLocation IdLoc, |
3477 | bool TypoCorrection = false); |
3478 | NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, |
3479 | Scope *S, bool ForRedeclaration, |
3480 | SourceLocation Loc); |
3481 | NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, |
3482 | Scope *S); |
3483 | void AddKnownFunctionAttributes(FunctionDecl *FD); |
3484 | |
3485 | // More parsing and symbol table subroutines. |
3486 | |
3487 | void ProcessPragmaWeak(Scope *S, Decl *D); |
3488 | // Decl attributes - this routine is the top level dispatcher. |
3489 | void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); |
3490 | // Helper for delayed processing of attributes. |
3491 | void ProcessDeclAttributeDelayed(Decl *D, |
3492 | const ParsedAttributesView &AttrList); |
3493 | void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, |
3494 | bool IncludeCXX11Attributes = true); |
3495 | bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, |
3496 | const ParsedAttributesView &AttrList); |
3497 | |
3498 | void checkUnusedDeclAttributes(Declarator &D); |
3499 | |
3500 | /// Determine if type T is a valid subject for a nonnull and similar |
3501 | /// attributes. By default, we look through references (the behavior used by |
3502 | /// nonnull), but if the second parameter is true, then we treat a reference |
3503 | /// type as valid. |
3504 | bool isValidPointerAttrType(QualType T, bool RefOkay = false); |
3505 | |
3506 | bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); |
3507 | bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, |
3508 | const FunctionDecl *FD = nullptr); |
3509 | bool CheckAttrTarget(const ParsedAttr &CurrAttr); |
3510 | bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); |
3511 | bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, |
3512 | StringRef &Str, |
3513 | SourceLocation *ArgLocation = nullptr); |
3514 | bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); |
3515 | bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); |
3516 | bool checkMSInheritanceAttrOnDefinition( |
3517 | CXXRecordDecl *RD, SourceRange Range, bool BestCase, |
3518 | MSInheritanceAttr::Spelling SemanticSpelling); |
3519 | |
3520 | void CheckAlignasUnderalignment(Decl *D); |
3521 | |
3522 | /// Adjust the calling convention of a method to be the ABI default if it |
3523 | /// wasn't specified explicitly. This handles method types formed from |
3524 | /// function type typedefs and typename template arguments. |
3525 | void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, |
3526 | SourceLocation Loc); |
3527 | |
3528 | // Check if there is an explicit attribute, but only look through parens. |
3529 | // The intent is to look for an attribute on the current declarator, but not |
3530 | // one that came from a typedef. |
3531 | bool hasExplicitCallingConv(QualType T); |
3532 | |
3533 | /// Get the outermost AttributedType node that sets a calling convention. |
3534 | /// Valid types should not have multiple attributes with different CCs. |
3535 | const AttributedType *getCallingConvAttributedType(QualType T) const; |
3536 | |
3537 | /// Stmt attributes - this routine is the top level dispatcher. |
3538 | StmtResult ProcessStmtAttributes(Stmt *Stmt, |
3539 | const ParsedAttributesView &Attrs, |
3540 | SourceRange Range); |
3541 | |
3542 | void WarnConflictingTypedMethods(ObjCMethodDecl *Method, |
3543 | ObjCMethodDecl *MethodDecl, |
3544 | bool IsProtocolMethodDecl); |
3545 | |
3546 | void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, |
3547 | ObjCMethodDecl *Overridden, |
3548 | bool IsProtocolMethodDecl); |
3549 | |
3550 | /// WarnExactTypedMethods - This routine issues a warning if method |
3551 | /// implementation declaration matches exactly that of its declaration. |
3552 | void WarnExactTypedMethods(ObjCMethodDecl *Method, |
3553 | ObjCMethodDecl *MethodDecl, |
3554 | bool IsProtocolMethodDecl); |
3555 | |
3556 | typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; |
3557 | |
3558 | /// CheckImplementationIvars - This routine checks if the instance variables |
3559 | /// listed in the implelementation match those listed in the interface. |
3560 | void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, |
3561 | ObjCIvarDecl **Fields, unsigned nIvars, |
3562 | SourceLocation Loc); |
3563 | |
3564 | /// ImplMethodsVsClassMethods - This is main routine to warn if any method |
3565 | /// remains unimplemented in the class or category \@implementation. |
3566 | void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, |
3567 | ObjCContainerDecl* IDecl, |
3568 | bool IncompleteImpl = false); |
3569 | |
3570 | /// DiagnoseUnimplementedProperties - This routine warns on those properties |
3571 | /// which must be implemented by this implementation. |
3572 | void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, |
3573 | ObjCContainerDecl *CDecl, |
3574 | bool SynthesizeProperties); |
3575 | |
3576 | /// Diagnose any null-resettable synthesized setters. |
3577 | void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); |
3578 | |
3579 | /// DefaultSynthesizeProperties - This routine default synthesizes all |
3580 | /// properties which must be synthesized in the class's \@implementation. |
3581 | void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, |
3582 | ObjCInterfaceDecl *IDecl, |
3583 | SourceLocation AtEnd); |
3584 | void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); |
3585 | |
3586 | /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is |
3587 | /// an ivar synthesized for 'Method' and 'Method' is a property accessor |
3588 | /// declared in class 'IFace'. |
3589 | bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, |
3590 | ObjCMethodDecl *Method, ObjCIvarDecl *IV); |
3591 | |
3592 | /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which |
3593 | /// backs the property is not used in the property's accessor. |
3594 | void DiagnoseUnusedBackingIvarInAccessor(Scope *S, |
3595 | const ObjCImplementationDecl *ImplD); |
3596 | |
3597 | /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and |
3598 | /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. |
3599 | /// It also returns ivar's property on success. |
3600 | ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, |
3601 | const ObjCPropertyDecl *&PDecl) const; |
3602 | |
3603 | /// Called by ActOnProperty to handle \@property declarations in |
3604 | /// class extensions. |
3605 | ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, |
3606 | SourceLocation AtLoc, |
3607 | SourceLocation LParenLoc, |
3608 | FieldDeclarator &FD, |
3609 | Selector GetterSel, |
3610 | SourceLocation GetterNameLoc, |
3611 | Selector SetterSel, |
3612 | SourceLocation SetterNameLoc, |
3613 | const bool isReadWrite, |
3614 | unsigned &Attributes, |
3615 | const unsigned AttributesAsWritten, |
3616 | QualType T, |
3617 | TypeSourceInfo *TSI, |
3618 | tok::ObjCKeywordKind MethodImplKind); |
3619 | |
3620 | /// Called by ActOnProperty and HandlePropertyInClassExtension to |
3621 | /// handle creating the ObjcPropertyDecl for a category or \@interface. |
3622 | ObjCPropertyDecl *CreatePropertyDecl(Scope *S, |
3623 | ObjCContainerDecl *CDecl, |
3624 | SourceLocation AtLoc, |
3625 | SourceLocation LParenLoc, |
3626 | FieldDeclarator &FD, |
3627 | Selector GetterSel, |
3628 | SourceLocation GetterNameLoc, |
3629 | Selector SetterSel, |
3630 | SourceLocation SetterNameLoc, |
3631 | const bool isReadWrite, |
3632 | const unsigned Attributes, |
3633 | const unsigned AttributesAsWritten, |
3634 | QualType T, |
3635 | TypeSourceInfo *TSI, |
3636 | tok::ObjCKeywordKind MethodImplKind, |
3637 | DeclContext *lexicalDC = nullptr); |
3638 | |
3639 | /// AtomicPropertySetterGetterRules - This routine enforces the rule (via |
3640 | /// warning) when atomic property has one but not the other user-declared |
3641 | /// setter or getter. |
3642 | void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, |
3643 | ObjCInterfaceDecl* IDecl); |
3644 | |
3645 | void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); |
3646 | |
3647 | void DiagnoseMissingDesignatedInitOverrides( |
3648 | const ObjCImplementationDecl *ImplD, |
3649 | const ObjCInterfaceDecl *IFD); |
3650 | |
3651 | void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); |
3652 | |
3653 | enum MethodMatchStrategy { |
3654 | MMS_loose, |
3655 | MMS_strict |
3656 | }; |
3657 | |
3658 | /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns |
3659 | /// true, or false, accordingly. |
3660 | bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, |
3661 | const ObjCMethodDecl *PrevMethod, |
3662 | MethodMatchStrategy strategy = MMS_strict); |
3663 | |
3664 | /// MatchAllMethodDeclarations - Check methods declaraed in interface or |
3665 | /// or protocol against those declared in their implementations. |
3666 | void MatchAllMethodDeclarations(const SelectorSet &InsMap, |
3667 | const SelectorSet &ClsMap, |
3668 | SelectorSet &InsMapSeen, |
3669 | SelectorSet &ClsMapSeen, |
3670 | ObjCImplDecl* IMPDecl, |
3671 | ObjCContainerDecl* IDecl, |
3672 | bool &IncompleteImpl, |
3673 | bool ImmediateClass, |
3674 | bool WarnCategoryMethodImpl=false); |
3675 | |
3676 | /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in |
3677 | /// category matches with those implemented in its primary class and |
3678 | /// warns each time an exact match is found. |
3679 | void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); |
3680 | |
3681 | /// Add the given method to the list of globally-known methods. |
3682 | void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); |
3683 | |
3684 | private: |
3685 | /// AddMethodToGlobalPool - Add an instance or factory method to the global |
3686 | /// pool. See descriptoin of AddInstanceMethodToGlobalPool. |
3687 | void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); |
3688 | |
3689 | /// LookupMethodInGlobalPool - Returns the instance or factory method and |
3690 | /// optionally warns if there are multiple signatures. |
3691 | ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, |
3692 | bool receiverIdOrClass, |
3693 | bool instance); |
3694 | |
3695 | public: |
3696 | /// - Returns instance or factory methods in global method pool for |
3697 | /// given selector. It checks the desired kind first, if none is found, and |
3698 | /// parameter checkTheOther is set, it then checks the other kind. If no such |
3699 | /// method or only one method is found, function returns false; otherwise, it |
3700 | /// returns true. |
3701 | bool |
3702 | CollectMultipleMethodsInGlobalPool(Selector Sel, |
3703 | SmallVectorImpl<ObjCMethodDecl*>& Methods, |
3704 | bool InstanceFirst, bool CheckTheOther, |
3705 | const ObjCObjectType *TypeBound = nullptr); |
3706 | |
3707 | bool |
3708 | AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, |
3709 | SourceRange R, bool receiverIdOrClass, |
3710 | SmallVectorImpl<ObjCMethodDecl*>& Methods); |
3711 | |
3712 | void |
3713 | DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, |
3714 | Selector Sel, SourceRange R, |
3715 | bool receiverIdOrClass); |
3716 | |
3717 | private: |
3718 | /// - Returns a selector which best matches given argument list or |
3719 | /// nullptr if none could be found |
3720 | ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, |
3721 | bool IsInstance, |
3722 | SmallVectorImpl<ObjCMethodDecl*>& Methods); |
3723 | |
3724 | |
3725 | /// Record the typo correction failure and return an empty correction. |
3726 | TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, |
3727 | bool RecordFailure = true) { |
3728 | if (RecordFailure) |
3729 | TypoCorrectionFailures[Typo].insert(TypoLoc); |
3730 | return TypoCorrection(); |
3731 | } |
3732 | |
3733 | public: |
3734 | /// AddInstanceMethodToGlobalPool - All instance methods in a translation |
3735 | /// unit are added to a global pool. This allows us to efficiently associate |
3736 | /// a selector with a method declaraation for purposes of typechecking |
3737 | /// messages sent to "id" (where the class of the object is unknown). |
3738 | void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { |
3739 | AddMethodToGlobalPool(Method, impl, /*instance*/true); |
3740 | } |
3741 | |
3742 | /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. |
3743 | void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { |
3744 | AddMethodToGlobalPool(Method, impl, /*instance*/false); |
3745 | } |
3746 | |
3747 | /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global |
3748 | /// pool. |
3749 | void AddAnyMethodToGlobalPool(Decl *D); |
3750 | |
3751 | /// LookupInstanceMethodInGlobalPool - Returns the method and warns if |
3752 | /// there are multiple signatures. |
3753 | ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, |
3754 | bool receiverIdOrClass=false) { |
3755 | return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, |
3756 | /*instance*/true); |
3757 | } |
3758 | |
3759 | /// LookupFactoryMethodInGlobalPool - Returns the method and warns if |
3760 | /// there are multiple signatures. |
3761 | ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, |
3762 | bool receiverIdOrClass=false) { |
3763 | return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, |
3764 | /*instance*/false); |
3765 | } |
3766 | |
3767 | const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, |
3768 | QualType ObjectType=QualType()); |
3769 | /// LookupImplementedMethodInGlobalPool - Returns the method which has an |
3770 | /// implementation. |
3771 | ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); |
3772 | |
3773 | /// CollectIvarsToConstructOrDestruct - Collect those ivars which require |
3774 | /// initialization. |
3775 | void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, |
3776 | SmallVectorImpl<ObjCIvarDecl*> &Ivars); |
3777 | |
3778 | //===--------------------------------------------------------------------===// |
3779 | // Statement Parsing Callbacks: SemaStmt.cpp. |
3780 | public: |
3781 | class FullExprArg { |
3782 | public: |
3783 | FullExprArg() : E(nullptr) { } |
3784 | FullExprArg(Sema &actions) : E(nullptr) { } |
3785 | |
3786 | ExprResult release() { |
3787 | return E; |
3788 | } |
3789 | |
3790 | Expr *get() const { return E; } |
3791 | |
3792 | Expr *operator->() { |
3793 | return E; |
3794 | } |
3795 | |
3796 | private: |
3797 | // FIXME: No need to make the entire Sema class a friend when it's just |
3798 | // Sema::MakeFullExpr that needs access to the constructor below. |
3799 | friend class Sema; |
3800 | |
3801 | explicit FullExprArg(Expr *expr) : E(expr) {} |
3802 | |
3803 | Expr *E; |
3804 | }; |
3805 | |
3806 | FullExprArg MakeFullExpr(Expr *Arg) { |
3807 | return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); |
3808 | } |
3809 | FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { |
3810 | return FullExprArg( |
3811 | ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); |
3812 | } |
3813 | FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { |
3814 | ExprResult FE = |
3815 | ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), |
3816 | /*DiscardedValue*/ true); |
3817 | return FullExprArg(FE.get()); |
3818 | } |
3819 | |
3820 | StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); |
3821 | StmtResult ActOnExprStmtError(); |
3822 | |
3823 | StmtResult ActOnNullStmt(SourceLocation SemiLoc, |
3824 | bool HasLeadingEmptyMacro = false); |
3825 | |
3826 | void ActOnStartOfCompoundStmt(bool IsStmtExpr); |
3827 | void ActOnFinishOfCompoundStmt(); |
3828 | StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, |
3829 | ArrayRef<Stmt *> Elts, bool isStmtExpr); |
3830 | |
3831 | /// A RAII object to enter scope of a compound statement. |
3832 | class CompoundScopeRAII { |
3833 | public: |
3834 | CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { |
3835 | S.ActOnStartOfCompoundStmt(IsStmtExpr); |
3836 | } |
3837 | |
3838 | ~CompoundScopeRAII() { |
3839 | S.ActOnFinishOfCompoundStmt(); |
3840 | } |
3841 | |
3842 | private: |
3843 | Sema &S; |
3844 | }; |
3845 | |
3846 | /// An RAII helper that pops function a function scope on exit. |
3847 | struct FunctionScopeRAII { |
3848 | Sema &S; |
3849 | bool Active; |
3850 | FunctionScopeRAII(Sema &S) : S(S), Active(true) {} |
3851 | ~FunctionScopeRAII() { |
3852 | if (Active) |
3853 | S.PopFunctionScopeInfo(); |
3854 | } |
3855 | void disable() { Active = false; } |
3856 | }; |
3857 | |
3858 | StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, |
3859 | SourceLocation StartLoc, |
3860 | SourceLocation EndLoc); |
3861 | void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); |
3862 | StmtResult ActOnForEachLValueExpr(Expr *E); |
3863 | ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); |
3864 | StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, |
3865 | SourceLocation DotDotDotLoc, ExprResult RHS, |
3866 | SourceLocation ColonLoc); |
3867 | void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); |
3868 | |
3869 | StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, |
3870 | SourceLocation ColonLoc, |
3871 | Stmt *SubStmt, Scope *CurScope); |
3872 | StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, |
3873 | SourceLocation ColonLoc, Stmt *SubStmt); |
3874 | |
3875 | StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, |
3876 | ArrayRef<const Attr*> Attrs, |
3877 | Stmt *SubStmt); |
3878 | |
3879 | class ConditionResult; |
3880 | StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, |
3881 | Stmt *InitStmt, |
3882 | ConditionResult Cond, Stmt *ThenVal, |
3883 | SourceLocation ElseLoc, Stmt *ElseVal); |
3884 | StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, |
3885 | Stmt *InitStmt, |
3886 | ConditionResult Cond, Stmt *ThenVal, |
3887 | SourceLocation ElseLoc, Stmt *ElseVal); |
3888 | StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, |
3889 | Stmt *InitStmt, |
3890 | ConditionResult Cond); |
3891 | StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, |
3892 | Stmt *Switch, Stmt *Body); |
3893 | StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, |
3894 | Stmt *Body); |
3895 | StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, |
3896 | SourceLocation WhileLoc, SourceLocation CondLParen, |
3897 | Expr *Cond, SourceLocation CondRParen); |
3898 | |
3899 | StmtResult ActOnForStmt(SourceLocation ForLoc, |
3900 | SourceLocation LParenLoc, |
3901 | Stmt *First, |
3902 | ConditionResult Second, |
3903 | FullExprArg Third, |
3904 | SourceLocation RParenLoc, |
3905 | Stmt *Body); |
3906 | ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, |
3907 | Expr *collection); |
3908 | StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, |
3909 | Stmt *First, Expr *collection, |
3910 | SourceLocation RParenLoc); |
3911 | StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); |
3912 | |
3913 | enum BuildForRangeKind { |
3914 | /// Initial building of a for-range statement. |
3915 | BFRK_Build, |
3916 | /// Instantiation or recovery rebuild of a for-range statement. Don't |
3917 | /// attempt any typo-correction. |
3918 | BFRK_Rebuild, |
3919 | /// Determining whether a for-range statement could be built. Avoid any |
3920 | /// unnecessary or irreversible actions. |
3921 | BFRK_Check |
3922 | }; |
3923 | |
3924 | StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, |
3925 | SourceLocation CoawaitLoc, |
3926 | Stmt *InitStmt, |
3927 | Stmt *LoopVar, |
3928 | SourceLocation ColonLoc, Expr *Collection, |
3929 | SourceLocation RParenLoc, |
3930 | BuildForRangeKind Kind); |
3931 | StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, |
3932 | SourceLocation CoawaitLoc, |
3933 | Stmt *InitStmt, |
3934 | SourceLocation ColonLoc, |
3935 | Stmt *RangeDecl, Stmt *Begin, Stmt *End, |
3936 | Expr *Cond, Expr *Inc, |
3937 | Stmt *LoopVarDecl, |
3938 | SourceLocation RParenLoc, |
3939 | BuildForRangeKind Kind); |
3940 | StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); |
3941 | |
3942 | StmtResult ActOnGotoStmt(SourceLocation GotoLoc, |
3943 | SourceLocation LabelLoc, |
3944 | LabelDecl *TheDecl); |
3945 | StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, |
3946 | SourceLocation StarLoc, |
3947 | Expr *DestExp); |
3948 | StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); |
3949 | StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); |
3950 | |
3951 | void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, |
3952 | CapturedRegionKind Kind, unsigned NumParams); |
3953 | typedef std::pair<StringRef, QualType> CapturedParamNameType; |
3954 | void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, |
3955 | CapturedRegionKind Kind, |
3956 | ArrayRef<CapturedParamNameType> Params); |
3957 | StmtResult ActOnCapturedRegionEnd(Stmt *S); |
3958 | void ActOnCapturedRegionError(); |
3959 | RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, |
3960 | SourceLocation Loc, |
3961 | unsigned NumParams); |
3962 | |
3963 | enum CopyElisionSemanticsKind { |
3964 | CES_Strict = 0, |
3965 | CES_AllowParameters = 1, |
3966 | CES_AllowDifferentTypes = 2, |
3967 | CES_AllowExceptionVariables = 4, |
3968 | CES_FormerDefault = (CES_AllowParameters), |
3969 | CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), |
3970 | CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | |
3971 | CES_AllowExceptionVariables), |
3972 | }; |
3973 | |
3974 | VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, |
3975 | CopyElisionSemanticsKind CESK); |
3976 | bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, |
3977 | CopyElisionSemanticsKind CESK); |
3978 | |
3979 | StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, |
3980 | Scope *CurScope); |
3981 | StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); |
3982 | StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); |
3983 | |
3984 | StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, |
3985 | bool IsVolatile, unsigned NumOutputs, |
3986 | unsigned NumInputs, IdentifierInfo **Names, |
3987 | MultiExprArg Constraints, MultiExprArg Exprs, |
3988 | Expr *AsmString, MultiExprArg Clobbers, |
3989 | unsigned NumLabels, |
3990 | SourceLocation RParenLoc); |
3991 | |
3992 | void FillInlineAsmIdentifierInfo(Expr *Res, |
3993 | llvm::InlineAsmIdentifierInfo &Info); |
3994 | ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, |
3995 | SourceLocation TemplateKWLoc, |
3996 | UnqualifiedId &Id, |
3997 | bool IsUnevaluatedContext); |
3998 | bool LookupInlineAsmField(StringRef Base, StringRef Member, |
3999 | unsigned &Offset, SourceLocation AsmLoc); |
4000 | ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, |
4001 | SourceLocation AsmLoc); |
4002 | StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, |
4003 | ArrayRef<Token> AsmToks, |
4004 | StringRef AsmString, |
4005 | unsigned NumOutputs, unsigned NumInputs, |
4006 | ArrayRef<StringRef> Constraints, |
4007 | ArrayRef<StringRef> Clobbers, |
4008 | ArrayRef<Expr*> Exprs, |
4009 | SourceLocation EndLoc); |
4010 | LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, |
4011 | SourceLocation Location, |
4012 | bool AlwaysCreate); |
4013 | |
4014 | VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, |
4015 | SourceLocation StartLoc, |
4016 | SourceLocation IdLoc, IdentifierInfo *Id, |
4017 | bool Invalid = false); |
4018 | |
4019 | Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); |
4020 | |
4021 | StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, |
4022 | Decl *Parm, Stmt *Body); |
4023 | |
4024 | StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); |
4025 | |
4026 | StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, |
4027 | MultiStmtArg Catch, Stmt *Finally); |
4028 | |
4029 | StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); |
4030 | StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, |
4031 | Scope *CurScope); |
4032 | ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, |
4033 | Expr *operand); |
4034 | StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, |
4035 | Expr *SynchExpr, |
4036 | Stmt *SynchBody); |
4037 | |
4038 | StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); |
4039 | |
4040 | VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, |
4041 | SourceLocation StartLoc, |
4042 | SourceLocation IdLoc, |
4043 | IdentifierInfo *Id); |
4044 | |
4045 | Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); |
4046 | |
4047 | StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, |
4048 | Decl *ExDecl, Stmt *HandlerBlock); |
4049 | StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, |
4050 | ArrayRef<Stmt *> Handlers); |
4051 | |
4052 | StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? |
4053 | SourceLocation TryLoc, Stmt *TryBlock, |
4054 | Stmt *Handler); |
4055 | StmtResult ActOnSEHExceptBlock(SourceLocation Loc, |
4056 | Expr *FilterExpr, |
4057 | Stmt *Block); |
4058 | void ActOnStartSEHFinallyBlock(); |
4059 | void ActOnAbortSEHFinallyBlock(); |
4060 | StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); |
4061 | StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); |
4062 | |
4063 | void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); |
4064 | |
4065 | bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; |
4066 | |
4067 | /// If it's a file scoped decl that must warn if not used, keep track |
4068 | /// of it. |
4069 | void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); |
4070 | |
4071 | /// DiagnoseUnusedExprResult - If the statement passed in is an expression |
4072 | /// whose result is unused, warn. |
4073 | void DiagnoseUnusedExprResult(const Stmt *S); |
4074 | void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); |
4075 | void DiagnoseUnusedDecl(const NamedDecl *ND); |
4076 | |
4077 | /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null |
4078 | /// statement as a \p Body, and it is located on the same line. |
4079 | /// |
4080 | /// This helps prevent bugs due to typos, such as: |
4081 | /// if (condition); |
4082 | /// do_stuff(); |
4083 | void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, |
4084 | const Stmt *Body, |
4085 | unsigned DiagID); |
4086 | |
4087 | /// Warn if a for/while loop statement \p S, which is followed by |
4088 | /// \p PossibleBody, has a suspicious null statement as a body. |
4089 | void DiagnoseEmptyLoopBody(const Stmt *S, |
4090 | const Stmt *PossibleBody); |
4091 | |
4092 | /// Warn if a value is moved to itself. |
4093 | void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, |
4094 | SourceLocation OpLoc); |
4095 | |
4096 | /// Warn if we're implicitly casting from a _Nullable pointer type to a |
4097 | /// _Nonnull one. |
4098 | void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, |
4099 | SourceLocation Loc); |
4100 | |
4101 | /// Warn when implicitly casting 0 to nullptr. |
4102 | void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); |
4103 | |
4104 | ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { |
4105 | return DelayedDiagnostics.push(pool); |
4106 | } |
4107 | void PopParsingDeclaration(ParsingDeclState state, Decl *decl); |
4108 | |
4109 | typedef ProcessingContextState ParsingClassState; |
4110 | ParsingClassState PushParsingClass() { |
4111 | return DelayedDiagnostics.pushUndelayed(); |
4112 | } |
4113 | void PopParsingClass(ParsingClassState state) { |
4114 | DelayedDiagnostics.popUndelayed(state); |
4115 | } |
4116 | |
4117 | void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); |
4118 | |
4119 | void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, |
4120 | const ObjCInterfaceDecl *UnknownObjCClass, |
4121 | bool ObjCPropertyAccess, |
4122 | bool AvoidPartialAvailabilityChecks = false, |
4123 | ObjCInterfaceDecl *ClassReceiver = nullptr); |
4124 | |
4125 | bool makeUnavailableInSystemHeader(SourceLocation loc, |
4126 | UnavailableAttr::ImplicitReason reason); |
4127 | |
4128 | /// Issue any -Wunguarded-availability warnings in \c FD |
4129 | void DiagnoseUnguardedAvailabilityViolations(Decl *FD); |
4130 | |
4131 | //===--------------------------------------------------------------------===// |
4132 | // Expression Parsing Callbacks: SemaExpr.cpp. |
4133 | |
4134 | bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); |
4135 | bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, |
4136 | const ObjCInterfaceDecl *UnknownObjCClass = nullptr, |
4137 | bool ObjCPropertyAccess = false, |
4138 | bool AvoidPartialAvailabilityChecks = false, |
4139 | ObjCInterfaceDecl *ClassReciever = nullptr); |
4140 | void NoteDeletedFunction(FunctionDecl *FD); |
4141 | void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); |
4142 | bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, |
4143 | ObjCMethodDecl *Getter, |
4144 | SourceLocation Loc); |
4145 | void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, |
4146 | ArrayRef<Expr *> Args); |
4147 | |
4148 | void PushExpressionEvaluationContext( |
4149 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, |
4150 | ExpressionEvaluationContextRecord::ExpressionKind Type = |
4151 | ExpressionEvaluationContextRecord::EK_Other); |
4152 | enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; |
4153 | void PushExpressionEvaluationContext( |
4154 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, |
4155 | ExpressionEvaluationContextRecord::ExpressionKind Type = |
4156 | ExpressionEvaluationContextRecord::EK_Other); |
4157 | void PopExpressionEvaluationContext(); |
4158 | |
4159 | void DiscardCleanupsInEvaluationContext(); |
4160 | |
4161 | ExprResult TransformToPotentiallyEvaluated(Expr *E); |
4162 | ExprResult HandleExprEvaluationContextForTypeof(Expr *E); |
4163 | |
4164 | ExprResult ActOnConstantExpression(ExprResult Res); |
4165 | |
4166 | // Functions for marking a declaration referenced. These functions also |
4167 | // contain the relevant logic for marking if a reference to a function or |
4168 | // variable is an odr-use (in the C++11 sense). There are separate variants |
4169 | // for expressions referring to a decl; these exist because odr-use marking |
4170 | // needs to be delayed for some constant variables when we build one of the |
4171 | // named expressions. |
4172 | // |
4173 | // MightBeOdrUse indicates whether the use could possibly be an odr-use, and |
4174 | // should usually be true. This only needs to be set to false if the lack of |
4175 | // odr-use cannot be determined from the current context (for instance, |
4176 | // because the name denotes a virtual function and was written without an |
4177 | // explicit nested-name-specifier). |
4178 | void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); |
4179 | void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, |
4180 | bool MightBeOdrUse = true); |
4181 | void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); |
4182 | void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); |
4183 | void MarkMemberReferenced(MemberExpr *E); |
4184 | void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); |
4185 | void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, |
4186 | unsigned CapturingScopeIndex); |
4187 | |
4188 | void UpdateMarkingForLValueToRValue(Expr *E); |
4189 | void CleanupVarDeclMarking(); |
4190 | |
4191 | enum TryCaptureKind { |
4192 | TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef |
4193 | }; |
4194 | |
4195 | /// Try to capture the given variable. |
4196 | /// |
4197 | /// \param Var The variable to capture. |
4198 | /// |
4199 | /// \param Loc The location at which the capture occurs. |
4200 | /// |
4201 | /// \param Kind The kind of capture, which may be implicit (for either a |
4202 | /// block or a lambda), or explicit by-value or by-reference (for a lambda). |
4203 | /// |
4204 | /// \param EllipsisLoc The location of the ellipsis, if one is provided in |
4205 | /// an explicit lambda capture. |
4206 | /// |
4207 | /// \param BuildAndDiagnose Whether we are actually supposed to add the |
4208 | /// captures or diagnose errors. If false, this routine merely check whether |
4209 | /// the capture can occur without performing the capture itself or complaining |
4210 | /// if the variable cannot be captured. |
4211 | /// |
4212 | /// \param CaptureType Will be set to the type of the field used to capture |
4213 | /// this variable in the innermost block or lambda. Only valid when the |
4214 | /// variable can be captured. |
4215 | /// |
4216 | /// \param DeclRefType Will be set to the type of a reference to the capture |
4217 | /// from within the current scope. Only valid when the variable can be |
4218 | /// captured. |
4219 | /// |
4220 | /// \param FunctionScopeIndexToStopAt If non-null, it points to the index |
4221 | /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. |
4222 | /// This is useful when enclosing lambdas must speculatively capture |
4223 | /// variables that may or may not be used in certain specializations of |
4224 | /// a nested generic lambda. |
4225 | /// |
4226 | /// \returns true if an error occurred (i.e., the variable cannot be |
4227 | /// captured) and false if the capture succeeded. |
4228 | bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, |
4229 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, |
4230 | QualType &CaptureType, |
4231 | QualType &DeclRefType, |
4232 | const unsigned *const FunctionScopeIndexToStopAt); |
4233 | |
4234 | /// Try to capture the given variable. |
4235 | bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, |
4236 | TryCaptureKind Kind = TryCapture_Implicit, |
4237 | SourceLocation EllipsisLoc = SourceLocation()); |
4238 | |
4239 | /// Checks if the variable must be captured. |
4240 | bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); |
4241 | |
4242 | /// Given a variable, determine the type that a reference to that |
4243 | /// variable will have in the given scope. |
4244 | QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); |
4245 | |
4246 | /// Mark all of the declarations referenced within a particular AST node as |
4247 | /// referenced. Used when template instantiation instantiates a non-dependent |
4248 | /// type -- entities referenced by the type are now referenced. |
4249 | void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); |
4250 | void MarkDeclarationsReferencedInExpr(Expr *E, |
4251 | bool SkipLocalVariables = false); |
4252 | |
4253 | /// Try to recover by turning the given expression into a |
4254 | /// call. Returns true if recovery was attempted or an error was |
4255 | /// emitted; this may also leave the ExprResult invalid. |
4256 | bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, |
4257 | bool ForceComplain = false, |
4258 | bool (*IsPlausibleResult)(QualType) = nullptr); |
4259 | |
4260 | /// Figure out if an expression could be turned into a call. |
4261 | bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, |
4262 | UnresolvedSetImpl &NonTemplateOverloads); |
4263 | |
4264 | /// Conditionally issue a diagnostic based on the current |
4265 | /// evaluation context. |
4266 | /// |
4267 | /// \param Statement If Statement is non-null, delay reporting the |
4268 | /// diagnostic until the function body is parsed, and then do a basic |
4269 | /// reachability analysis to determine if the statement is reachable. |
4270 | /// If it is unreachable, the diagnostic will not be emitted. |
4271 | bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, |
4272 | const PartialDiagnostic &PD); |
4273 | /// Similar, but diagnostic is only produced if all the specified statements |
4274 | /// are reachable. |
4275 | bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, |
4276 | const PartialDiagnostic &PD); |
4277 | |
4278 | // Primary Expressions. |
4279 | SourceRange getExprRange(Expr *E) const; |
4280 | |
4281 | ExprResult ActOnIdExpression( |
4282 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
4283 | UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, |
4284 | CorrectionCandidateCallback *CCC = nullptr, |
4285 | bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); |
4286 | |
4287 | void DecomposeUnqualifiedId(const UnqualifiedId &Id, |
4288 | TemplateArgumentListInfo &Buffer, |
4289 | DeclarationNameInfo &NameInfo, |
4290 | const TemplateArgumentListInfo *&TemplateArgs); |
4291 | |
4292 | bool |
4293 | DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, |
4294 | CorrectionCandidateCallback &CCC, |
4295 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, |
4296 | ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); |
4297 | |
4298 | ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, |
4299 | IdentifierInfo *II, |
4300 | bool AllowBuiltinCreation=false); |
4301 | |
4302 | ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, |
4303 | SourceLocation TemplateKWLoc, |
4304 | const DeclarationNameInfo &NameInfo, |
4305 | bool isAddressOfOperand, |
4306 | const TemplateArgumentListInfo *TemplateArgs); |
4307 | |
4308 | DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
4309 | SourceLocation Loc, |
4310 | const CXXScopeSpec *SS = nullptr); |
4311 | DeclRefExpr * |
4312 | BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
4313 | const DeclarationNameInfo &NameInfo, |
4314 | const CXXScopeSpec *SS = nullptr, |
4315 | NamedDecl *FoundD = nullptr, |
4316 | SourceLocation TemplateKWLoc = SourceLocation(), |
4317 | const TemplateArgumentListInfo *TemplateArgs = nullptr); |
4318 | DeclRefExpr * |
4319 | BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
4320 | const DeclarationNameInfo &NameInfo, |
4321 | NestedNameSpecifierLoc NNS, |
4322 | NamedDecl *FoundD = nullptr, |
4323 | SourceLocation TemplateKWLoc = SourceLocation(), |
4324 | const TemplateArgumentListInfo *TemplateArgs = nullptr); |
4325 | |
4326 | ExprResult |
4327 | BuildAnonymousStructUnionMemberReference( |
4328 | const CXXScopeSpec &SS, |
4329 | SourceLocation nameLoc, |
4330 | IndirectFieldDecl *indirectField, |
4331 | DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), |
4332 | Expr *baseObjectExpr = nullptr, |
4333 | SourceLocation opLoc = SourceLocation()); |
4334 | |
4335 | ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, |
4336 | SourceLocation TemplateKWLoc, |
4337 | LookupResult &R, |
4338 | const TemplateArgumentListInfo *TemplateArgs, |
4339 | const Scope *S); |
4340 | ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, |
4341 | SourceLocation TemplateKWLoc, |
4342 | LookupResult &R, |
4343 | const TemplateArgumentListInfo *TemplateArgs, |
4344 | bool IsDefiniteInstance, |
4345 | const Scope *S); |
4346 | bool UseArgumentDependentLookup(const CXXScopeSpec &SS, |
4347 | const LookupResult &R, |
4348 | bool HasTrailingLParen); |
4349 | |
4350 | ExprResult |
4351 | BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, |
4352 | const DeclarationNameInfo &NameInfo, |
4353 | bool IsAddressOfOperand, const Scope *S, |
4354 | TypeSourceInfo **RecoveryTSI = nullptr); |
4355 | |
4356 | ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, |
4357 | SourceLocation TemplateKWLoc, |
4358 | const DeclarationNameInfo &NameInfo, |
4359 | const TemplateArgumentListInfo *TemplateArgs); |
4360 | |
4361 | ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, |
4362 | LookupResult &R, |
4363 | bool NeedsADL, |
4364 | bool AcceptInvalidDecl = false); |
4365 | ExprResult BuildDeclarationNameExpr( |
4366 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, |
4367 | NamedDecl *FoundD = nullptr, |
4368 | const TemplateArgumentListInfo *TemplateArgs = nullptr, |
4369 | bool AcceptInvalidDecl = false); |
4370 | |
4371 | ExprResult BuildLiteralOperatorCall(LookupResult &R, |
4372 | DeclarationNameInfo &SuffixInfo, |
4373 | ArrayRef<Expr *> Args, |
4374 | SourceLocation LitEndLoc, |
4375 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); |
4376 | |
4377 | ExprResult BuildPredefinedExpr(SourceLocation Loc, |
4378 | PredefinedExpr::IdentKind IK); |
4379 | ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); |
4380 | ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); |
4381 | |
4382 | bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); |
4383 | |
4384 | ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); |
4385 | ExprResult ActOnCharacterConstant(const Token &Tok, |
4386 | Scope *UDLScope = nullptr); |
4387 | ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); |
4388 | ExprResult ActOnParenListExpr(SourceLocation L, |
4389 | SourceLocation R, |
4390 | MultiExprArg Val); |
4391 | |
4392 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string |
4393 | /// fragments (e.g. "foo" "bar" L"baz"). |
4394 | ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, |
4395 | Scope *UDLScope = nullptr); |
4396 | |
4397 | ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, |
4398 | SourceLocation DefaultLoc, |
4399 | SourceLocation RParenLoc, |
4400 | Expr *ControllingExpr, |
4401 | ArrayRef<ParsedType> ArgTypes, |
4402 | ArrayRef<Expr *> ArgExprs); |
4403 | ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, |
4404 | SourceLocation DefaultLoc, |
4405 | SourceLocation RParenLoc, |
4406 | Expr *ControllingExpr, |
4407 | ArrayRef<TypeSourceInfo *> Types, |
4408 | ArrayRef<Expr *> Exprs); |
4409 | |
4410 | // Binary/Unary Operators. 'Tok' is the token for the operator. |
4411 | ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, |
4412 | Expr *InputExpr); |
4413 | ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, |
4414 | UnaryOperatorKind Opc, Expr *Input); |
4415 | ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, |
4416 | tok::TokenKind Op, Expr *Input); |
4417 | |
4418 | bool isQualifiedMemberAccess(Expr *E); |
4419 | QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); |
4420 | |
4421 | ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, |
4422 | SourceLocation OpLoc, |
4423 | UnaryExprOrTypeTrait ExprKind, |
4424 | SourceRange R); |
4425 | ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, |
4426 | UnaryExprOrTypeTrait ExprKind); |
4427 | ExprResult |
4428 | ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, |
4429 | UnaryExprOrTypeTrait ExprKind, |
4430 | bool IsType, void *TyOrEx, |
4431 | SourceRange ArgRange); |
4432 | |
4433 | ExprResult CheckPlaceholderExpr(Expr *E); |
4434 | bool CheckVecStepExpr(Expr *E); |
4435 | |
4436 | bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); |
4437 | bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, |
4438 | SourceRange ExprRange, |
4439 | UnaryExprOrTypeTrait ExprKind); |
4440 | ExprResult ActOnSizeofParameterPackExpr(Scope *S, |
4441 | SourceLocation OpLoc, |
4442 | IdentifierInfo &Name, |
4443 | SourceLocation NameLoc, |
4444 | SourceLocation RParenLoc); |
4445 | ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, |
4446 | tok::TokenKind Kind, Expr *Input); |
4447 | |
4448 | ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, |
4449 | Expr *Idx, SourceLocation RLoc); |
4450 | ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, |
4451 | Expr *Idx, SourceLocation RLoc); |
4452 | ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, |
4453 | Expr *LowerBound, SourceLocation ColonLoc, |
4454 | Expr *Length, SourceLocation RBLoc); |
4455 | |
4456 | // This struct is for use by ActOnMemberAccess to allow |
4457 | // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after |
4458 | // changing the access operator from a '.' to a '->' (to see if that is the |
4459 | // change needed to fix an error about an unknown member, e.g. when the class |
4460 | // defines a custom operator->). |
4461 | struct ActOnMemberAccessExtraArgs { |
4462 | Scope *S; |
4463 | UnqualifiedId &Id; |
4464 | Decl *ObjCImpDecl; |
4465 | }; |
4466 | |
4467 | ExprResult BuildMemberReferenceExpr( |
4468 | Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, |
4469 | CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
4470 | NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, |
4471 | const TemplateArgumentListInfo *TemplateArgs, |
4472 | const Scope *S, |
4473 | ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); |
4474 | |
4475 | ExprResult |
4476 | BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, |
4477 | bool IsArrow, const CXXScopeSpec &SS, |
4478 | SourceLocation TemplateKWLoc, |
4479 | NamedDecl *FirstQualifierInScope, LookupResult &R, |
4480 | const TemplateArgumentListInfo *TemplateArgs, |
4481 | const Scope *S, |
4482 | bool SuppressQualifierCheck = false, |
4483 | ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); |
4484 | |
4485 | ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, |
4486 | SourceLocation OpLoc, |
4487 | const CXXScopeSpec &SS, FieldDecl *Field, |
4488 | DeclAccessPair FoundDecl, |
4489 | const DeclarationNameInfo &MemberNameInfo); |
4490 | |
4491 | ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); |
4492 | |
4493 | bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, |
4494 | const CXXScopeSpec &SS, |
4495 | const LookupResult &R); |
4496 | |
4497 | ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, |
4498 | bool IsArrow, SourceLocation OpLoc, |
4499 | const CXXScopeSpec &SS, |
4500 | SourceLocation TemplateKWLoc, |
4501 | NamedDecl *FirstQualifierInScope, |
4502 | const DeclarationNameInfo &NameInfo, |
4503 | const TemplateArgumentListInfo *TemplateArgs); |
4504 | |
4505 | ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, |
4506 | SourceLocation OpLoc, |
4507 | tok::TokenKind OpKind, |
4508 | CXXScopeSpec &SS, |
4509 | SourceLocation TemplateKWLoc, |
4510 | UnqualifiedId &Member, |
4511 | Decl *ObjCImpDecl); |
4512 | |
4513 | void ActOnDefaultCtorInitializers(Decl *CDtorDecl); |
4514 | bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, |
4515 | FunctionDecl *FDecl, |
4516 | const FunctionProtoType *Proto, |
4517 | ArrayRef<Expr *> Args, |
4518 | SourceLocation RParenLoc, |
4519 | bool ExecConfig = false); |
4520 | void CheckStaticArrayArgument(SourceLocation CallLoc, |
4521 | ParmVarDecl *Param, |
4522 | const Expr *ArgExpr); |
4523 | |
4524 | /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. |
4525 | /// This provides the location of the left/right parens and a list of comma |
4526 | /// locations. |
4527 | ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, |
4528 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
4529 | Expr *ExecConfig = nullptr); |
4530 | ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, |
4531 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
4532 | Expr *ExecConfig = nullptr, |
4533 | bool IsExecConfig = false); |
4534 | ExprResult |
4535 | BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, |
4536 | ArrayRef<Expr *> Arg, SourceLocation RParenLoc, |
4537 | Expr *Config = nullptr, bool IsExecConfig = false, |
4538 | ADLCallKind UsesADL = ADLCallKind::NotADL); |
4539 | |
4540 | ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, |
4541 | MultiExprArg ExecConfig, |
4542 | SourceLocation GGGLoc); |
4543 | |
4544 | ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, |
4545 | Declarator &D, ParsedType &Ty, |
4546 | SourceLocation RParenLoc, Expr *CastExpr); |
4547 | ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, |
4548 | TypeSourceInfo *Ty, |
4549 | SourceLocation RParenLoc, |
4550 | Expr *Op); |
4551 | CastKind PrepareScalarCast(ExprResult &src, QualType destType); |
4552 | |
4553 | /// Build an altivec or OpenCL literal. |
4554 | ExprResult BuildVectorLiteral(SourceLocation LParenLoc, |
4555 | SourceLocation RParenLoc, Expr *E, |
4556 | TypeSourceInfo *TInfo); |
4557 | |
4558 | ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); |
4559 | |
4560 | ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, |
4561 | ParsedType Ty, |
4562 | SourceLocation RParenLoc, |
4563 | Expr *InitExpr); |
4564 | |
4565 | ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, |
4566 | TypeSourceInfo *TInfo, |
4567 | SourceLocation RParenLoc, |
4568 | Expr *LiteralExpr); |
4569 | |
4570 | ExprResult ActOnInitList(SourceLocation LBraceLoc, |
4571 | MultiExprArg InitArgList, |
4572 | SourceLocation RBraceLoc); |
4573 | |
4574 | ExprResult ActOnDesignatedInitializer(Designation &Desig, |
4575 | SourceLocation Loc, |
4576 | bool GNUSyntax, |
4577 | ExprResult Init); |
4578 | |
4579 | private: |
4580 | static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); |
4581 | |
4582 | public: |
4583 | ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, |
4584 | tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); |
4585 | ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, |
4586 | BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); |
4587 | ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, |
4588 | Expr *LHSExpr, Expr *RHSExpr); |
4589 | |
4590 | void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); |
4591 | |
4592 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null |
4593 | /// in the case of a the GNU conditional expr extension. |
4594 | ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, |
4595 | SourceLocation ColonLoc, |
4596 | Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); |
4597 | |
4598 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". |
4599 | ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, |
4600 | LabelDecl *TheDecl); |
4601 | |
4602 | void ActOnStartStmtExpr(); |
4603 | ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, |
4604 | SourceLocation RPLoc); // "({..})" |
4605 | // Handle the final expression in a statement expression. |
4606 | ExprResult ActOnStmtExprResult(ExprResult E); |
4607 | void ActOnStmtExprError(); |
4608 | |
4609 | // __builtin_offsetof(type, identifier(.identifier|[expr])*) |
4610 | struct OffsetOfComponent { |
4611 | SourceLocation LocStart, LocEnd; |
4612 | bool isBrackets; // true if [expr], false if .ident |
4613 | union { |
4614 | IdentifierInfo *IdentInfo; |
4615 | Expr *E; |
4616 | } U; |
4617 | }; |
4618 | |
4619 | /// __builtin_offsetof(type, a.b[123][456].c) |
4620 | ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, |
4621 | TypeSourceInfo *TInfo, |
4622 | ArrayRef<OffsetOfComponent> Components, |
4623 | SourceLocation RParenLoc); |
4624 | ExprResult ActOnBuiltinOffsetOf(Scope *S, |
4625 | SourceLocation BuiltinLoc, |
4626 | SourceLocation TypeLoc, |
4627 | ParsedType ParsedArgTy, |
4628 | ArrayRef<OffsetOfComponent> Components, |
4629 | SourceLocation RParenLoc); |
4630 | |
4631 | // __builtin_choose_expr(constExpr, expr1, expr2) |
4632 | ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, |
4633 | Expr *CondExpr, Expr *LHSExpr, |
4634 | Expr *RHSExpr, SourceLocation RPLoc); |
4635 | |
4636 | // __builtin_va_arg(expr, type) |
4637 | ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, |
4638 | SourceLocation RPLoc); |
4639 | ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, |
4640 | TypeSourceInfo *TInfo, SourceLocation RPLoc); |
4641 | |
4642 | // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), |
4643 | // __builtin_COLUMN() |
4644 | ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, |
4645 | SourceLocation BuiltinLoc, |
4646 | SourceLocation RPLoc); |
4647 | |
4648 | // Build a potentially resolved SourceLocExpr. |
4649 | ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, |
4650 | SourceLocation BuiltinLoc, SourceLocation RPLoc, |
4651 | DeclContext *ParentContext); |
4652 | |
4653 | // __null |
4654 | ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); |
4655 | |
4656 | bool CheckCaseExpression(Expr *E); |
4657 | |
4658 | /// Describes the result of an "if-exists" condition check. |
4659 | enum IfExistsResult { |
4660 | /// The symbol exists. |
4661 | IER_Exists, |
4662 | |
4663 | /// The symbol does not exist. |
4664 | IER_DoesNotExist, |
4665 | |
4666 | /// The name is a dependent name, so the results will differ |
4667 | /// from one instantiation to the next. |
4668 | IER_Dependent, |
4669 | |
4670 | /// An error occurred. |
4671 | IER_Error |
4672 | }; |
4673 | |
4674 | IfExistsResult |
4675 | CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, |
4676 | const DeclarationNameInfo &TargetNameInfo); |
4677 | |
4678 | IfExistsResult |
4679 | CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, |
4680 | bool IsIfExists, CXXScopeSpec &SS, |
4681 | UnqualifiedId &Name); |
4682 | |
4683 | StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, |
4684 | bool IsIfExists, |
4685 | NestedNameSpecifierLoc QualifierLoc, |
4686 | DeclarationNameInfo NameInfo, |
4687 | Stmt *Nested); |
4688 | StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, |
4689 | bool IsIfExists, |
4690 | CXXScopeSpec &SS, UnqualifiedId &Name, |
4691 | Stmt *Nested); |
4692 | |
4693 | //===------------------------- "Block" Extension ------------------------===// |
4694 | |
4695 | /// ActOnBlockStart - This callback is invoked when a block literal is |
4696 | /// started. |
4697 | void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); |
4698 | |
4699 | /// ActOnBlockArguments - This callback allows processing of block arguments. |
4700 | /// If there are no arguments, this is still invoked. |
4701 | void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, |
4702 | Scope *CurScope); |
4703 | |
4704 | /// ActOnBlockError - If there is an error parsing a block, this callback |
4705 | /// is invoked to pop the information about the block from the action impl. |
4706 | void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); |
4707 | |
4708 | /// ActOnBlockStmtExpr - This is called when the body of a block statement |
4709 | /// literal was successfully completed. ^(int x){...} |
4710 | ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, |
4711 | Scope *CurScope); |
4712 | |
4713 | //===---------------------------- Clang Extensions ----------------------===// |
4714 | |
4715 | /// __builtin_convertvector(...) |
4716 | ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, |
4717 | SourceLocation BuiltinLoc, |
4718 | SourceLocation RParenLoc); |
4719 | |
4720 | //===---------------------------- OpenCL Features -----------------------===// |
4721 | |
4722 | /// __builtin_astype(...) |
4723 | ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, |
4724 | SourceLocation BuiltinLoc, |
4725 | SourceLocation RParenLoc); |
4726 | |
4727 | //===---------------------------- C++ Features --------------------------===// |
4728 | |
4729 | // Act on C++ namespaces |
4730 | Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, |
4731 | SourceLocation NamespaceLoc, |
4732 | SourceLocation IdentLoc, IdentifierInfo *Ident, |
4733 | SourceLocation LBrace, |
4734 | const ParsedAttributesView &AttrList, |
4735 | UsingDirectiveDecl *&UsingDecl); |
4736 | void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); |
4737 | |
4738 | NamespaceDecl *getStdNamespace() const; |
4739 | NamespaceDecl *getOrCreateStdNamespace(); |
4740 | |
4741 | NamespaceDecl *lookupStdExperimentalNamespace(); |
4742 | |
4743 | CXXRecordDecl *getStdBadAlloc() const; |
4744 | EnumDecl *getStdAlignValT() const; |
4745 | |
4746 | private: |
4747 | // A cache representing if we've fully checked the various comparison category |
4748 | // types stored in ASTContext. The bit-index corresponds to the integer value |
4749 | // of a ComparisonCategoryType enumerator. |
4750 | llvm::SmallBitVector FullyCheckedComparisonCategories; |
4751 | |
4752 | ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, |
4753 | CXXScopeSpec &SS, |
4754 | ParsedType TemplateTypeTy, |
4755 | IdentifierInfo *MemberOrBase); |
4756 | |
4757 | public: |
4758 | /// Lookup the specified comparison category types in the standard |
4759 | /// library, an check the VarDecls possibly returned by the operator<=> |
4760 | /// builtins for that type. |
4761 | /// |
4762 | /// \return The type of the comparison category type corresponding to the |
4763 | /// specified Kind, or a null type if an error occurs |
4764 | QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, |
4765 | SourceLocation Loc); |
4766 | |
4767 | /// Tests whether Ty is an instance of std::initializer_list and, if |
4768 | /// it is and Element is not NULL, assigns the element type to Element. |
4769 | bool isStdInitializerList(QualType Ty, QualType *Element); |
4770 | |
4771 | /// Looks for the std::initializer_list template and instantiates it |
4772 | /// with Element, or emits an error if it's not found. |
4773 | /// |
4774 | /// \returns The instantiated template, or null on error. |
4775 | QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); |
4776 | |
4777 | /// Determine whether Ctor is an initializer-list constructor, as |
4778 | /// defined in [dcl.init.list]p2. |
4779 | bool isInitListConstructor(const FunctionDecl *Ctor); |
4780 | |
4781 | Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, |
4782 | SourceLocation NamespcLoc, CXXScopeSpec &SS, |
4783 | SourceLocation IdentLoc, |
4784 | IdentifierInfo *NamespcName, |
4785 | const ParsedAttributesView &AttrList); |
4786 | |
4787 | void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); |
4788 | |
4789 | Decl *ActOnNamespaceAliasDef(Scope *CurScope, |
4790 | SourceLocation NamespaceLoc, |
4791 | SourceLocation AliasLoc, |
4792 | IdentifierInfo *Alias, |
4793 | CXXScopeSpec &SS, |
4794 | SourceLocation IdentLoc, |
4795 | IdentifierInfo *Ident); |
4796 | |
4797 | void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); |
4798 | bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, |
4799 | const LookupResult &PreviousDecls, |
4800 | UsingShadowDecl *&PrevShadow); |
4801 | UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, |
4802 | NamedDecl *Target, |
4803 | UsingShadowDecl *PrevDecl); |
4804 | |
4805 | bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, |
4806 | bool HasTypenameKeyword, |
4807 | const CXXScopeSpec &SS, |
4808 | SourceLocation NameLoc, |
4809 | const LookupResult &Previous); |
4810 | bool CheckUsingDeclQualifier(SourceLocation UsingLoc, |
4811 | bool HasTypename, |
4812 | const CXXScopeSpec &SS, |
4813 | const DeclarationNameInfo &NameInfo, |
4814 | SourceLocation NameLoc); |
4815 | |
4816 | NamedDecl *BuildUsingDeclaration( |
4817 | Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, |
4818 | bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, |
4819 | DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, |
4820 | const ParsedAttributesView &AttrList, bool IsInstantiation); |
4821 | NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, |
4822 | ArrayRef<NamedDecl *> Expansions); |
4823 | |
4824 | bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); |
4825 | |
4826 | /// Given a derived-class using shadow declaration for a constructor and the |
4827 | /// correspnding base class constructor, find or create the implicit |
4828 | /// synthesized derived class constructor to use for this initialization. |
4829 | CXXConstructorDecl * |
4830 | findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, |
4831 | ConstructorUsingShadowDecl *DerivedShadow); |
4832 | |
4833 | Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, |
4834 | SourceLocation UsingLoc, |
4835 | SourceLocation TypenameLoc, CXXScopeSpec &SS, |
4836 | UnqualifiedId &Name, SourceLocation EllipsisLoc, |
4837 | const ParsedAttributesView &AttrList); |
4838 | Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, |
4839 | MultiTemplateParamsArg TemplateParams, |
4840 | SourceLocation UsingLoc, UnqualifiedId &Name, |
4841 | const ParsedAttributesView &AttrList, |
4842 | TypeResult Type, Decl *DeclFromDeclSpec); |
4843 | |
4844 | /// BuildCXXConstructExpr - Creates a complete call to a constructor, |
4845 | /// including handling of its default argument expressions. |
4846 | /// |
4847 | /// \param ConstructKind - a CXXConstructExpr::ConstructionKind |
4848 | ExprResult |
4849 | BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, |
4850 | NamedDecl *FoundDecl, |
4851 | CXXConstructorDecl *Constructor, MultiExprArg Exprs, |
4852 | bool HadMultipleCandidates, bool IsListInitialization, |
4853 | bool IsStdInitListInitialization, |
4854 | bool RequiresZeroInit, unsigned ConstructKind, |
4855 | SourceRange ParenRange); |
4856 | |
4857 | /// Build a CXXConstructExpr whose constructor has already been resolved if |
4858 | /// it denotes an inherited constructor. |
4859 | ExprResult |
4860 | BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, |
4861 | CXXConstructorDecl *Constructor, bool Elidable, |
4862 | MultiExprArg Exprs, |
4863 | bool HadMultipleCandidates, bool IsListInitialization, |
4864 | bool IsStdInitListInitialization, |
4865 | bool RequiresZeroInit, unsigned ConstructKind, |
4866 | SourceRange ParenRange); |
4867 | |
4868 | // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if |
4869 | // the constructor can be elidable? |
4870 | ExprResult |
4871 | BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, |
4872 | NamedDecl *FoundDecl, |
4873 | CXXConstructorDecl *Constructor, bool Elidable, |
4874 | MultiExprArg Exprs, bool HadMultipleCandidates, |
4875 | bool IsListInitialization, |
4876 | bool IsStdInitListInitialization, bool RequiresZeroInit, |
4877 | unsigned ConstructKind, SourceRange ParenRange); |
4878 | |
4879 | ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); |
4880 | |
4881 | |
4882 | /// Instantiate or parse a C++ default argument expression as necessary. |
4883 | /// Return true on error. |
4884 | bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, |
4885 | ParmVarDecl *Param); |
4886 | |
4887 | /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating |
4888 | /// the default expr if needed. |
4889 | ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, |
4890 | FunctionDecl *FD, |
4891 | ParmVarDecl *Param); |
4892 | |
4893 | /// FinalizeVarWithDestructor - Prepare for calling destructor on the |
4894 | /// constructed variable. |
4895 | void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); |
4896 | |
4897 | /// Helper class that collects exception specifications for |
4898 | /// implicitly-declared special member functions. |
4899 | class ImplicitExceptionSpecification { |
4900 | // Pointer to allow copying |
4901 | Sema *Self; |
4902 | // We order exception specifications thus: |
4903 | // noexcept is the most restrictive, but is only used in C++11. |
4904 | // throw() comes next. |
4905 | // Then a throw(collected exceptions) |
4906 | // Finally no specification, which is expressed as noexcept(false). |
4907 | // throw(...) is used instead if any called function uses it. |
4908 | ExceptionSpecificationType ComputedEST; |
4909 | llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; |
4910 | SmallVector<QualType, 4> Exceptions; |
4911 | |
4912 | void ClearExceptions() { |
4913 | ExceptionsSeen.clear(); |
4914 | Exceptions.clear(); |
4915 | } |
4916 | |
4917 | public: |
4918 | explicit ImplicitExceptionSpecification(Sema &Self) |
4919 | : Self(&Self), ComputedEST(EST_BasicNoexcept) { |
4920 | if (!Self.getLangOpts().CPlusPlus11) |
4921 | ComputedEST = EST_DynamicNone; |
4922 | } |
4923 | |
4924 | /// Get the computed exception specification type. |
4925 | ExceptionSpecificationType getExceptionSpecType() const { |
4926 | assert(!isComputedNoexcept(ComputedEST) &&((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result" ) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 4927, __PRETTY_FUNCTION__)) |
4927 | "noexcept(expr) should not be a possible result")((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result" ) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 4927, __PRETTY_FUNCTION__)); |
4928 | return ComputedEST; |
4929 | } |
4930 | |
4931 | /// The number of exceptions in the exception specification. |
4932 | unsigned size() const { return Exceptions.size(); } |
4933 | |
4934 | /// The set of exceptions in the exception specification. |
4935 | const QualType *data() const { return Exceptions.data(); } |
4936 | |
4937 | /// Integrate another called method into the collected data. |
4938 | void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); |
4939 | |
4940 | /// Integrate an invoked expression into the collected data. |
4941 | void CalledExpr(Expr *E); |
4942 | |
4943 | /// Overwrite an EPI's exception specification with this |
4944 | /// computed exception specification. |
4945 | FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { |
4946 | FunctionProtoType::ExceptionSpecInfo ESI; |
4947 | ESI.Type = getExceptionSpecType(); |
4948 | if (ESI.Type == EST_Dynamic) { |
4949 | ESI.Exceptions = Exceptions; |
4950 | } else if (ESI.Type == EST_None) { |
4951 | /// C++11 [except.spec]p14: |
4952 | /// The exception-specification is noexcept(false) if the set of |
4953 | /// potential exceptions of the special member function contains "any" |
4954 | ESI.Type = EST_NoexceptFalse; |
4955 | ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), |
4956 | tok::kw_false).get(); |
4957 | } |
4958 | return ESI; |
4959 | } |
4960 | }; |
4961 | |
4962 | /// Determine what sort of exception specification a defaulted |
4963 | /// copy constructor of a class will have. |
4964 | ImplicitExceptionSpecification |
4965 | ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, |
4966 | CXXMethodDecl *MD); |
4967 | |
4968 | /// Determine what sort of exception specification a defaulted |
4969 | /// default constructor of a class will have, and whether the parameter |
4970 | /// will be const. |
4971 | ImplicitExceptionSpecification |
4972 | ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); |
4973 | |
4974 | /// Determine what sort of exception specification a defaulted |
4975 | /// copy assignment operator of a class will have, and whether the |
4976 | /// parameter will be const. |
4977 | ImplicitExceptionSpecification |
4978 | ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); |
4979 | |
4980 | /// Determine what sort of exception specification a defaulted move |
4981 | /// constructor of a class will have. |
4982 | ImplicitExceptionSpecification |
4983 | ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); |
4984 | |
4985 | /// Determine what sort of exception specification a defaulted move |
4986 | /// assignment operator of a class will have. |
4987 | ImplicitExceptionSpecification |
4988 | ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); |
4989 | |
4990 | /// Determine what sort of exception specification a defaulted |
4991 | /// destructor of a class will have. |
4992 | ImplicitExceptionSpecification |
4993 | ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); |
4994 | |
4995 | /// Determine what sort of exception specification an inheriting |
4996 | /// constructor of a class will have. |
4997 | ImplicitExceptionSpecification |
4998 | ComputeInheritingCtorExceptionSpec(SourceLocation Loc, |
4999 | CXXConstructorDecl *CD); |
5000 | |
5001 | /// Evaluate the implicit exception specification for a defaulted |
5002 | /// special member function. |
5003 | void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); |
5004 | |
5005 | /// Check the given noexcept-specifier, convert its expression, and compute |
5006 | /// the appropriate ExceptionSpecificationType. |
5007 | ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, |
5008 | ExceptionSpecificationType &EST); |
5009 | |
5010 | /// Check the given exception-specification and update the |
5011 | /// exception specification information with the results. |
5012 | void checkExceptionSpecification(bool IsTopLevel, |
5013 | ExceptionSpecificationType EST, |
5014 | ArrayRef<ParsedType> DynamicExceptions, |
5015 | ArrayRef<SourceRange> DynamicExceptionRanges, |
5016 | Expr *NoexceptExpr, |
5017 | SmallVectorImpl<QualType> &Exceptions, |
5018 | FunctionProtoType::ExceptionSpecInfo &ESI); |
5019 | |
5020 | /// Determine if we're in a case where we need to (incorrectly) eagerly |
5021 | /// parse an exception specification to work around a libstdc++ bug. |
5022 | bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); |
5023 | |
5024 | /// Add an exception-specification to the given member function |
5025 | /// (or member function template). The exception-specification was parsed |
5026 | /// after the method itself was declared. |
5027 | void actOnDelayedExceptionSpecification(Decl *Method, |
5028 | ExceptionSpecificationType EST, |
5029 | SourceRange SpecificationRange, |
5030 | ArrayRef<ParsedType> DynamicExceptions, |
5031 | ArrayRef<SourceRange> DynamicExceptionRanges, |
5032 | Expr *NoexceptExpr); |
5033 | |
5034 | class InheritedConstructorInfo; |
5035 | |
5036 | /// Determine if a special member function should have a deleted |
5037 | /// definition when it is defaulted. |
5038 | bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, |
5039 | InheritedConstructorInfo *ICI = nullptr, |
5040 | bool Diagnose = false); |
5041 | |
5042 | /// Declare the implicit default constructor for the given class. |
5043 | /// |
5044 | /// \param ClassDecl The class declaration into which the implicit |
5045 | /// default constructor will be added. |
5046 | /// |
5047 | /// \returns The implicitly-declared default constructor. |
5048 | CXXConstructorDecl *DeclareImplicitDefaultConstructor( |
5049 | CXXRecordDecl *ClassDecl); |
5050 | |
5051 | /// DefineImplicitDefaultConstructor - Checks for feasibility of |
5052 | /// defining this constructor as the default constructor. |
5053 | void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, |
5054 | CXXConstructorDecl *Constructor); |
5055 | |
5056 | /// Declare the implicit destructor for the given class. |
5057 | /// |
5058 | /// \param ClassDecl The class declaration into which the implicit |
5059 | /// destructor will be added. |
5060 | /// |
5061 | /// \returns The implicitly-declared destructor. |
5062 | CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); |
5063 | |
5064 | /// DefineImplicitDestructor - Checks for feasibility of |
5065 | /// defining this destructor as the default destructor. |
5066 | void DefineImplicitDestructor(SourceLocation CurrentLocation, |
5067 | CXXDestructorDecl *Destructor); |
5068 | |
5069 | /// Build an exception spec for destructors that don't have one. |
5070 | /// |
5071 | /// C++11 says that user-defined destructors with no exception spec get one |
5072 | /// that looks as if the destructor was implicitly declared. |
5073 | void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); |
5074 | |
5075 | /// Define the specified inheriting constructor. |
5076 | void DefineInheritingConstructor(SourceLocation UseLoc, |
5077 | CXXConstructorDecl *Constructor); |
5078 | |
5079 | /// Declare the implicit copy constructor for the given class. |
5080 | /// |
5081 | /// \param ClassDecl The class declaration into which the implicit |
5082 | /// copy constructor will be added. |
5083 | /// |
5084 | /// \returns The implicitly-declared copy constructor. |
5085 | CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); |
5086 | |
5087 | /// DefineImplicitCopyConstructor - Checks for feasibility of |
5088 | /// defining this constructor as the copy constructor. |
5089 | void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, |
5090 | CXXConstructorDecl *Constructor); |
5091 | |
5092 | /// Declare the implicit move constructor for the given class. |
5093 | /// |
5094 | /// \param ClassDecl The Class declaration into which the implicit |
5095 | /// move constructor will be added. |
5096 | /// |
5097 | /// \returns The implicitly-declared move constructor, or NULL if it wasn't |
5098 | /// declared. |
5099 | CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); |
5100 | |
5101 | /// DefineImplicitMoveConstructor - Checks for feasibility of |
5102 | /// defining this constructor as the move constructor. |
5103 | void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, |
5104 | CXXConstructorDecl *Constructor); |
5105 | |
5106 | /// Declare the implicit copy assignment operator for the given class. |
5107 | /// |
5108 | /// \param ClassDecl The class declaration into which the implicit |
5109 | /// copy assignment operator will be added. |
5110 | /// |
5111 | /// \returns The implicitly-declared copy assignment operator. |
5112 | CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); |
5113 | |
5114 | /// Defines an implicitly-declared copy assignment operator. |
5115 | void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, |
5116 | CXXMethodDecl *MethodDecl); |
5117 | |
5118 | /// Declare the implicit move assignment operator for the given class. |
5119 | /// |
5120 | /// \param ClassDecl The Class declaration into which the implicit |
5121 | /// move assignment operator will be added. |
5122 | /// |
5123 | /// \returns The implicitly-declared move assignment operator, or NULL if it |
5124 | /// wasn't declared. |
5125 | CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); |
5126 | |
5127 | /// Defines an implicitly-declared move assignment operator. |
5128 | void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, |
5129 | CXXMethodDecl *MethodDecl); |
5130 | |
5131 | /// Force the declaration of any implicitly-declared members of this |
5132 | /// class. |
5133 | void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); |
5134 | |
5135 | /// Check a completed declaration of an implicit special member. |
5136 | void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); |
5137 | |
5138 | /// Determine whether the given function is an implicitly-deleted |
5139 | /// special member function. |
5140 | bool isImplicitlyDeleted(FunctionDecl *FD); |
5141 | |
5142 | /// Check whether 'this' shows up in the type of a static member |
5143 | /// function after the (naturally empty) cv-qualifier-seq would be. |
5144 | /// |
5145 | /// \returns true if an error occurred. |
5146 | bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); |
5147 | |
5148 | /// Whether this' shows up in the exception specification of a static |
5149 | /// member function. |
5150 | bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); |
5151 | |
5152 | /// Check whether 'this' shows up in the attributes of the given |
5153 | /// static member function. |
5154 | /// |
5155 | /// \returns true if an error occurred. |
5156 | bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); |
5157 | |
5158 | /// MaybeBindToTemporary - If the passed in expression has a record type with |
5159 | /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise |
5160 | /// it simply returns the passed in expression. |
5161 | ExprResult MaybeBindToTemporary(Expr *E); |
5162 | |
5163 | bool CompleteConstructorCall(CXXConstructorDecl *Constructor, |
5164 | MultiExprArg ArgsPtr, |
5165 | SourceLocation Loc, |
5166 | SmallVectorImpl<Expr*> &ConvertedArgs, |
5167 | bool AllowExplicit = false, |
5168 | bool IsListInitialization = false); |
5169 | |
5170 | ParsedType getInheritingConstructorName(CXXScopeSpec &SS, |
5171 | SourceLocation NameLoc, |
5172 | IdentifierInfo &Name); |
5173 | |
5174 | ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, |
5175 | Scope *S, CXXScopeSpec &SS, |
5176 | bool EnteringContext); |
5177 | ParsedType getDestructorName(SourceLocation TildeLoc, |
5178 | IdentifierInfo &II, SourceLocation NameLoc, |
5179 | Scope *S, CXXScopeSpec &SS, |
5180 | ParsedType ObjectType, |
5181 | bool EnteringContext); |
5182 | |
5183 | ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, |
5184 | ParsedType ObjectType); |
5185 | |
5186 | // Checks that reinterpret casts don't have undefined behavior. |
5187 | void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, |
5188 | bool IsDereference, SourceRange Range); |
5189 | |
5190 | /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. |
5191 | ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, |
5192 | tok::TokenKind Kind, |
5193 | SourceLocation LAngleBracketLoc, |
5194 | Declarator &D, |
5195 | SourceLocation RAngleBracketLoc, |
5196 | SourceLocation LParenLoc, |
5197 | Expr *E, |
5198 | SourceLocation RParenLoc); |
5199 | |
5200 | ExprResult BuildCXXNamedCast(SourceLocation OpLoc, |
5201 | tok::TokenKind Kind, |
5202 | TypeSourceInfo *Ty, |
5203 | Expr *E, |
5204 | SourceRange AngleBrackets, |
5205 | SourceRange Parens); |
5206 | |
5207 | ExprResult BuildCXXTypeId(QualType TypeInfoType, |
5208 | SourceLocation TypeidLoc, |
5209 | TypeSourceInfo *Operand, |
5210 | SourceLocation RParenLoc); |
5211 | ExprResult BuildCXXTypeId(QualType TypeInfoType, |
5212 | SourceLocation TypeidLoc, |
5213 | Expr *Operand, |
5214 | SourceLocation RParenLoc); |
5215 | |
5216 | /// ActOnCXXTypeid - Parse typeid( something ). |
5217 | ExprResult ActOnCXXTypeid(SourceLocation OpLoc, |
5218 | SourceLocation LParenLoc, bool isType, |
5219 | void *TyOrExpr, |
5220 | SourceLocation RParenLoc); |
5221 | |
5222 | ExprResult BuildCXXUuidof(QualType TypeInfoType, |
5223 | SourceLocation TypeidLoc, |
5224 | TypeSourceInfo *Operand, |
5225 | SourceLocation RParenLoc); |
5226 | ExprResult BuildCXXUuidof(QualType TypeInfoType, |
5227 | SourceLocation TypeidLoc, |
5228 | Expr *Operand, |
5229 | SourceLocation RParenLoc); |
5230 | |
5231 | /// ActOnCXXUuidof - Parse __uuidof( something ). |
5232 | ExprResult ActOnCXXUuidof(SourceLocation OpLoc, |
5233 | SourceLocation LParenLoc, bool isType, |
5234 | void *TyOrExpr, |
5235 | SourceLocation RParenLoc); |
5236 | |
5237 | /// Handle a C++1z fold-expression: ( expr op ... op expr ). |
5238 | ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, |
5239 | tok::TokenKind Operator, |
5240 | SourceLocation EllipsisLoc, Expr *RHS, |
5241 | SourceLocation RParenLoc); |
5242 | ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, |
5243 | BinaryOperatorKind Operator, |
5244 | SourceLocation EllipsisLoc, Expr *RHS, |
5245 | SourceLocation RParenLoc, |
5246 | Optional<unsigned> NumExpansions); |
5247 | ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, |
5248 | BinaryOperatorKind Operator); |
5249 | |
5250 | //// ActOnCXXThis - Parse 'this' pointer. |
5251 | ExprResult ActOnCXXThis(SourceLocation loc); |
5252 | |
5253 | /// Build a CXXThisExpr and mark it referenced in the current context. |
5254 | Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); |
5255 | void MarkThisReferenced(CXXThisExpr *This); |
5256 | |
5257 | /// Try to retrieve the type of the 'this' pointer. |
5258 | /// |
5259 | /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. |
5260 | QualType getCurrentThisType(); |
5261 | |
5262 | /// When non-NULL, the C++ 'this' expression is allowed despite the |
5263 | /// current context not being a non-static member function. In such cases, |
5264 | /// this provides the type used for 'this'. |
5265 | QualType CXXThisTypeOverride; |
5266 | |
5267 | /// RAII object used to temporarily allow the C++ 'this' expression |
5268 | /// to be used, with the given qualifiers on the current class type. |
5269 | class CXXThisScopeRAII { |
5270 | Sema &S; |
5271 | QualType OldCXXThisTypeOverride; |
5272 | bool Enabled; |
5273 | |
5274 | public: |
5275 | /// Introduce a new scope where 'this' may be allowed (when enabled), |
5276 | /// using the given declaration (which is either a class template or a |
5277 | /// class) along with the given qualifiers. |
5278 | /// along with the qualifiers placed on '*this'. |
5279 | CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, |
5280 | bool Enabled = true); |
5281 | |
5282 | ~CXXThisScopeRAII(); |
5283 | }; |
5284 | |
5285 | /// Make sure the value of 'this' is actually available in the current |
5286 | /// context, if it is a potentially evaluated context. |
5287 | /// |
5288 | /// \param Loc The location at which the capture of 'this' occurs. |
5289 | /// |
5290 | /// \param Explicit Whether 'this' is explicitly captured in a lambda |
5291 | /// capture list. |
5292 | /// |
5293 | /// \param FunctionScopeIndexToStopAt If non-null, it points to the index |
5294 | /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. |
5295 | /// This is useful when enclosing lambdas must speculatively capture |
5296 | /// 'this' that may or may not be used in certain specializations of |
5297 | /// a nested generic lambda (depending on whether the name resolves to |
5298 | /// a non-static member function or a static function). |
5299 | /// \return returns 'true' if failed, 'false' if success. |
5300 | bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, |
5301 | bool BuildAndDiagnose = true, |
5302 | const unsigned *const FunctionScopeIndexToStopAt = nullptr, |
5303 | bool ByCopy = false); |
5304 | |
5305 | /// Determine whether the given type is the type of *this that is used |
5306 | /// outside of the body of a member function for a type that is currently |
5307 | /// being defined. |
5308 | bool isThisOutsideMemberFunctionBody(QualType BaseType); |
5309 | |
5310 | /// ActOnCXXBoolLiteral - Parse {true,false} literals. |
5311 | ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); |
5312 | |
5313 | |
5314 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. |
5315 | ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); |
5316 | |
5317 | ExprResult |
5318 | ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, |
5319 | SourceLocation AtLoc, SourceLocation RParen); |
5320 | |
5321 | /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. |
5322 | ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); |
5323 | |
5324 | //// ActOnCXXThrow - Parse throw expressions. |
5325 | ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); |
5326 | ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, |
5327 | bool IsThrownVarInScope); |
5328 | bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); |
5329 | |
5330 | /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. |
5331 | /// Can be interpreted either as function-style casting ("int(x)") |
5332 | /// or class type construction ("ClassType(x,y,z)") |
5333 | /// or creation of a value-initialized type ("int()"). |
5334 | ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, |
5335 | SourceLocation LParenOrBraceLoc, |
5336 | MultiExprArg Exprs, |
5337 | SourceLocation RParenOrBraceLoc, |
5338 | bool ListInitialization); |
5339 | |
5340 | ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, |
5341 | SourceLocation LParenLoc, |
5342 | MultiExprArg Exprs, |
5343 | SourceLocation RParenLoc, |
5344 | bool ListInitialization); |
5345 | |
5346 | /// ActOnCXXNew - Parsed a C++ 'new' expression. |
5347 | ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, |
5348 | SourceLocation PlacementLParen, |
5349 | MultiExprArg PlacementArgs, |
5350 | SourceLocation PlacementRParen, |
5351 | SourceRange TypeIdParens, Declarator &D, |
5352 | Expr *Initializer); |
5353 | ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, |
5354 | SourceLocation PlacementLParen, |
5355 | MultiExprArg PlacementArgs, |
5356 | SourceLocation PlacementRParen, |
5357 | SourceRange TypeIdParens, |
5358 | QualType AllocType, |
5359 | TypeSourceInfo *AllocTypeInfo, |
5360 | Optional<Expr *> ArraySize, |
5361 | SourceRange DirectInitRange, |
5362 | Expr *Initializer); |
5363 | |
5364 | /// Determine whether \p FD is an aligned allocation or deallocation |
5365 | /// function that is unavailable. |
5366 | bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; |
5367 | |
5368 | /// Produce diagnostics if \p FD is an aligned allocation or deallocation |
5369 | /// function that is unavailable. |
5370 | void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, |
5371 | SourceLocation Loc); |
5372 | |
5373 | bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, |
5374 | SourceRange R); |
5375 | |
5376 | /// The scope in which to find allocation functions. |
5377 | enum AllocationFunctionScope { |
5378 | /// Only look for allocation functions in the global scope. |
5379 | AFS_Global, |
5380 | /// Only look for allocation functions in the scope of the |
5381 | /// allocated class. |
5382 | AFS_Class, |
5383 | /// Look for allocation functions in both the global scope |
5384 | /// and in the scope of the allocated class. |
5385 | AFS_Both |
5386 | }; |
5387 | |
5388 | /// Finds the overloads of operator new and delete that are appropriate |
5389 | /// for the allocation. |
5390 | bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, |
5391 | AllocationFunctionScope NewScope, |
5392 | AllocationFunctionScope DeleteScope, |
5393 | QualType AllocType, bool IsArray, |
5394 | bool &PassAlignment, MultiExprArg PlaceArgs, |
5395 | FunctionDecl *&OperatorNew, |
5396 | FunctionDecl *&OperatorDelete, |
5397 | bool Diagnose = true); |
5398 | void DeclareGlobalNewDelete(); |
5399 | void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, |
5400 | ArrayRef<QualType> Params); |
5401 | |
5402 | bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, |
5403 | DeclarationName Name, FunctionDecl* &Operator, |
5404 | bool Diagnose = true); |
5405 | FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, |
5406 | bool CanProvideSize, |
5407 | bool Overaligned, |
5408 | DeclarationName Name); |
5409 | FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, |
5410 | CXXRecordDecl *RD); |
5411 | |
5412 | /// ActOnCXXDelete - Parsed a C++ 'delete' expression |
5413 | ExprResult ActOnCXXDelete(SourceLocation StartLoc, |
5414 | bool UseGlobal, bool ArrayForm, |
5415 | Expr *Operand); |
5416 | void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, |
5417 | bool IsDelete, bool CallCanBeVirtual, |
5418 | bool WarnOnNonAbstractTypes, |
5419 | SourceLocation DtorLoc); |
5420 | |
5421 | ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, |
5422 | Expr *Operand, SourceLocation RParen); |
5423 | ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, |
5424 | SourceLocation RParen); |
5425 | |
5426 | /// Parsed one of the type trait support pseudo-functions. |
5427 | ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, |
5428 | ArrayRef<ParsedType> Args, |
5429 | SourceLocation RParenLoc); |
5430 | ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, |
5431 | ArrayRef<TypeSourceInfo *> Args, |
5432 | SourceLocation RParenLoc); |
5433 | |
5434 | /// ActOnArrayTypeTrait - Parsed one of the binary type trait support |
5435 | /// pseudo-functions. |
5436 | ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, |
5437 | SourceLocation KWLoc, |
5438 | ParsedType LhsTy, |
5439 | Expr *DimExpr, |
5440 | SourceLocation RParen); |
5441 | |
5442 | ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, |
5443 | SourceLocation KWLoc, |
5444 | TypeSourceInfo *TSInfo, |
5445 | Expr *DimExpr, |
5446 | SourceLocation RParen); |
5447 | |
5448 | /// ActOnExpressionTrait - Parsed one of the unary type trait support |
5449 | /// pseudo-functions. |
5450 | ExprResult ActOnExpressionTrait(ExpressionTrait OET, |
5451 | SourceLocation KWLoc, |
5452 | Expr *Queried, |
5453 | SourceLocation RParen); |
5454 | |
5455 | ExprResult BuildExpressionTrait(ExpressionTrait OET, |
5456 | SourceLocation KWLoc, |
5457 | Expr *Queried, |
5458 | SourceLocation RParen); |
5459 | |
5460 | ExprResult ActOnStartCXXMemberReference(Scope *S, |
5461 | Expr *Base, |
5462 | SourceLocation OpLoc, |
5463 | tok::TokenKind OpKind, |
5464 | ParsedType &ObjectType, |
5465 | bool &MayBePseudoDestructor); |
5466 | |
5467 | ExprResult BuildPseudoDestructorExpr(Expr *Base, |
5468 | SourceLocation OpLoc, |
5469 | tok::TokenKind OpKind, |
5470 | const CXXScopeSpec &SS, |
5471 | TypeSourceInfo *ScopeType, |
5472 | SourceLocation CCLoc, |
5473 | SourceLocation TildeLoc, |
5474 | PseudoDestructorTypeStorage DestroyedType); |
5475 | |
5476 | ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
5477 | SourceLocation OpLoc, |
5478 | tok::TokenKind OpKind, |
5479 | CXXScopeSpec &SS, |
5480 | UnqualifiedId &FirstTypeName, |
5481 | SourceLocation CCLoc, |
5482 | SourceLocation TildeLoc, |
5483 | UnqualifiedId &SecondTypeName); |
5484 | |
5485 | ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
5486 | SourceLocation OpLoc, |
5487 | tok::TokenKind OpKind, |
5488 | SourceLocation TildeLoc, |
5489 | const DeclSpec& DS); |
5490 | |
5491 | /// MaybeCreateExprWithCleanups - If the current full-expression |
5492 | /// requires any cleanups, surround it with a ExprWithCleanups node. |
5493 | /// Otherwise, just returns the passed-in expression. |
5494 | Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); |
5495 | Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); |
5496 | ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); |
5497 | |
5498 | MaterializeTemporaryExpr * |
5499 | CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, |
5500 | bool BoundToLvalueReference); |
5501 | |
5502 | ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { |
5503 | return ActOnFinishFullExpr( |
5504 | Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); |
5505 | } |
5506 | ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, |
5507 | bool DiscardedValue, bool IsConstexpr = false); |
5508 | StmtResult ActOnFinishFullStmt(Stmt *Stmt); |
5509 | |
5510 | // Marks SS invalid if it represents an incomplete type. |
5511 | bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); |
5512 | |
5513 | DeclContext *computeDeclContext(QualType T); |
5514 | DeclContext *computeDeclContext(const CXXScopeSpec &SS, |
5515 | bool EnteringContext = false); |
5516 | bool isDependentScopeSpecifier(const CXXScopeSpec &SS); |
5517 | CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); |
5518 | |
5519 | /// The parser has parsed a global nested-name-specifier '::'. |
5520 | /// |
5521 | /// \param CCLoc The location of the '::'. |
5522 | /// |
5523 | /// \param SS The nested-name-specifier, which will be updated in-place |
5524 | /// to reflect the parsed nested-name-specifier. |
5525 | /// |
5526 | /// \returns true if an error occurred, false otherwise. |
5527 | bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); |
5528 | |
5529 | /// The parser has parsed a '__super' nested-name-specifier. |
5530 | /// |
5531 | /// \param SuperLoc The location of the '__super' keyword. |
5532 | /// |
5533 | /// \param ColonColonLoc The location of the '::'. |
5534 | /// |
5535 | /// \param SS The nested-name-specifier, which will be updated in-place |
5536 | /// to reflect the parsed nested-name-specifier. |
5537 | /// |
5538 | /// \returns true if an error occurred, false otherwise. |
5539 | bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, |
5540 | SourceLocation ColonColonLoc, CXXScopeSpec &SS); |
5541 | |
5542 | bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, |
5543 | bool *CanCorrect = nullptr); |
5544 | NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); |
5545 | |
5546 | /// Keeps information about an identifier in a nested-name-spec. |
5547 | /// |
5548 | struct NestedNameSpecInfo { |
5549 | /// The type of the object, if we're parsing nested-name-specifier in |
5550 | /// a member access expression. |
5551 | ParsedType ObjectType; |
5552 | |
5553 | /// The identifier preceding the '::'. |
5554 | IdentifierInfo *Identifier; |
5555 | |
5556 | /// The location of the identifier. |
5557 | SourceLocation IdentifierLoc; |
5558 | |
5559 | /// The location of the '::'. |
5560 | SourceLocation CCLoc; |
5561 | |
5562 | /// Creates info object for the most typical case. |
5563 | NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, |
5564 | SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) |
5565 | : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), |
5566 | CCLoc(ColonColonLoc) { |
5567 | } |
5568 | |
5569 | NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, |
5570 | SourceLocation ColonColonLoc, QualType ObjectType) |
5571 | : ObjectType(ParsedType::make(ObjectType)), Identifier(II), |
5572 | IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { |
5573 | } |
5574 | }; |
5575 | |
5576 | bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, |
5577 | NestedNameSpecInfo &IdInfo); |
5578 | |
5579 | bool BuildCXXNestedNameSpecifier(Scope *S, |
5580 | NestedNameSpecInfo &IdInfo, |
5581 | bool EnteringContext, |
5582 | CXXScopeSpec &SS, |
5583 | NamedDecl *ScopeLookupResult, |
5584 | bool ErrorRecoveryLookup, |
5585 | bool *IsCorrectedToColon = nullptr, |
5586 | bool OnlyNamespace = false); |
5587 | |
5588 | /// The parser has parsed a nested-name-specifier 'identifier::'. |
5589 | /// |
5590 | /// \param S The scope in which this nested-name-specifier occurs. |
5591 | /// |
5592 | /// \param IdInfo Parser information about an identifier in the |
5593 | /// nested-name-spec. |
5594 | /// |
5595 | /// \param EnteringContext Whether we're entering the context nominated by |
5596 | /// this nested-name-specifier. |
5597 | /// |
5598 | /// \param SS The nested-name-specifier, which is both an input |
5599 | /// parameter (the nested-name-specifier before this type) and an |
5600 | /// output parameter (containing the full nested-name-specifier, |
5601 | /// including this new type). |
5602 | /// |
5603 | /// \param ErrorRecoveryLookup If true, then this method is called to improve |
5604 | /// error recovery. In this case do not emit error message. |
5605 | /// |
5606 | /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' |
5607 | /// are allowed. The bool value pointed by this parameter is set to 'true' |
5608 | /// if the identifier is treated as if it was followed by ':', not '::'. |
5609 | /// |
5610 | /// \param OnlyNamespace If true, only considers namespaces in lookup. |
5611 | /// |
5612 | /// \returns true if an error occurred, false otherwise. |
5613 | bool ActOnCXXNestedNameSpecifier(Scope *S, |
5614 | NestedNameSpecInfo &IdInfo, |
5615 | bool EnteringContext, |
5616 | CXXScopeSpec &SS, |
5617 | bool ErrorRecoveryLookup = false, |
5618 | bool *IsCorrectedToColon = nullptr, |
5619 | bool OnlyNamespace = false); |
5620 | |
5621 | ExprResult ActOnDecltypeExpression(Expr *E); |
5622 | |
5623 | bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, |
5624 | const DeclSpec &DS, |
5625 | SourceLocation ColonColonLoc); |
5626 | |
5627 | bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, |
5628 | NestedNameSpecInfo &IdInfo, |
5629 | bool EnteringContext); |
5630 | |
5631 | /// The parser has parsed a nested-name-specifier |
5632 | /// 'template[opt] template-name < template-args >::'. |
5633 | /// |
5634 | /// \param S The scope in which this nested-name-specifier occurs. |
5635 | /// |
5636 | /// \param SS The nested-name-specifier, which is both an input |
5637 | /// parameter (the nested-name-specifier before this type) and an |
5638 | /// output parameter (containing the full nested-name-specifier, |
5639 | /// including this new type). |
5640 | /// |
5641 | /// \param TemplateKWLoc the location of the 'template' keyword, if any. |
5642 | /// \param TemplateName the template name. |
5643 | /// \param TemplateNameLoc The location of the template name. |
5644 | /// \param LAngleLoc The location of the opening angle bracket ('<'). |
5645 | /// \param TemplateArgs The template arguments. |
5646 | /// \param RAngleLoc The location of the closing angle bracket ('>'). |
5647 | /// \param CCLoc The location of the '::'. |
5648 | /// |
5649 | /// \param EnteringContext Whether we're entering the context of the |
5650 | /// nested-name-specifier. |
5651 | /// |
5652 | /// |
5653 | /// \returns true if an error occurred, false otherwise. |
5654 | bool ActOnCXXNestedNameSpecifier(Scope *S, |
5655 | CXXScopeSpec &SS, |
5656 | SourceLocation TemplateKWLoc, |
5657 | TemplateTy TemplateName, |
5658 | SourceLocation TemplateNameLoc, |
5659 | SourceLocation LAngleLoc, |
5660 | ASTTemplateArgsPtr TemplateArgs, |
5661 | SourceLocation RAngleLoc, |
5662 | SourceLocation CCLoc, |
5663 | bool EnteringContext); |
5664 | |
5665 | /// Given a C++ nested-name-specifier, produce an annotation value |
5666 | /// that the parser can use later to reconstruct the given |
5667 | /// nested-name-specifier. |
5668 | /// |
5669 | /// \param SS A nested-name-specifier. |
5670 | /// |
5671 | /// \returns A pointer containing all of the information in the |
5672 | /// nested-name-specifier \p SS. |
5673 | void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); |
5674 | |
5675 | /// Given an annotation pointer for a nested-name-specifier, restore |
5676 | /// the nested-name-specifier structure. |
5677 | /// |
5678 | /// \param Annotation The annotation pointer, produced by |
5679 | /// \c SaveNestedNameSpecifierAnnotation(). |
5680 | /// |
5681 | /// \param AnnotationRange The source range corresponding to the annotation. |
5682 | /// |
5683 | /// \param SS The nested-name-specifier that will be updated with the contents |
5684 | /// of the annotation pointer. |
5685 | void RestoreNestedNameSpecifierAnnotation(void *Annotation, |
5686 | SourceRange AnnotationRange, |
5687 | CXXScopeSpec &SS); |
5688 | |
5689 | bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); |
5690 | |
5691 | /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global |
5692 | /// scope or nested-name-specifier) is parsed, part of a declarator-id. |
5693 | /// After this method is called, according to [C++ 3.4.3p3], names should be |
5694 | /// looked up in the declarator-id's scope, until the declarator is parsed and |
5695 | /// ActOnCXXExitDeclaratorScope is called. |
5696 | /// The 'SS' should be a non-empty valid CXXScopeSpec. |
5697 | bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); |
5698 | |
5699 | /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously |
5700 | /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same |
5701 | /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. |
5702 | /// Used to indicate that names should revert to being looked up in the |
5703 | /// defining scope. |
5704 | void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); |
5705 | |
5706 | /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an |
5707 | /// initializer for the declaration 'Dcl'. |
5708 | /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a |
5709 | /// static data member of class X, names should be looked up in the scope of |
5710 | /// class X. |
5711 | void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); |
5712 | |
5713 | /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an |
5714 | /// initializer for the declaration 'Dcl'. |
5715 | void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); |
5716 | |
5717 | /// Create a new lambda closure type. |
5718 | CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, |
5719 | TypeSourceInfo *Info, |
5720 | bool KnownDependent, |
5721 | LambdaCaptureDefault CaptureDefault); |
5722 | |
5723 | /// Start the definition of a lambda expression. |
5724 | CXXMethodDecl * |
5725 | startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, |
5726 | TypeSourceInfo *MethodType, SourceLocation EndLoc, |
5727 | ArrayRef<ParmVarDecl *> Params, |
5728 | bool IsConstexprSpecified, |
5729 | Optional<std::pair<unsigned, Decl *>> Mangling = None); |
5730 | |
5731 | /// Endow the lambda scope info with the relevant properties. |
5732 | void buildLambdaScope(sema::LambdaScopeInfo *LSI, |
5733 | CXXMethodDecl *CallOperator, |
5734 | SourceRange IntroducerRange, |
5735 | LambdaCaptureDefault CaptureDefault, |
5736 | SourceLocation CaptureDefaultLoc, |
5737 | bool ExplicitParams, |
5738 | bool ExplicitResultType, |
5739 | bool Mutable); |
5740 | |
5741 | /// Perform initialization analysis of the init-capture and perform |
5742 | /// any implicit conversions such as an lvalue-to-rvalue conversion if |
5743 | /// not being used to initialize a reference. |
5744 | ParsedType actOnLambdaInitCaptureInitialization( |
5745 | SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, |
5746 | IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { |
5747 | return ParsedType::make(buildLambdaInitCaptureInitialization( |
5748 | Loc, ByRef, EllipsisLoc, None, Id, |
5749 | InitKind != LambdaCaptureInitKind::CopyInit, Init)); |
5750 | } |
5751 | QualType buildLambdaInitCaptureInitialization( |
5752 | SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, |
5753 | Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, |
5754 | Expr *&Init); |
5755 | |
5756 | /// Create a dummy variable within the declcontext of the lambda's |
5757 | /// call operator, for name lookup purposes for a lambda init capture. |
5758 | /// |
5759 | /// CodeGen handles emission of lambda captures, ignoring these dummy |
5760 | /// variables appropriately. |
5761 | VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, |
5762 | QualType InitCaptureType, |
5763 | SourceLocation EllipsisLoc, |
5764 | IdentifierInfo *Id, |
5765 | unsigned InitStyle, Expr *Init); |
5766 | |
5767 | /// Add an init-capture to a lambda scope. |
5768 | void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); |
5769 | |
5770 | /// Note that we have finished the explicit captures for the |
5771 | /// given lambda. |
5772 | void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); |
5773 | |
5774 | /// \brief This is called after parsing the explicit template parameter list |
5775 | /// on a lambda (if it exists) in C++2a. |
5776 | void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, |
5777 | ArrayRef<NamedDecl *> TParams, |
5778 | SourceLocation RAngleLoc); |
5779 | |
5780 | /// Introduce the lambda parameters into scope. |
5781 | void addLambdaParameters( |
5782 | ArrayRef<LambdaIntroducer::LambdaCapture> Captures, |
5783 | CXXMethodDecl *CallOperator, Scope *CurScope); |
5784 | |
5785 | /// Deduce a block or lambda's return type based on the return |
5786 | /// statements present in the body. |
5787 | void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); |
5788 | |
5789 | /// ActOnStartOfLambdaDefinition - This is called just before we start |
5790 | /// parsing the body of a lambda; it analyzes the explicit captures and |
5791 | /// arguments, and sets up various data-structures for the body of the |
5792 | /// lambda. |
5793 | void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, |
5794 | Declarator &ParamInfo, Scope *CurScope); |
5795 | |
5796 | /// ActOnLambdaError - If there is an error parsing a lambda, this callback |
5797 | /// is invoked to pop the information about the lambda. |
5798 | void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, |
5799 | bool IsInstantiation = false); |
5800 | |
5801 | /// ActOnLambdaExpr - This is called when the body of a lambda expression |
5802 | /// was successfully completed. |
5803 | ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, |
5804 | Scope *CurScope); |
5805 | |
5806 | /// Does copying/destroying the captured variable have side effects? |
5807 | bool CaptureHasSideEffects(const sema::Capture &From); |
5808 | |
5809 | /// Diagnose if an explicit lambda capture is unused. Returns true if a |
5810 | /// diagnostic is emitted. |
5811 | bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, |
5812 | const sema::Capture &From); |
5813 | |
5814 | /// Build a FieldDecl suitable to hold the given capture. |
5815 | FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); |
5816 | |
5817 | /// Initialize the given capture with a suitable expression. |
5818 | ExprResult BuildCaptureInit(const sema::Capture &Capture, |
5819 | SourceLocation ImplicitCaptureLoc, |
5820 | bool IsOpenMPMapping = false); |
5821 | |
5822 | /// Complete a lambda-expression having processed and attached the |
5823 | /// lambda body. |
5824 | ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, |
5825 | sema::LambdaScopeInfo *LSI); |
5826 | |
5827 | /// Get the return type to use for a lambda's conversion function(s) to |
5828 | /// function pointer type, given the type of the call operator. |
5829 | QualType |
5830 | getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); |
5831 | |
5832 | /// Define the "body" of the conversion from a lambda object to a |
5833 | /// function pointer. |
5834 | /// |
5835 | /// This routine doesn't actually define a sensible body; rather, it fills |
5836 | /// in the initialization expression needed to copy the lambda object into |
5837 | /// the block, and IR generation actually generates the real body of the |
5838 | /// block pointer conversion. |
5839 | void DefineImplicitLambdaToFunctionPointerConversion( |
5840 | SourceLocation CurrentLoc, CXXConversionDecl *Conv); |
5841 | |
5842 | /// Define the "body" of the conversion from a lambda object to a |
5843 | /// block pointer. |
5844 | /// |
5845 | /// This routine doesn't actually define a sensible body; rather, it fills |
5846 | /// in the initialization expression needed to copy the lambda object into |
5847 | /// the block, and IR generation actually generates the real body of the |
5848 | /// block pointer conversion. |
5849 | void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, |
5850 | CXXConversionDecl *Conv); |
5851 | |
5852 | ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, |
5853 | SourceLocation ConvLocation, |
5854 | CXXConversionDecl *Conv, |
5855 | Expr *Src); |
5856 | |
5857 | // ParseObjCStringLiteral - Parse Objective-C string literals. |
5858 | ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, |
5859 | ArrayRef<Expr *> Strings); |
5860 | |
5861 | ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); |
5862 | |
5863 | /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the |
5864 | /// numeric literal expression. Type of the expression will be "NSNumber *" |
5865 | /// or "id" if NSNumber is unavailable. |
5866 | ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); |
5867 | ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, |
5868 | bool Value); |
5869 | ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); |
5870 | |
5871 | /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the |
5872 | /// '@' prefixed parenthesized expression. The type of the expression will |
5873 | /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type |
5874 | /// of ValueType, which is allowed to be a built-in numeric type, "char *", |
5875 | /// "const char *" or C structure with attribute 'objc_boxable'. |
5876 | ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); |
5877 | |
5878 | ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, |
5879 | Expr *IndexExpr, |
5880 | ObjCMethodDecl *getterMethod, |
5881 | ObjCMethodDecl *setterMethod); |
5882 | |
5883 | ExprResult BuildObjCDictionaryLiteral(SourceRange SR, |
5884 | MutableArrayRef<ObjCDictionaryElement> Elements); |
5885 | |
5886 | ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, |
5887 | TypeSourceInfo *EncodedTypeInfo, |
5888 | SourceLocation RParenLoc); |
5889 | ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, |
5890 | CXXConversionDecl *Method, |
5891 | bool HadMultipleCandidates); |
5892 | |
5893 | ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, |
5894 | SourceLocation EncodeLoc, |
5895 | SourceLocation LParenLoc, |
5896 | ParsedType Ty, |
5897 | SourceLocation RParenLoc); |
5898 | |
5899 | /// ParseObjCSelectorExpression - Build selector expression for \@selector |
5900 | ExprResult ParseObjCSelectorExpression(Selector Sel, |
5901 | SourceLocation AtLoc, |
5902 | SourceLocation SelLoc, |
5903 | SourceLocation LParenLoc, |
5904 | SourceLocation RParenLoc, |
5905 | bool WarnMultipleSelectors); |
5906 | |
5907 | /// ParseObjCProtocolExpression - Build protocol expression for \@protocol |
5908 | ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, |
5909 | SourceLocation AtLoc, |
5910 | SourceLocation ProtoLoc, |
5911 | SourceLocation LParenLoc, |
5912 | SourceLocation ProtoIdLoc, |
5913 | SourceLocation RParenLoc); |
5914 | |
5915 | //===--------------------------------------------------------------------===// |
5916 | // C++ Declarations |
5917 | // |
5918 | Decl *ActOnStartLinkageSpecification(Scope *S, |
5919 | SourceLocation ExternLoc, |
5920 | Expr *LangStr, |
5921 | SourceLocation LBraceLoc); |
5922 | Decl *ActOnFinishLinkageSpecification(Scope *S, |
5923 | Decl *LinkageSpec, |
5924 | SourceLocation RBraceLoc); |
5925 | |
5926 | |
5927 | //===--------------------------------------------------------------------===// |
5928 | // C++ Classes |
5929 | // |
5930 | CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); |
5931 | bool isCurrentClassName(const IdentifierInfo &II, Scope *S, |
5932 | const CXXScopeSpec *SS = nullptr); |
5933 | bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); |
5934 | |
5935 | bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, |
5936 | SourceLocation ColonLoc, |
5937 | const ParsedAttributesView &Attrs); |
5938 | |
5939 | NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, |
5940 | Declarator &D, |
5941 | MultiTemplateParamsArg TemplateParameterLists, |
5942 | Expr *BitfieldWidth, const VirtSpecifiers &VS, |
5943 | InClassInitStyle InitStyle); |
5944 | |
5945 | void ActOnStartCXXInClassMemberInitializer(); |
5946 | void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, |
5947 | SourceLocation EqualLoc, |
5948 | Expr *Init); |
5949 | |
5950 | MemInitResult ActOnMemInitializer(Decl *ConstructorD, |
5951 | Scope *S, |
5952 | CXXScopeSpec &SS, |
5953 | IdentifierInfo *MemberOrBase, |
5954 | ParsedType TemplateTypeTy, |
5955 | const DeclSpec &DS, |
5956 | SourceLocation IdLoc, |
5957 | SourceLocation LParenLoc, |
5958 | ArrayRef<Expr *> Args, |
5959 | SourceLocation RParenLoc, |
5960 | SourceLocation EllipsisLoc); |
5961 | |
5962 | MemInitResult ActOnMemInitializer(Decl *ConstructorD, |
5963 | Scope *S, |
5964 | CXXScopeSpec &SS, |
5965 | IdentifierInfo *MemberOrBase, |
5966 | ParsedType TemplateTypeTy, |
5967 | const DeclSpec &DS, |
5968 | SourceLocation IdLoc, |
5969 | Expr *InitList, |
5970 | SourceLocation EllipsisLoc); |
5971 | |
5972 | MemInitResult BuildMemInitializer(Decl *ConstructorD, |
5973 | Scope *S, |
5974 | CXXScopeSpec &SS, |
5975 | IdentifierInfo *MemberOrBase, |
5976 | ParsedType TemplateTypeTy, |
5977 | const DeclSpec &DS, |
5978 | SourceLocation IdLoc, |
5979 | Expr *Init, |
5980 | SourceLocation EllipsisLoc); |
5981 | |
5982 | MemInitResult BuildMemberInitializer(ValueDecl *Member, |
5983 | Expr *Init, |
5984 | SourceLocation IdLoc); |
5985 | |
5986 | MemInitResult BuildBaseInitializer(QualType BaseType, |
5987 | TypeSourceInfo *BaseTInfo, |
5988 | Expr *Init, |
5989 | CXXRecordDecl *ClassDecl, |
5990 | SourceLocation EllipsisLoc); |
5991 | |
5992 | MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, |
5993 | Expr *Init, |
5994 | CXXRecordDecl *ClassDecl); |
5995 | |
5996 | bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, |
5997 | CXXCtorInitializer *Initializer); |
5998 | |
5999 | bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, |
6000 | ArrayRef<CXXCtorInitializer *> Initializers = None); |
6001 | |
6002 | void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); |
6003 | |
6004 | |
6005 | /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, |
6006 | /// mark all the non-trivial destructors of its members and bases as |
6007 | /// referenced. |
6008 | void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, |
6009 | CXXRecordDecl *Record); |
6010 | |
6011 | /// The list of classes whose vtables have been used within |
6012 | /// this translation unit, and the source locations at which the |
6013 | /// first use occurred. |
6014 | typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; |
6015 | |
6016 | /// The list of vtables that are required but have not yet been |
6017 | /// materialized. |
6018 | SmallVector<VTableUse, 16> VTableUses; |
6019 | |
6020 | /// The set of classes whose vtables have been used within |
6021 | /// this translation unit, and a bit that will be true if the vtable is |
6022 | /// required to be emitted (otherwise, it should be emitted only if needed |
6023 | /// by code generation). |
6024 | llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; |
6025 | |
6026 | /// Load any externally-stored vtable uses. |
6027 | void LoadExternalVTableUses(); |
6028 | |
6029 | /// Note that the vtable for the given class was used at the |
6030 | /// given location. |
6031 | void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, |
6032 | bool DefinitionRequired = false); |
6033 | |
6034 | /// Mark the exception specifications of all virtual member functions |
6035 | /// in the given class as needed. |
6036 | void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, |
6037 | const CXXRecordDecl *RD); |
6038 | |
6039 | /// MarkVirtualMembersReferenced - Will mark all members of the given |
6040 | /// CXXRecordDecl referenced. |
6041 | void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, |
6042 | bool ConstexprOnly = false); |
6043 | |
6044 | /// Define all of the vtables that have been used in this |
6045 | /// translation unit and reference any virtual members used by those |
6046 | /// vtables. |
6047 | /// |
6048 | /// \returns true if any work was done, false otherwise. |
6049 | bool DefineUsedVTables(); |
6050 | |
6051 | void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); |
6052 | |
6053 | void ActOnMemInitializers(Decl *ConstructorDecl, |
6054 | SourceLocation ColonLoc, |
6055 | ArrayRef<CXXCtorInitializer*> MemInits, |
6056 | bool AnyErrors); |
6057 | |
6058 | /// Check class-level dllimport/dllexport attribute. The caller must |
6059 | /// ensure that referenceDLLExportedClassMethods is called some point later |
6060 | /// when all outer classes of Class are complete. |
6061 | void checkClassLevelDLLAttribute(CXXRecordDecl *Class); |
6062 | void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); |
6063 | |
6064 | void referenceDLLExportedClassMethods(); |
6065 | |
6066 | void propagateDLLAttrToBaseClassTemplate( |
6067 | CXXRecordDecl *Class, Attr *ClassAttr, |
6068 | ClassTemplateSpecializationDecl *BaseTemplateSpec, |
6069 | SourceLocation BaseLoc); |
6070 | |
6071 | void CheckCompletedCXXClass(CXXRecordDecl *Record); |
6072 | |
6073 | /// Check that the C++ class annoated with "trivial_abi" satisfies all the |
6074 | /// conditions that are needed for the attribute to have an effect. |
6075 | void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); |
6076 | |
6077 | void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, |
6078 | Decl *TagDecl, SourceLocation LBrac, |
6079 | SourceLocation RBrac, |
6080 | const ParsedAttributesView &AttrList); |
6081 | void ActOnFinishCXXMemberDecls(); |
6082 | void ActOnFinishCXXNonNestedClass(Decl *D); |
6083 | |
6084 | void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); |
6085 | unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); |
6086 | void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); |
6087 | void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); |
6088 | void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); |
6089 | void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); |
6090 | void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); |
6091 | void ActOnFinishDelayedMemberInitializers(Decl *Record); |
6092 | void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, |
6093 | CachedTokens &Toks); |
6094 | void UnmarkAsLateParsedTemplate(FunctionDecl *FD); |
6095 | bool IsInsideALocalClassWithinATemplateFunction(); |
6096 | |
6097 | Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, |
6098 | Expr *AssertExpr, |
6099 | Expr *AssertMessageExpr, |
6100 | SourceLocation RParenLoc); |
6101 | Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, |
6102 | Expr *AssertExpr, |
6103 | StringLiteral *AssertMessageExpr, |
6104 | SourceLocation RParenLoc, |
6105 | bool Failed); |
6106 | |
6107 | FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, |
6108 | SourceLocation FriendLoc, |
6109 | TypeSourceInfo *TSInfo); |
6110 | Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, |
6111 | MultiTemplateParamsArg TemplateParams); |
6112 | NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, |
6113 | MultiTemplateParamsArg TemplateParams); |
6114 | |
6115 | QualType CheckConstructorDeclarator(Declarator &D, QualType R, |
6116 | StorageClass& SC); |
6117 | void CheckConstructor(CXXConstructorDecl *Constructor); |
6118 | QualType CheckDestructorDeclarator(Declarator &D, QualType R, |
6119 | StorageClass& SC); |
6120 | bool CheckDestructor(CXXDestructorDecl *Destructor); |
6121 | void CheckConversionDeclarator(Declarator &D, QualType &R, |
6122 | StorageClass& SC); |
6123 | Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); |
6124 | void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, |
6125 | StorageClass &SC); |
6126 | void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); |
6127 | |
6128 | void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); |
6129 | void CheckDelayedMemberExceptionSpecs(); |
6130 | |
6131 | //===--------------------------------------------------------------------===// |
6132 | // C++ Derived Classes |
6133 | // |
6134 | |
6135 | /// ActOnBaseSpecifier - Parsed a base specifier |
6136 | CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, |
6137 | SourceRange SpecifierRange, |
6138 | bool Virtual, AccessSpecifier Access, |
6139 | TypeSourceInfo *TInfo, |
6140 | SourceLocation EllipsisLoc); |
6141 | |
6142 | BaseResult ActOnBaseSpecifier(Decl *classdecl, |
6143 | SourceRange SpecifierRange, |
6144 | ParsedAttributes &Attrs, |
6145 | bool Virtual, AccessSpecifier Access, |
6146 | ParsedType basetype, |
6147 | SourceLocation BaseLoc, |
6148 | SourceLocation EllipsisLoc); |
6149 | |
6150 | bool AttachBaseSpecifiers(CXXRecordDecl *Class, |
6151 | MutableArrayRef<CXXBaseSpecifier *> Bases); |
6152 | void ActOnBaseSpecifiers(Decl *ClassDecl, |
6153 | MutableArrayRef<CXXBaseSpecifier *> Bases); |
6154 | |
6155 | bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); |
6156 | bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, |
6157 | CXXBasePaths &Paths); |
6158 | |
6159 | // FIXME: I don't like this name. |
6160 | void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); |
6161 | |
6162 | bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
6163 | SourceLocation Loc, SourceRange Range, |
6164 | CXXCastPath *BasePath = nullptr, |
6165 | bool IgnoreAccess = false); |
6166 | bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
6167 | unsigned InaccessibleBaseID, |
6168 | unsigned AmbigiousBaseConvID, |
6169 | SourceLocation Loc, SourceRange Range, |
6170 | DeclarationName Name, |
6171 | CXXCastPath *BasePath, |
6172 | bool IgnoreAccess = false); |
6173 | |
6174 | std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); |
6175 | |
6176 | bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, |
6177 | const CXXMethodDecl *Old); |
6178 | |
6179 | /// CheckOverridingFunctionReturnType - Checks whether the return types are |
6180 | /// covariant, according to C++ [class.virtual]p5. |
6181 | bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, |
6182 | const CXXMethodDecl *Old); |
6183 | |
6184 | /// CheckOverridingFunctionExceptionSpec - Checks whether the exception |
6185 | /// spec is a subset of base spec. |
6186 | bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, |
6187 | const CXXMethodDecl *Old); |
6188 | |
6189 | bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); |
6190 | |
6191 | /// CheckOverrideControl - Check C++11 override control semantics. |
6192 | void CheckOverrideControl(NamedDecl *D); |
6193 | |
6194 | /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was |
6195 | /// not used in the declaration of an overriding method. |
6196 | void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); |
6197 | |
6198 | /// CheckForFunctionMarkedFinal - Checks whether a virtual member function |
6199 | /// overrides a virtual member function marked 'final', according to |
6200 | /// C++11 [class.virtual]p4. |
6201 | bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, |
6202 | const CXXMethodDecl *Old); |
6203 | |
6204 | |
6205 | //===--------------------------------------------------------------------===// |
6206 | // C++ Access Control |
6207 | // |
6208 | |
6209 | enum AccessResult { |
6210 | AR_accessible, |
6211 | AR_inaccessible, |
6212 | AR_dependent, |
6213 | AR_delayed |
6214 | }; |
6215 | |
6216 | bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, |
6217 | NamedDecl *PrevMemberDecl, |
6218 | AccessSpecifier LexicalAS); |
6219 | |
6220 | AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, |
6221 | DeclAccessPair FoundDecl); |
6222 | AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, |
6223 | DeclAccessPair FoundDecl); |
6224 | AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, |
6225 | SourceRange PlacementRange, |
6226 | CXXRecordDecl *NamingClass, |
6227 | DeclAccessPair FoundDecl, |
6228 | bool Diagnose = true); |
6229 | AccessResult CheckConstructorAccess(SourceLocation Loc, |
6230 | CXXConstructorDecl *D, |
6231 | DeclAccessPair FoundDecl, |
6232 | const InitializedEntity &Entity, |
6233 | bool IsCopyBindingRefToTemp = false); |
6234 | AccessResult CheckConstructorAccess(SourceLocation Loc, |
6235 | CXXConstructorDecl *D, |
6236 | DeclAccessPair FoundDecl, |
6237 | const InitializedEntity &Entity, |
6238 | const PartialDiagnostic &PDiag); |
6239 | AccessResult CheckDestructorAccess(SourceLocation Loc, |
6240 | CXXDestructorDecl *Dtor, |
6241 | const PartialDiagnostic &PDiag, |
6242 | QualType objectType = QualType()); |
6243 | AccessResult CheckFriendAccess(NamedDecl *D); |
6244 | AccessResult CheckMemberAccess(SourceLocation UseLoc, |
6245 | CXXRecordDecl *NamingClass, |
6246 | DeclAccessPair Found); |
6247 | AccessResult |
6248 | CheckStructuredBindingMemberAccess(SourceLocation UseLoc, |
6249 | CXXRecordDecl *DecomposedClass, |
6250 | DeclAccessPair Field); |
6251 | AccessResult CheckMemberOperatorAccess(SourceLocation Loc, |
6252 | Expr *ObjectExpr, |
6253 | Expr *ArgExpr, |
6254 | DeclAccessPair FoundDecl); |
6255 | AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, |
6256 | DeclAccessPair FoundDecl); |
6257 | AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, |
6258 | QualType Base, QualType Derived, |
6259 | const CXXBasePath &Path, |
6260 | unsigned DiagID, |
6261 | bool ForceCheck = false, |
6262 | bool ForceUnprivileged = false); |
6263 | void CheckLookupAccess(const LookupResult &R); |
6264 | bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, |
6265 | QualType BaseType); |
6266 | bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, |
6267 | AccessSpecifier access, |
6268 | QualType objectType); |
6269 | |
6270 | void HandleDependentAccessCheck(const DependentDiagnostic &DD, |
6271 | const MultiLevelTemplateArgumentList &TemplateArgs); |
6272 | void PerformDependentDiagnostics(const DeclContext *Pattern, |
6273 | const MultiLevelTemplateArgumentList &TemplateArgs); |
6274 | |
6275 | void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); |
6276 | |
6277 | /// When true, access checking violations are treated as SFINAE |
6278 | /// failures rather than hard errors. |
6279 | bool AccessCheckingSFINAE; |
6280 | |
6281 | enum AbstractDiagSelID { |
6282 | AbstractNone = -1, |
6283 | AbstractReturnType, |
6284 | AbstractParamType, |
6285 | AbstractVariableType, |
6286 | AbstractFieldType, |
6287 | AbstractIvarType, |
6288 | AbstractSynthesizedIvarType, |
6289 | AbstractArrayType |
6290 | }; |
6291 | |
6292 | bool isAbstractType(SourceLocation Loc, QualType T); |
6293 | bool RequireNonAbstractType(SourceLocation Loc, QualType T, |
6294 | TypeDiagnoser &Diagnoser); |
6295 | template <typename... Ts> |
6296 | bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, |
6297 | const Ts &...Args) { |
6298 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
6299 | return RequireNonAbstractType(Loc, T, Diagnoser); |
6300 | } |
6301 | |
6302 | void DiagnoseAbstractType(const CXXRecordDecl *RD); |
6303 | |
6304 | //===--------------------------------------------------------------------===// |
6305 | // C++ Overloaded Operators [C++ 13.5] |
6306 | // |
6307 | |
6308 | bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); |
6309 | |
6310 | bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); |
6311 | |
6312 | //===--------------------------------------------------------------------===// |
6313 | // C++ Templates [C++ 14] |
6314 | // |
6315 | void FilterAcceptableTemplateNames(LookupResult &R, |
6316 | bool AllowFunctionTemplates = true, |
6317 | bool AllowDependent = true); |
6318 | bool hasAnyAcceptableTemplateNames(LookupResult &R, |
6319 | bool AllowFunctionTemplates = true, |
6320 | bool AllowDependent = true, |
6321 | bool AllowNonTemplateFunctions = false); |
6322 | /// Try to interpret the lookup result D as a template-name. |
6323 | /// |
6324 | /// \param D A declaration found by name lookup. |
6325 | /// \param AllowFunctionTemplates Whether function templates should be |
6326 | /// considered valid results. |
6327 | /// \param AllowDependent Whether unresolved using declarations (that might |
6328 | /// name templates) should be considered valid results. |
6329 | NamedDecl *getAsTemplateNameDecl(NamedDecl *D, |
6330 | bool AllowFunctionTemplates = true, |
6331 | bool AllowDependent = true); |
6332 | |
6333 | enum class AssumedTemplateKind { |
6334 | /// This is not assumed to be a template name. |
6335 | None, |
6336 | /// This is assumed to be a template name because lookup found nothing. |
6337 | FoundNothing, |
6338 | /// This is assumed to be a template name because lookup found one or more |
6339 | /// functions (but no function templates). |
6340 | FoundFunctions, |
6341 | }; |
6342 | bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, |
6343 | QualType ObjectType, bool EnteringContext, |
6344 | bool &MemberOfUnknownSpecialization, |
6345 | SourceLocation TemplateKWLoc = SourceLocation(), |
6346 | AssumedTemplateKind *ATK = nullptr); |
6347 | |
6348 | TemplateNameKind isTemplateName(Scope *S, |
6349 | CXXScopeSpec &SS, |
6350 | bool hasTemplateKeyword, |
6351 | const UnqualifiedId &Name, |
6352 | ParsedType ObjectType, |
6353 | bool EnteringContext, |
6354 | TemplateTy &Template, |
6355 | bool &MemberOfUnknownSpecialization); |
6356 | |
6357 | /// Try to resolve an undeclared template name as a type template. |
6358 | /// |
6359 | /// Sets II to the identifier corresponding to the template name, and updates |
6360 | /// Name to a corresponding (typo-corrected) type template name and TNK to |
6361 | /// the corresponding kind, if possible. |
6362 | void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, |
6363 | TemplateNameKind &TNK, |
6364 | SourceLocation NameLoc, |
6365 | IdentifierInfo *&II); |
6366 | |
6367 | bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, |
6368 | SourceLocation NameLoc, |
6369 | bool Diagnose = true); |
6370 | |
6371 | /// Determine whether a particular identifier might be the name in a C++1z |
6372 | /// deduction-guide declaration. |
6373 | bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, |
6374 | SourceLocation NameLoc, |
6375 | ParsedTemplateTy *Template = nullptr); |
6376 | |
6377 | bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, |
6378 | SourceLocation IILoc, |
6379 | Scope *S, |
6380 | const CXXScopeSpec *SS, |
6381 | TemplateTy &SuggestedTemplate, |
6382 | TemplateNameKind &SuggestedKind); |
6383 | |
6384 | bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, |
6385 | NamedDecl *Instantiation, |
6386 | bool InstantiatedFromMember, |
6387 | const NamedDecl *Pattern, |
6388 | const NamedDecl *PatternDef, |
6389 | TemplateSpecializationKind TSK, |
6390 | bool Complain = true); |
6391 | |
6392 | void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); |
6393 | TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); |
6394 | |
6395 | NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, |
6396 | SourceLocation EllipsisLoc, |
6397 | SourceLocation KeyLoc, |
6398 | IdentifierInfo *ParamName, |
6399 | SourceLocation ParamNameLoc, |
6400 | unsigned Depth, unsigned Position, |
6401 | SourceLocation EqualLoc, |
6402 | ParsedType DefaultArg); |
6403 | |
6404 | QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, |
6405 | SourceLocation Loc); |
6406 | QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); |
6407 | |
6408 | NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, |
6409 | unsigned Depth, |
6410 | unsigned Position, |
6411 | SourceLocation EqualLoc, |
6412 | Expr *DefaultArg); |
6413 | NamedDecl *ActOnTemplateTemplateParameter(Scope *S, |
6414 | SourceLocation TmpLoc, |
6415 | TemplateParameterList *Params, |
6416 | SourceLocation EllipsisLoc, |
6417 | IdentifierInfo *ParamName, |
6418 | SourceLocation ParamNameLoc, |
6419 | unsigned Depth, |
6420 | unsigned Position, |
6421 | SourceLocation EqualLoc, |
6422 | ParsedTemplateArgument DefaultArg); |
6423 | |
6424 | TemplateParameterList * |
6425 | ActOnTemplateParameterList(unsigned Depth, |
6426 | SourceLocation ExportLoc, |
6427 | SourceLocation TemplateLoc, |
6428 | SourceLocation LAngleLoc, |
6429 | ArrayRef<NamedDecl *> Params, |
6430 | SourceLocation RAngleLoc, |
6431 | Expr *RequiresClause); |
6432 | |
6433 | /// The context in which we are checking a template parameter list. |
6434 | enum TemplateParamListContext { |
6435 | TPC_ClassTemplate, |
6436 | TPC_VarTemplate, |
6437 | TPC_FunctionTemplate, |
6438 | TPC_ClassTemplateMember, |
6439 | TPC_FriendClassTemplate, |
6440 | TPC_FriendFunctionTemplate, |
6441 | TPC_FriendFunctionTemplateDefinition, |
6442 | TPC_TypeAliasTemplate |
6443 | }; |
6444 | |
6445 | bool CheckTemplateParameterList(TemplateParameterList *NewParams, |
6446 | TemplateParameterList *OldParams, |
6447 | TemplateParamListContext TPC, |
6448 | SkipBodyInfo *SkipBody = nullptr); |
6449 | TemplateParameterList *MatchTemplateParametersToScopeSpecifier( |
6450 | SourceLocation DeclStartLoc, SourceLocation DeclLoc, |
6451 | const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, |
6452 | ArrayRef<TemplateParameterList *> ParamLists, |
6453 | bool IsFriend, bool &IsMemberSpecialization, bool &Invalid); |
6454 | |
6455 | DeclResult CheckClassTemplate( |
6456 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
6457 | CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, |
6458 | const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, |
6459 | AccessSpecifier AS, SourceLocation ModulePrivateLoc, |
6460 | SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, |
6461 | TemplateParameterList **OuterTemplateParamLists, |
6462 | SkipBodyInfo *SkipBody = nullptr); |
6463 | |
6464 | TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, |
6465 | QualType NTTPType, |
6466 | SourceLocation Loc); |
6467 | |
6468 | void translateTemplateArguments(const ASTTemplateArgsPtr &In, |
6469 | TemplateArgumentListInfo &Out); |
6470 | |
6471 | ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); |
6472 | |
6473 | void NoteAllFoundTemplates(TemplateName Name); |
6474 | |
6475 | QualType CheckTemplateIdType(TemplateName Template, |
6476 | SourceLocation TemplateLoc, |
6477 | TemplateArgumentListInfo &TemplateArgs); |
6478 | |
6479 | TypeResult |
6480 | ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
6481 | TemplateTy Template, IdentifierInfo *TemplateII, |
6482 | SourceLocation TemplateIILoc, SourceLocation LAngleLoc, |
6483 | ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, |
6484 | bool IsCtorOrDtorName = false, bool IsClassName = false); |
6485 | |
6486 | /// Parsed an elaborated-type-specifier that refers to a template-id, |
6487 | /// such as \c class T::template apply<U>. |
6488 | TypeResult ActOnTagTemplateIdType(TagUseKind TUK, |
6489 | TypeSpecifierType TagSpec, |
6490 | SourceLocation TagLoc, |
6491 | CXXScopeSpec &SS, |
6492 | SourceLocation TemplateKWLoc, |
6493 | TemplateTy TemplateD, |
6494 | SourceLocation TemplateLoc, |
6495 | SourceLocation LAngleLoc, |
6496 | ASTTemplateArgsPtr TemplateArgsIn, |
6497 | SourceLocation RAngleLoc); |
6498 | |
6499 | DeclResult ActOnVarTemplateSpecialization( |
6500 | Scope *S, Declarator &D, TypeSourceInfo *DI, |
6501 | SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, |
6502 | StorageClass SC, bool IsPartialSpecialization); |
6503 | |
6504 | DeclResult CheckVarTemplateId(VarTemplateDecl *Template, |
6505 | SourceLocation TemplateLoc, |
6506 | SourceLocation TemplateNameLoc, |
6507 | const TemplateArgumentListInfo &TemplateArgs); |
6508 | |
6509 | ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, |
6510 | const DeclarationNameInfo &NameInfo, |
6511 | VarTemplateDecl *Template, |
6512 | SourceLocation TemplateLoc, |
6513 | const TemplateArgumentListInfo *TemplateArgs); |
6514 | |
6515 | void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); |
6516 | |
6517 | ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, |
6518 | SourceLocation TemplateKWLoc, |
6519 | LookupResult &R, |
6520 | bool RequiresADL, |
6521 | const TemplateArgumentListInfo *TemplateArgs); |
6522 | |
6523 | ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, |
6524 | SourceLocation TemplateKWLoc, |
6525 | const DeclarationNameInfo &NameInfo, |
6526 | const TemplateArgumentListInfo *TemplateArgs); |
6527 | |
6528 | TemplateNameKind ActOnDependentTemplateName( |
6529 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
6530 | const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, |
6531 | TemplateTy &Template, bool AllowInjectedClassName = false); |
6532 | |
6533 | DeclResult ActOnClassTemplateSpecialization( |
6534 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, |
6535 | SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, |
6536 | const ParsedAttributesView &Attr, |
6537 | MultiTemplateParamsArg TemplateParameterLists, |
6538 | SkipBodyInfo *SkipBody = nullptr); |
6539 | |
6540 | bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, |
6541 | TemplateDecl *PrimaryTemplate, |
6542 | unsigned NumExplicitArgs, |
6543 | ArrayRef<TemplateArgument> Args); |
6544 | void CheckTemplatePartialSpecialization( |
6545 | ClassTemplatePartialSpecializationDecl *Partial); |
6546 | void CheckTemplatePartialSpecialization( |
6547 | VarTemplatePartialSpecializationDecl *Partial); |
6548 | |
6549 | Decl *ActOnTemplateDeclarator(Scope *S, |
6550 | MultiTemplateParamsArg TemplateParameterLists, |
6551 | Declarator &D); |
6552 | |
6553 | bool |
6554 | CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, |
6555 | TemplateSpecializationKind NewTSK, |
6556 | NamedDecl *PrevDecl, |
6557 | TemplateSpecializationKind PrevTSK, |
6558 | SourceLocation PrevPtOfInstantiation, |
6559 | bool &SuppressNew); |
6560 | |
6561 | bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, |
6562 | const TemplateArgumentListInfo &ExplicitTemplateArgs, |
6563 | LookupResult &Previous); |
6564 | |
6565 | bool CheckFunctionTemplateSpecialization( |
6566 | FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, |
6567 | LookupResult &Previous, bool QualifiedFriend = false); |
6568 | bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); |
6569 | void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); |
6570 | |
6571 | DeclResult ActOnExplicitInstantiation( |
6572 | Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, |
6573 | unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, |
6574 | TemplateTy Template, SourceLocation TemplateNameLoc, |
6575 | SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, |
6576 | SourceLocation RAngleLoc, const ParsedAttributesView &Attr); |
6577 | |
6578 | DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, |
6579 | SourceLocation TemplateLoc, |
6580 | unsigned TagSpec, SourceLocation KWLoc, |
6581 | CXXScopeSpec &SS, IdentifierInfo *Name, |
6582 | SourceLocation NameLoc, |
6583 | const ParsedAttributesView &Attr); |
6584 | |
6585 | DeclResult ActOnExplicitInstantiation(Scope *S, |
6586 | SourceLocation ExternLoc, |
6587 | SourceLocation TemplateLoc, |
6588 | Declarator &D); |
6589 | |
6590 | TemplateArgumentLoc |
6591 | SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, |
6592 | SourceLocation TemplateLoc, |
6593 | SourceLocation RAngleLoc, |
6594 | Decl *Param, |
6595 | SmallVectorImpl<TemplateArgument> |
6596 | &Converted, |
6597 | bool &HasDefaultArg); |
6598 | |
6599 | /// Specifies the context in which a particular template |
6600 | /// argument is being checked. |
6601 | enum CheckTemplateArgumentKind { |
6602 | /// The template argument was specified in the code or was |
6603 | /// instantiated with some deduced template arguments. |
6604 | CTAK_Specified, |
6605 | |
6606 | /// The template argument was deduced via template argument |
6607 | /// deduction. |
6608 | CTAK_Deduced, |
6609 | |
6610 | /// The template argument was deduced from an array bound |
6611 | /// via template argument deduction. |
6612 | CTAK_DeducedFromArrayBound |
6613 | }; |
6614 | |
6615 | bool CheckTemplateArgument(NamedDecl *Param, |
6616 | TemplateArgumentLoc &Arg, |
6617 | NamedDecl *Template, |
6618 | SourceLocation TemplateLoc, |
6619 | SourceLocation RAngleLoc, |
6620 | unsigned ArgumentPackIndex, |
6621 | SmallVectorImpl<TemplateArgument> &Converted, |
6622 | CheckTemplateArgumentKind CTAK = CTAK_Specified); |
6623 | |
6624 | /// Check that the given template arguments can be be provided to |
6625 | /// the given template, converting the arguments along the way. |
6626 | /// |
6627 | /// \param Template The template to which the template arguments are being |
6628 | /// provided. |
6629 | /// |
6630 | /// \param TemplateLoc The location of the template name in the source. |
6631 | /// |
6632 | /// \param TemplateArgs The list of template arguments. If the template is |
6633 | /// a template template parameter, this function may extend the set of |
6634 | /// template arguments to also include substituted, defaulted template |
6635 | /// arguments. |
6636 | /// |
6637 | /// \param PartialTemplateArgs True if the list of template arguments is |
6638 | /// intentionally partial, e.g., because we're checking just the initial |
6639 | /// set of template arguments. |
6640 | /// |
6641 | /// \param Converted Will receive the converted, canonicalized template |
6642 | /// arguments. |
6643 | /// |
6644 | /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to |
6645 | /// contain the converted forms of the template arguments as written. |
6646 | /// Otherwise, \p TemplateArgs will not be modified. |
6647 | /// |
6648 | /// \returns true if an error occurred, false otherwise. |
6649 | bool CheckTemplateArgumentList(TemplateDecl *Template, |
6650 | SourceLocation TemplateLoc, |
6651 | TemplateArgumentListInfo &TemplateArgs, |
6652 | bool PartialTemplateArgs, |
6653 | SmallVectorImpl<TemplateArgument> &Converted, |
6654 | bool UpdateArgsWithConversions = true); |
6655 | |
6656 | bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, |
6657 | TemplateArgumentLoc &Arg, |
6658 | SmallVectorImpl<TemplateArgument> &Converted); |
6659 | |
6660 | bool CheckTemplateArgument(TemplateTypeParmDecl *Param, |
6661 | TypeSourceInfo *Arg); |
6662 | ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, |
6663 | QualType InstantiatedParamType, Expr *Arg, |
6664 | TemplateArgument &Converted, |
6665 | CheckTemplateArgumentKind CTAK = CTAK_Specified); |
6666 | bool CheckTemplateTemplateArgument(TemplateParameterList *Params, |
6667 | TemplateArgumentLoc &Arg); |
6668 | |
6669 | ExprResult |
6670 | BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, |
6671 | QualType ParamType, |
6672 | SourceLocation Loc); |
6673 | ExprResult |
6674 | BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, |
6675 | SourceLocation Loc); |
6676 | |
6677 | /// Enumeration describing how template parameter lists are compared |
6678 | /// for equality. |
6679 | enum TemplateParameterListEqualKind { |
6680 | /// We are matching the template parameter lists of two templates |
6681 | /// that might be redeclarations. |
6682 | /// |
6683 | /// \code |
6684 | /// template<typename T> struct X; |
6685 | /// template<typename T> struct X; |
6686 | /// \endcode |
6687 | TPL_TemplateMatch, |
6688 | |
6689 | /// We are matching the template parameter lists of two template |
6690 | /// template parameters as part of matching the template parameter lists |
6691 | /// of two templates that might be redeclarations. |
6692 | /// |
6693 | /// \code |
6694 | /// template<template<int I> class TT> struct X; |
6695 | /// template<template<int Value> class Other> struct X; |
6696 | /// \endcode |
6697 | TPL_TemplateTemplateParmMatch, |
6698 | |
6699 | /// We are matching the template parameter lists of a template |
6700 | /// template argument against the template parameter lists of a template |
6701 | /// template parameter. |
6702 | /// |
6703 | /// \code |
6704 | /// template<template<int Value> class Metafun> struct X; |
6705 | /// template<int Value> struct integer_c; |
6706 | /// X<integer_c> xic; |
6707 | /// \endcode |
6708 | TPL_TemplateTemplateArgumentMatch |
6709 | }; |
6710 | |
6711 | bool TemplateParameterListsAreEqual(TemplateParameterList *New, |
6712 | TemplateParameterList *Old, |
6713 | bool Complain, |
6714 | TemplateParameterListEqualKind Kind, |
6715 | SourceLocation TemplateArgLoc |
6716 | = SourceLocation()); |
6717 | |
6718 | bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); |
6719 | |
6720 | /// Called when the parser has parsed a C++ typename |
6721 | /// specifier, e.g., "typename T::type". |
6722 | /// |
6723 | /// \param S The scope in which this typename type occurs. |
6724 | /// \param TypenameLoc the location of the 'typename' keyword |
6725 | /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). |
6726 | /// \param II the identifier we're retrieving (e.g., 'type' in the example). |
6727 | /// \param IdLoc the location of the identifier. |
6728 | TypeResult |
6729 | ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, |
6730 | const CXXScopeSpec &SS, const IdentifierInfo &II, |
6731 | SourceLocation IdLoc); |
6732 | |
6733 | /// Called when the parser has parsed a C++ typename |
6734 | /// specifier that ends in a template-id, e.g., |
6735 | /// "typename MetaFun::template apply<T1, T2>". |
6736 | /// |
6737 | /// \param S The scope in which this typename type occurs. |
6738 | /// \param TypenameLoc the location of the 'typename' keyword |
6739 | /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). |
6740 | /// \param TemplateLoc the location of the 'template' keyword, if any. |
6741 | /// \param TemplateName The template name. |
6742 | /// \param TemplateII The identifier used to name the template. |
6743 | /// \param TemplateIILoc The location of the template name. |
6744 | /// \param LAngleLoc The location of the opening angle bracket ('<'). |
6745 | /// \param TemplateArgs The template arguments. |
6746 | /// \param RAngleLoc The location of the closing angle bracket ('>'). |
6747 | TypeResult |
6748 | ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, |
6749 | const CXXScopeSpec &SS, |
6750 | SourceLocation TemplateLoc, |
6751 | TemplateTy TemplateName, |
6752 | IdentifierInfo *TemplateII, |
6753 | SourceLocation TemplateIILoc, |
6754 | SourceLocation LAngleLoc, |
6755 | ASTTemplateArgsPtr TemplateArgs, |
6756 | SourceLocation RAngleLoc); |
6757 | |
6758 | QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, |
6759 | SourceLocation KeywordLoc, |
6760 | NestedNameSpecifierLoc QualifierLoc, |
6761 | const IdentifierInfo &II, |
6762 | SourceLocation IILoc); |
6763 | |
6764 | TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, |
6765 | SourceLocation Loc, |
6766 | DeclarationName Name); |
6767 | bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); |
6768 | |
6769 | ExprResult RebuildExprInCurrentInstantiation(Expr *E); |
6770 | bool RebuildTemplateParamsInCurrentInstantiation( |
6771 | TemplateParameterList *Params); |
6772 | |
6773 | std::string |
6774 | getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
6775 | const TemplateArgumentList &Args); |
6776 | |
6777 | std::string |
6778 | getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
6779 | const TemplateArgument *Args, |
6780 | unsigned NumArgs); |
6781 | |
6782 | //===--------------------------------------------------------------------===// |
6783 | // C++ Variadic Templates (C++0x [temp.variadic]) |
6784 | //===--------------------------------------------------------------------===// |
6785 | |
6786 | /// Determine whether an unexpanded parameter pack might be permitted in this |
6787 | /// location. Useful for error recovery. |
6788 | bool isUnexpandedParameterPackPermitted(); |
6789 | |
6790 | /// The context in which an unexpanded parameter pack is |
6791 | /// being diagnosed. |
6792 | /// |
6793 | /// Note that the values of this enumeration line up with the first |
6794 | /// argument to the \c err_unexpanded_parameter_pack diagnostic. |
6795 | enum UnexpandedParameterPackContext { |
6796 | /// An arbitrary expression. |
6797 | UPPC_Expression = 0, |
6798 | |
6799 | /// The base type of a class type. |
6800 | UPPC_BaseType, |
6801 | |
6802 | /// The type of an arbitrary declaration. |
6803 | UPPC_DeclarationType, |
6804 | |
6805 | /// The type of a data member. |
6806 | UPPC_DataMemberType, |
6807 | |
6808 | /// The size of a bit-field. |
6809 | UPPC_BitFieldWidth, |
6810 | |
6811 | /// The expression in a static assertion. |
6812 | UPPC_StaticAssertExpression, |
6813 | |
6814 | /// The fixed underlying type of an enumeration. |
6815 | UPPC_FixedUnderlyingType, |
6816 | |
6817 | /// The enumerator value. |
6818 | UPPC_EnumeratorValue, |
6819 | |
6820 | /// A using declaration. |
6821 | UPPC_UsingDeclaration, |
6822 | |
6823 | /// A friend declaration. |
6824 | UPPC_FriendDeclaration, |
6825 | |
6826 | /// A declaration qualifier. |
6827 | UPPC_DeclarationQualifier, |
6828 | |
6829 | /// An initializer. |
6830 | UPPC_Initializer, |
6831 | |
6832 | /// A default argument. |
6833 | UPPC_DefaultArgument, |
6834 | |
6835 | /// The type of a non-type template parameter. |
6836 | UPPC_NonTypeTemplateParameterType, |
6837 | |
6838 | /// The type of an exception. |
6839 | UPPC_ExceptionType, |
6840 | |
6841 | /// Partial specialization. |
6842 | UPPC_PartialSpecialization, |
6843 | |
6844 | /// Microsoft __if_exists. |
6845 | UPPC_IfExists, |
6846 | |
6847 | /// Microsoft __if_not_exists. |
6848 | UPPC_IfNotExists, |
6849 | |
6850 | /// Lambda expression. |
6851 | UPPC_Lambda, |
6852 | |
6853 | /// Block expression, |
6854 | UPPC_Block |
6855 | }; |
6856 | |
6857 | /// Diagnose unexpanded parameter packs. |
6858 | /// |
6859 | /// \param Loc The location at which we should emit the diagnostic. |
6860 | /// |
6861 | /// \param UPPC The context in which we are diagnosing unexpanded |
6862 | /// parameter packs. |
6863 | /// |
6864 | /// \param Unexpanded the set of unexpanded parameter packs. |
6865 | /// |
6866 | /// \returns true if an error occurred, false otherwise. |
6867 | bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, |
6868 | UnexpandedParameterPackContext UPPC, |
6869 | ArrayRef<UnexpandedParameterPack> Unexpanded); |
6870 | |
6871 | /// If the given type contains an unexpanded parameter pack, |
6872 | /// diagnose the error. |
6873 | /// |
6874 | /// \param Loc The source location where a diagnostc should be emitted. |
6875 | /// |
6876 | /// \param T The type that is being checked for unexpanded parameter |
6877 | /// packs. |
6878 | /// |
6879 | /// \returns true if an error occurred, false otherwise. |
6880 | bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, |
6881 | UnexpandedParameterPackContext UPPC); |
6882 | |
6883 | /// If the given expression contains an unexpanded parameter |
6884 | /// pack, diagnose the error. |
6885 | /// |
6886 | /// \param E The expression that is being checked for unexpanded |
6887 | /// parameter packs. |
6888 | /// |
6889 | /// \returns true if an error occurred, false otherwise. |
6890 | bool DiagnoseUnexpandedParameterPack(Expr *E, |
6891 | UnexpandedParameterPackContext UPPC = UPPC_Expression); |
6892 | |
6893 | /// If the given nested-name-specifier contains an unexpanded |
6894 | /// parameter pack, diagnose the error. |
6895 | /// |
6896 | /// \param SS The nested-name-specifier that is being checked for |
6897 | /// unexpanded parameter packs. |
6898 | /// |
6899 | /// \returns true if an error occurred, false otherwise. |
6900 | bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, |
6901 | UnexpandedParameterPackContext UPPC); |
6902 | |
6903 | /// If the given name contains an unexpanded parameter pack, |
6904 | /// diagnose the error. |
6905 | /// |
6906 | /// \param NameInfo The name (with source location information) that |
6907 | /// is being checked for unexpanded parameter packs. |
6908 | /// |
6909 | /// \returns true if an error occurred, false otherwise. |
6910 | bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, |
6911 | UnexpandedParameterPackContext UPPC); |
6912 | |
6913 | /// If the given template name contains an unexpanded parameter pack, |
6914 | /// diagnose the error. |
6915 | /// |
6916 | /// \param Loc The location of the template name. |
6917 | /// |
6918 | /// \param Template The template name that is being checked for unexpanded |
6919 | /// parameter packs. |
6920 | /// |
6921 | /// \returns true if an error occurred, false otherwise. |
6922 | bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, |
6923 | TemplateName Template, |
6924 | UnexpandedParameterPackContext UPPC); |
6925 | |
6926 | /// If the given template argument contains an unexpanded parameter |
6927 | /// pack, diagnose the error. |
6928 | /// |
6929 | /// \param Arg The template argument that is being checked for unexpanded |
6930 | /// parameter packs. |
6931 | /// |
6932 | /// \returns true if an error occurred, false otherwise. |
6933 | bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, |
6934 | UnexpandedParameterPackContext UPPC); |
6935 | |
6936 | /// Collect the set of unexpanded parameter packs within the given |
6937 | /// template argument. |
6938 | /// |
6939 | /// \param Arg The template argument that will be traversed to find |
6940 | /// unexpanded parameter packs. |
6941 | void collectUnexpandedParameterPacks(TemplateArgument Arg, |
6942 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6943 | |
6944 | /// Collect the set of unexpanded parameter packs within the given |
6945 | /// template argument. |
6946 | /// |
6947 | /// \param Arg The template argument that will be traversed to find |
6948 | /// unexpanded parameter packs. |
6949 | void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, |
6950 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6951 | |
6952 | /// Collect the set of unexpanded parameter packs within the given |
6953 | /// type. |
6954 | /// |
6955 | /// \param T The type that will be traversed to find |
6956 | /// unexpanded parameter packs. |
6957 | void collectUnexpandedParameterPacks(QualType T, |
6958 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6959 | |
6960 | /// Collect the set of unexpanded parameter packs within the given |
6961 | /// type. |
6962 | /// |
6963 | /// \param TL The type that will be traversed to find |
6964 | /// unexpanded parameter packs. |
6965 | void collectUnexpandedParameterPacks(TypeLoc TL, |
6966 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6967 | |
6968 | /// Collect the set of unexpanded parameter packs within the given |
6969 | /// nested-name-specifier. |
6970 | /// |
6971 | /// \param NNS The nested-name-specifier that will be traversed to find |
6972 | /// unexpanded parameter packs. |
6973 | void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, |
6974 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6975 | |
6976 | /// Collect the set of unexpanded parameter packs within the given |
6977 | /// name. |
6978 | /// |
6979 | /// \param NameInfo The name that will be traversed to find |
6980 | /// unexpanded parameter packs. |
6981 | void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, |
6982 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6983 | |
6984 | /// Invoked when parsing a template argument followed by an |
6985 | /// ellipsis, which creates a pack expansion. |
6986 | /// |
6987 | /// \param Arg The template argument preceding the ellipsis, which |
6988 | /// may already be invalid. |
6989 | /// |
6990 | /// \param EllipsisLoc The location of the ellipsis. |
6991 | ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, |
6992 | SourceLocation EllipsisLoc); |
6993 | |
6994 | /// Invoked when parsing a type followed by an ellipsis, which |
6995 | /// creates a pack expansion. |
6996 | /// |
6997 | /// \param Type The type preceding the ellipsis, which will become |
6998 | /// the pattern of the pack expansion. |
6999 | /// |
7000 | /// \param EllipsisLoc The location of the ellipsis. |
7001 | TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); |
7002 | |
7003 | /// Construct a pack expansion type from the pattern of the pack |
7004 | /// expansion. |
7005 | TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, |
7006 | SourceLocation EllipsisLoc, |
7007 | Optional<unsigned> NumExpansions); |
7008 | |
7009 | /// Construct a pack expansion type from the pattern of the pack |
7010 | /// expansion. |
7011 | QualType CheckPackExpansion(QualType Pattern, |
7012 | SourceRange PatternRange, |
7013 | SourceLocation EllipsisLoc, |
7014 | Optional<unsigned> NumExpansions); |
7015 | |
7016 | /// Invoked when parsing an expression followed by an ellipsis, which |
7017 | /// creates a pack expansion. |
7018 | /// |
7019 | /// \param Pattern The expression preceding the ellipsis, which will become |
7020 | /// the pattern of the pack expansion. |
7021 | /// |
7022 | /// \param EllipsisLoc The location of the ellipsis. |
7023 | ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); |
7024 | |
7025 | /// Invoked when parsing an expression followed by an ellipsis, which |
7026 | /// creates a pack expansion. |
7027 | /// |
7028 | /// \param Pattern The expression preceding the ellipsis, which will become |
7029 | /// the pattern of the pack expansion. |
7030 | /// |
7031 | /// \param EllipsisLoc The location of the ellipsis. |
7032 | ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, |
7033 | Optional<unsigned> NumExpansions); |
7034 | |
7035 | /// Determine whether we could expand a pack expansion with the |
7036 | /// given set of parameter packs into separate arguments by repeatedly |
7037 | /// transforming the pattern. |
7038 | /// |
7039 | /// \param EllipsisLoc The location of the ellipsis that identifies the |
7040 | /// pack expansion. |
7041 | /// |
7042 | /// \param PatternRange The source range that covers the entire pattern of |
7043 | /// the pack expansion. |
7044 | /// |
7045 | /// \param Unexpanded The set of unexpanded parameter packs within the |
7046 | /// pattern. |
7047 | /// |
7048 | /// \param ShouldExpand Will be set to \c true if the transformer should |
7049 | /// expand the corresponding pack expansions into separate arguments. When |
7050 | /// set, \c NumExpansions must also be set. |
7051 | /// |
7052 | /// \param RetainExpansion Whether the caller should add an unexpanded |
7053 | /// pack expansion after all of the expanded arguments. This is used |
7054 | /// when extending explicitly-specified template argument packs per |
7055 | /// C++0x [temp.arg.explicit]p9. |
7056 | /// |
7057 | /// \param NumExpansions The number of separate arguments that will be in |
7058 | /// the expanded form of the corresponding pack expansion. This is both an |
7059 | /// input and an output parameter, which can be set by the caller if the |
7060 | /// number of expansions is known a priori (e.g., due to a prior substitution) |
7061 | /// and will be set by the callee when the number of expansions is known. |
7062 | /// The callee must set this value when \c ShouldExpand is \c true; it may |
7063 | /// set this value in other cases. |
7064 | /// |
7065 | /// \returns true if an error occurred (e.g., because the parameter packs |
7066 | /// are to be instantiated with arguments of different lengths), false |
7067 | /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) |
7068 | /// must be set. |
7069 | bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, |
7070 | SourceRange PatternRange, |
7071 | ArrayRef<UnexpandedParameterPack> Unexpanded, |
7072 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7073 | bool &ShouldExpand, |
7074 | bool &RetainExpansion, |
7075 | Optional<unsigned> &NumExpansions); |
7076 | |
7077 | /// Determine the number of arguments in the given pack expansion |
7078 | /// type. |
7079 | /// |
7080 | /// This routine assumes that the number of arguments in the expansion is |
7081 | /// consistent across all of the unexpanded parameter packs in its pattern. |
7082 | /// |
7083 | /// Returns an empty Optional if the type can't be expanded. |
7084 | Optional<unsigned> getNumArgumentsInExpansion(QualType T, |
7085 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7086 | |
7087 | /// Determine whether the given declarator contains any unexpanded |
7088 | /// parameter packs. |
7089 | /// |
7090 | /// This routine is used by the parser to disambiguate function declarators |
7091 | /// with an ellipsis prior to the ')', e.g., |
7092 | /// |
7093 | /// \code |
7094 | /// void f(T...); |
7095 | /// \endcode |
7096 | /// |
7097 | /// To determine whether we have an (unnamed) function parameter pack or |
7098 | /// a variadic function. |
7099 | /// |
7100 | /// \returns true if the declarator contains any unexpanded parameter packs, |
7101 | /// false otherwise. |
7102 | bool containsUnexpandedParameterPacks(Declarator &D); |
7103 | |
7104 | /// Returns the pattern of the pack expansion for a template argument. |
7105 | /// |
7106 | /// \param OrigLoc The template argument to expand. |
7107 | /// |
7108 | /// \param Ellipsis Will be set to the location of the ellipsis. |
7109 | /// |
7110 | /// \param NumExpansions Will be set to the number of expansions that will |
7111 | /// be generated from this pack expansion, if known a priori. |
7112 | TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( |
7113 | TemplateArgumentLoc OrigLoc, |
7114 | SourceLocation &Ellipsis, |
7115 | Optional<unsigned> &NumExpansions) const; |
7116 | |
7117 | /// Given a template argument that contains an unexpanded parameter pack, but |
7118 | /// which has already been substituted, attempt to determine the number of |
7119 | /// elements that will be produced once this argument is fully-expanded. |
7120 | /// |
7121 | /// This is intended for use when transforming 'sizeof...(Arg)' in order to |
7122 | /// avoid actually expanding the pack where possible. |
7123 | Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); |
7124 | |
7125 | //===--------------------------------------------------------------------===// |
7126 | // C++ Template Argument Deduction (C++ [temp.deduct]) |
7127 | //===--------------------------------------------------------------------===// |
7128 | |
7129 | /// Adjust the type \p ArgFunctionType to match the calling convention, |
7130 | /// noreturn, and optionally the exception specification of \p FunctionType. |
7131 | /// Deduction often wants to ignore these properties when matching function |
7132 | /// types. |
7133 | QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, |
7134 | bool AdjustExceptionSpec = false); |
7135 | |
7136 | /// Describes the result of template argument deduction. |
7137 | /// |
7138 | /// The TemplateDeductionResult enumeration describes the result of |
7139 | /// template argument deduction, as returned from |
7140 | /// DeduceTemplateArguments(). The separate TemplateDeductionInfo |
7141 | /// structure provides additional information about the results of |
7142 | /// template argument deduction, e.g., the deduced template argument |
7143 | /// list (if successful) or the specific template parameters or |
7144 | /// deduced arguments that were involved in the failure. |
7145 | enum TemplateDeductionResult { |
7146 | /// Template argument deduction was successful. |
7147 | TDK_Success = 0, |
7148 | /// The declaration was invalid; do nothing. |
7149 | TDK_Invalid, |
7150 | /// Template argument deduction exceeded the maximum template |
7151 | /// instantiation depth (which has already been diagnosed). |
7152 | TDK_InstantiationDepth, |
7153 | /// Template argument deduction did not deduce a value |
7154 | /// for every template parameter. |
7155 | TDK_Incomplete, |
7156 | /// Template argument deduction did not deduce a value for every |
7157 | /// expansion of an expanded template parameter pack. |
7158 | TDK_IncompletePack, |
7159 | /// Template argument deduction produced inconsistent |
7160 | /// deduced values for the given template parameter. |
7161 | TDK_Inconsistent, |
7162 | /// Template argument deduction failed due to inconsistent |
7163 | /// cv-qualifiers on a template parameter type that would |
7164 | /// otherwise be deduced, e.g., we tried to deduce T in "const T" |
7165 | /// but were given a non-const "X". |
7166 | TDK_Underqualified, |
7167 | /// Substitution of the deduced template argument values |
7168 | /// resulted in an error. |
7169 | TDK_SubstitutionFailure, |
7170 | /// After substituting deduced template arguments, a dependent |
7171 | /// parameter type did not match the corresponding argument. |
7172 | TDK_DeducedMismatch, |
7173 | /// After substituting deduced template arguments, an element of |
7174 | /// a dependent parameter type did not match the corresponding element |
7175 | /// of the corresponding argument (when deducing from an initializer list). |
7176 | TDK_DeducedMismatchNested, |
7177 | /// A non-depnedent component of the parameter did not match the |
7178 | /// corresponding component of the argument. |
7179 | TDK_NonDeducedMismatch, |
7180 | /// When performing template argument deduction for a function |
7181 | /// template, there were too many call arguments. |
7182 | TDK_TooManyArguments, |
7183 | /// When performing template argument deduction for a function |
7184 | /// template, there were too few call arguments. |
7185 | TDK_TooFewArguments, |
7186 | /// The explicitly-specified template arguments were not valid |
7187 | /// template arguments for the given template. |
7188 | TDK_InvalidExplicitArguments, |
7189 | /// Checking non-dependent argument conversions failed. |
7190 | TDK_NonDependentConversionFailure, |
7191 | /// Deduction failed; that's all we know. |
7192 | TDK_MiscellaneousDeductionFailure, |
7193 | /// CUDA Target attributes do not match. |
7194 | TDK_CUDATargetMismatch |
7195 | }; |
7196 | |
7197 | TemplateDeductionResult |
7198 | DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, |
7199 | const TemplateArgumentList &TemplateArgs, |
7200 | sema::TemplateDeductionInfo &Info); |
7201 | |
7202 | TemplateDeductionResult |
7203 | DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, |
7204 | const TemplateArgumentList &TemplateArgs, |
7205 | sema::TemplateDeductionInfo &Info); |
7206 | |
7207 | TemplateDeductionResult SubstituteExplicitTemplateArguments( |
7208 | FunctionTemplateDecl *FunctionTemplate, |
7209 | TemplateArgumentListInfo &ExplicitTemplateArgs, |
7210 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
7211 | SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, |
7212 | sema::TemplateDeductionInfo &Info); |
7213 | |
7214 | /// brief A function argument from which we performed template argument |
7215 | // deduction for a call. |
7216 | struct OriginalCallArg { |
7217 | OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, |
7218 | unsigned ArgIdx, QualType OriginalArgType) |
7219 | : OriginalParamType(OriginalParamType), |
7220 | DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), |
7221 | OriginalArgType(OriginalArgType) {} |
7222 | |
7223 | QualType OriginalParamType; |
7224 | bool DecomposedParam; |
7225 | unsigned ArgIdx; |
7226 | QualType OriginalArgType; |
7227 | }; |
7228 | |
7229 | TemplateDeductionResult FinishTemplateArgumentDeduction( |
7230 | FunctionTemplateDecl *FunctionTemplate, |
7231 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
7232 | unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, |
7233 | sema::TemplateDeductionInfo &Info, |
7234 | SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, |
7235 | bool PartialOverloading = false, |
7236 | llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); |
7237 | |
7238 | TemplateDeductionResult DeduceTemplateArguments( |
7239 | FunctionTemplateDecl *FunctionTemplate, |
7240 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
7241 | FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, |
7242 | bool PartialOverloading, |
7243 | llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); |
7244 | |
7245 | TemplateDeductionResult |
7246 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, |
7247 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
7248 | QualType ArgFunctionType, |
7249 | FunctionDecl *&Specialization, |
7250 | sema::TemplateDeductionInfo &Info, |
7251 | bool IsAddressOfFunction = false); |
7252 | |
7253 | TemplateDeductionResult |
7254 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, |
7255 | QualType ToType, |
7256 | CXXConversionDecl *&Specialization, |
7257 | sema::TemplateDeductionInfo &Info); |
7258 | |
7259 | TemplateDeductionResult |
7260 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, |
7261 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
7262 | FunctionDecl *&Specialization, |
7263 | sema::TemplateDeductionInfo &Info, |
7264 | bool IsAddressOfFunction = false); |
7265 | |
7266 | /// Substitute Replacement for \p auto in \p TypeWithAuto |
7267 | QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); |
7268 | /// Substitute Replacement for auto in TypeWithAuto |
7269 | TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, |
7270 | QualType Replacement); |
7271 | /// Completely replace the \c auto in \p TypeWithAuto by |
7272 | /// \p Replacement. This does not retain any \c auto type sugar. |
7273 | QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); |
7274 | |
7275 | /// Result type of DeduceAutoType. |
7276 | enum DeduceAutoResult { |
7277 | DAR_Succeeded, |
7278 | DAR_Failed, |
7279 | DAR_FailedAlreadyDiagnosed |
7280 | }; |
7281 | |
7282 | DeduceAutoResult |
7283 | DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, |
7284 | Optional<unsigned> DependentDeductionDepth = None); |
7285 | DeduceAutoResult |
7286 | DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, |
7287 | Optional<unsigned> DependentDeductionDepth = None); |
7288 | void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); |
7289 | bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, |
7290 | bool Diagnose = true); |
7291 | |
7292 | /// Declare implicit deduction guides for a class template if we've |
7293 | /// not already done so. |
7294 | void DeclareImplicitDeductionGuides(TemplateDecl *Template, |
7295 | SourceLocation Loc); |
7296 | |
7297 | QualType DeduceTemplateSpecializationFromInitializer( |
7298 | TypeSourceInfo *TInfo, const InitializedEntity &Entity, |
7299 | const InitializationKind &Kind, MultiExprArg Init); |
7300 | |
7301 | QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, |
7302 | QualType Type, TypeSourceInfo *TSI, |
7303 | SourceRange Range, bool DirectInit, |
7304 | Expr *Init); |
7305 | |
7306 | TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; |
7307 | |
7308 | bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, |
7309 | SourceLocation ReturnLoc, |
7310 | Expr *&RetExpr, AutoType *AT); |
7311 | |
7312 | FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, |
7313 | FunctionTemplateDecl *FT2, |
7314 | SourceLocation Loc, |
7315 | TemplatePartialOrderingContext TPOC, |
7316 | unsigned NumCallArguments1, |
7317 | unsigned NumCallArguments2); |
7318 | UnresolvedSetIterator |
7319 | getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, |
7320 | TemplateSpecCandidateSet &FailedCandidates, |
7321 | SourceLocation Loc, |
7322 | const PartialDiagnostic &NoneDiag, |
7323 | const PartialDiagnostic &AmbigDiag, |
7324 | const PartialDiagnostic &CandidateDiag, |
7325 | bool Complain = true, QualType TargetType = QualType()); |
7326 | |
7327 | ClassTemplatePartialSpecializationDecl * |
7328 | getMoreSpecializedPartialSpecialization( |
7329 | ClassTemplatePartialSpecializationDecl *PS1, |
7330 | ClassTemplatePartialSpecializationDecl *PS2, |
7331 | SourceLocation Loc); |
7332 | |
7333 | bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, |
7334 | sema::TemplateDeductionInfo &Info); |
7335 | |
7336 | VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( |
7337 | VarTemplatePartialSpecializationDecl *PS1, |
7338 | VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); |
7339 | |
7340 | bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, |
7341 | sema::TemplateDeductionInfo &Info); |
7342 | |
7343 | bool isTemplateTemplateParameterAtLeastAsSpecializedAs( |
7344 | TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc); |
7345 | |
7346 | void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, |
7347 | bool OnlyDeduced, |
7348 | unsigned Depth, |
7349 | llvm::SmallBitVector &Used); |
7350 | void MarkDeducedTemplateParameters( |
7351 | const FunctionTemplateDecl *FunctionTemplate, |
7352 | llvm::SmallBitVector &Deduced) { |
7353 | return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); |
7354 | } |
7355 | static void MarkDeducedTemplateParameters(ASTContext &Ctx, |
7356 | const FunctionTemplateDecl *FunctionTemplate, |
7357 | llvm::SmallBitVector &Deduced); |
7358 | |
7359 | //===--------------------------------------------------------------------===// |
7360 | // C++ Template Instantiation |
7361 | // |
7362 | |
7363 | MultiLevelTemplateArgumentList |
7364 | getTemplateInstantiationArgs(NamedDecl *D, |
7365 | const TemplateArgumentList *Innermost = nullptr, |
7366 | bool RelativeToPrimary = false, |
7367 | const FunctionDecl *Pattern = nullptr); |
7368 | |
7369 | /// A context in which code is being synthesized (where a source location |
7370 | /// alone is not sufficient to identify the context). This covers template |
7371 | /// instantiation and various forms of implicitly-generated functions. |
7372 | struct CodeSynthesisContext { |
7373 | /// The kind of template instantiation we are performing |
7374 | enum SynthesisKind { |
7375 | /// We are instantiating a template declaration. The entity is |
7376 | /// the declaration we're instantiating (e.g., a CXXRecordDecl). |
7377 | TemplateInstantiation, |
7378 | |
7379 | /// We are instantiating a default argument for a template |
7380 | /// parameter. The Entity is the template parameter whose argument is |
7381 | /// being instantiated, the Template is the template, and the |
7382 | /// TemplateArgs/NumTemplateArguments provide the template arguments as |
7383 | /// specified. |
7384 | DefaultTemplateArgumentInstantiation, |
7385 | |
7386 | /// We are instantiating a default argument for a function. |
7387 | /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs |
7388 | /// provides the template arguments as specified. |
7389 | DefaultFunctionArgumentInstantiation, |
7390 | |
7391 | /// We are substituting explicit template arguments provided for |
7392 | /// a function template. The entity is a FunctionTemplateDecl. |
7393 | ExplicitTemplateArgumentSubstitution, |
7394 | |
7395 | /// We are substituting template argument determined as part of |
7396 | /// template argument deduction for either a class template |
7397 | /// partial specialization or a function template. The |
7398 | /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or |
7399 | /// a TemplateDecl. |
7400 | DeducedTemplateArgumentSubstitution, |
7401 | |
7402 | /// We are substituting prior template arguments into a new |
7403 | /// template parameter. The template parameter itself is either a |
7404 | /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. |
7405 | PriorTemplateArgumentSubstitution, |
7406 | |
7407 | /// We are checking the validity of a default template argument that |
7408 | /// has been used when naming a template-id. |
7409 | DefaultTemplateArgumentChecking, |
7410 | |
7411 | /// We are computing the exception specification for a defaulted special |
7412 | /// member function. |
7413 | ExceptionSpecEvaluation, |
7414 | |
7415 | /// We are instantiating the exception specification for a function |
7416 | /// template which was deferred until it was needed. |
7417 | ExceptionSpecInstantiation, |
7418 | |
7419 | /// We are declaring an implicit special member function. |
7420 | DeclaringSpecialMember, |
7421 | |
7422 | /// We are defining a synthesized function (such as a defaulted special |
7423 | /// member). |
7424 | DefiningSynthesizedFunction, |
7425 | |
7426 | /// Added for Template instantiation observation. |
7427 | /// Memoization means we are _not_ instantiating a template because |
7428 | /// it is already instantiated (but we entered a context where we |
7429 | /// would have had to if it was not already instantiated). |
7430 | Memoization |
7431 | } Kind; |
7432 | |
7433 | /// Was the enclosing context a non-instantiation SFINAE context? |
7434 | bool SavedInNonInstantiationSFINAEContext; |
7435 | |
7436 | /// The point of instantiation or synthesis within the source code. |
7437 | SourceLocation PointOfInstantiation; |
7438 | |
7439 | /// The entity that is being synthesized. |
7440 | Decl *Entity; |
7441 | |
7442 | /// The template (or partial specialization) in which we are |
7443 | /// performing the instantiation, for substitutions of prior template |
7444 | /// arguments. |
7445 | NamedDecl *Template; |
7446 | |
7447 | /// The list of template arguments we are substituting, if they |
7448 | /// are not part of the entity. |
7449 | const TemplateArgument *TemplateArgs; |
7450 | |
7451 | // FIXME: Wrap this union around more members, or perhaps store the |
7452 | // kind-specific members in the RAII object owning the context. |
7453 | union { |
7454 | /// The number of template arguments in TemplateArgs. |
7455 | unsigned NumTemplateArgs; |
7456 | |
7457 | /// The special member being declared or defined. |
7458 | CXXSpecialMember SpecialMember; |
7459 | }; |
7460 | |
7461 | ArrayRef<TemplateArgument> template_arguments() const { |
7462 | assert(Kind != DeclaringSpecialMember)((Kind != DeclaringSpecialMember) ? static_cast<void> ( 0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7462, __PRETTY_FUNCTION__)); |
7463 | return {TemplateArgs, NumTemplateArgs}; |
7464 | } |
7465 | |
7466 | /// The template deduction info object associated with the |
7467 | /// substitution or checking of explicit or deduced template arguments. |
7468 | sema::TemplateDeductionInfo *DeductionInfo; |
7469 | |
7470 | /// The source range that covers the construct that cause |
7471 | /// the instantiation, e.g., the template-id that causes a class |
7472 | /// template instantiation. |
7473 | SourceRange InstantiationRange; |
7474 | |
7475 | CodeSynthesisContext() |
7476 | : Kind(TemplateInstantiation), |
7477 | SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), |
7478 | Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), |
7479 | DeductionInfo(nullptr) {} |
7480 | |
7481 | /// Determines whether this template is an actual instantiation |
7482 | /// that should be counted toward the maximum instantiation depth. |
7483 | bool isInstantiationRecord() const; |
7484 | }; |
7485 | |
7486 | /// List of active code synthesis contexts. |
7487 | /// |
7488 | /// This vector is treated as a stack. As synthesis of one entity requires |
7489 | /// synthesis of another, additional contexts are pushed onto the stack. |
7490 | SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; |
7491 | |
7492 | /// Specializations whose definitions are currently being instantiated. |
7493 | llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; |
7494 | |
7495 | /// Non-dependent types used in templates that have already been instantiated |
7496 | /// by some template instantiation. |
7497 | llvm::DenseSet<QualType> InstantiatedNonDependentTypes; |
7498 | |
7499 | /// Extra modules inspected when performing a lookup during a template |
7500 | /// instantiation. Computed lazily. |
7501 | SmallVector<Module*, 16> CodeSynthesisContextLookupModules; |
7502 | |
7503 | /// Cache of additional modules that should be used for name lookup |
7504 | /// within the current template instantiation. Computed lazily; use |
7505 | /// getLookupModules() to get a complete set. |
7506 | llvm::DenseSet<Module*> LookupModulesCache; |
7507 | |
7508 | /// Get the set of additional modules that should be checked during |
7509 | /// name lookup. A module and its imports become visible when instanting a |
7510 | /// template defined within it. |
7511 | llvm::DenseSet<Module*> &getLookupModules(); |
7512 | |
7513 | /// Map from the most recent declaration of a namespace to the most |
7514 | /// recent visible declaration of that namespace. |
7515 | llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; |
7516 | |
7517 | /// Whether we are in a SFINAE context that is not associated with |
7518 | /// template instantiation. |
7519 | /// |
7520 | /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside |
7521 | /// of a template instantiation or template argument deduction. |
7522 | bool InNonInstantiationSFINAEContext; |
7523 | |
7524 | /// The number of \p CodeSynthesisContexts that are not template |
7525 | /// instantiations and, therefore, should not be counted as part of the |
7526 | /// instantiation depth. |
7527 | /// |
7528 | /// When the instantiation depth reaches the user-configurable limit |
7529 | /// \p LangOptions::InstantiationDepth we will abort instantiation. |
7530 | // FIXME: Should we have a similar limit for other forms of synthesis? |
7531 | unsigned NonInstantiationEntries; |
7532 | |
7533 | /// The depth of the context stack at the point when the most recent |
7534 | /// error or warning was produced. |
7535 | /// |
7536 | /// This value is used to suppress printing of redundant context stacks |
7537 | /// when there are multiple errors or warnings in the same instantiation. |
7538 | // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. |
7539 | unsigned LastEmittedCodeSynthesisContextDepth = 0; |
7540 | |
7541 | /// The template instantiation callbacks to trace or track |
7542 | /// instantiations (objects can be chained). |
7543 | /// |
7544 | /// This callbacks is used to print, trace or track template |
7545 | /// instantiations as they are being constructed. |
7546 | std::vector<std::unique_ptr<TemplateInstantiationCallback>> |
7547 | TemplateInstCallbacks; |
7548 | |
7549 | /// The current index into pack expansion arguments that will be |
7550 | /// used for substitution of parameter packs. |
7551 | /// |
7552 | /// The pack expansion index will be -1 to indicate that parameter packs |
7553 | /// should be instantiated as themselves. Otherwise, the index specifies |
7554 | /// which argument within the parameter pack will be used for substitution. |
7555 | int ArgumentPackSubstitutionIndex; |
7556 | |
7557 | /// RAII object used to change the argument pack substitution index |
7558 | /// within a \c Sema object. |
7559 | /// |
7560 | /// See \c ArgumentPackSubstitutionIndex for more information. |
7561 | class ArgumentPackSubstitutionIndexRAII { |
7562 | Sema &Self; |
7563 | int OldSubstitutionIndex; |
7564 | |
7565 | public: |
7566 | ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) |
7567 | : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { |
7568 | Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; |
7569 | } |
7570 | |
7571 | ~ArgumentPackSubstitutionIndexRAII() { |
7572 | Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; |
7573 | } |
7574 | }; |
7575 | |
7576 | friend class ArgumentPackSubstitutionRAII; |
7577 | |
7578 | /// For each declaration that involved template argument deduction, the |
7579 | /// set of diagnostics that were suppressed during that template argument |
7580 | /// deduction. |
7581 | /// |
7582 | /// FIXME: Serialize this structure to the AST file. |
7583 | typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > |
7584 | SuppressedDiagnosticsMap; |
7585 | SuppressedDiagnosticsMap SuppressedDiagnostics; |
7586 | |
7587 | /// A stack object to be created when performing template |
7588 | /// instantiation. |
7589 | /// |
7590 | /// Construction of an object of type \c InstantiatingTemplate |
7591 | /// pushes the current instantiation onto the stack of active |
7592 | /// instantiations. If the size of this stack exceeds the maximum |
7593 | /// number of recursive template instantiations, construction |
7594 | /// produces an error and evaluates true. |
7595 | /// |
7596 | /// Destruction of this object will pop the named instantiation off |
7597 | /// the stack. |
7598 | struct InstantiatingTemplate { |
7599 | /// Note that we are instantiating a class template, |
7600 | /// function template, variable template, alias template, |
7601 | /// or a member thereof. |
7602 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7603 | Decl *Entity, |
7604 | SourceRange InstantiationRange = SourceRange()); |
7605 | |
7606 | struct ExceptionSpecification {}; |
7607 | /// Note that we are instantiating an exception specification |
7608 | /// of a function template. |
7609 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7610 | FunctionDecl *Entity, ExceptionSpecification, |
7611 | SourceRange InstantiationRange = SourceRange()); |
7612 | |
7613 | /// Note that we are instantiating a default argument in a |
7614 | /// template-id. |
7615 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7616 | TemplateParameter Param, TemplateDecl *Template, |
7617 | ArrayRef<TemplateArgument> TemplateArgs, |
7618 | SourceRange InstantiationRange = SourceRange()); |
7619 | |
7620 | /// Note that we are substituting either explicitly-specified or |
7621 | /// deduced template arguments during function template argument deduction. |
7622 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7623 | FunctionTemplateDecl *FunctionTemplate, |
7624 | ArrayRef<TemplateArgument> TemplateArgs, |
7625 | CodeSynthesisContext::SynthesisKind Kind, |
7626 | sema::TemplateDeductionInfo &DeductionInfo, |
7627 | SourceRange InstantiationRange = SourceRange()); |
7628 | |
7629 | /// Note that we are instantiating as part of template |
7630 | /// argument deduction for a class template declaration. |
7631 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7632 | TemplateDecl *Template, |
7633 | ArrayRef<TemplateArgument> TemplateArgs, |
7634 | sema::TemplateDeductionInfo &DeductionInfo, |
7635 | SourceRange InstantiationRange = SourceRange()); |
7636 | |
7637 | /// Note that we are instantiating as part of template |
7638 | /// argument deduction for a class template partial |
7639 | /// specialization. |
7640 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7641 | ClassTemplatePartialSpecializationDecl *PartialSpec, |
7642 | ArrayRef<TemplateArgument> TemplateArgs, |
7643 | sema::TemplateDeductionInfo &DeductionInfo, |
7644 | SourceRange InstantiationRange = SourceRange()); |
7645 | |
7646 | /// Note that we are instantiating as part of template |
7647 | /// argument deduction for a variable template partial |
7648 | /// specialization. |
7649 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7650 | VarTemplatePartialSpecializationDecl *PartialSpec, |
7651 | ArrayRef<TemplateArgument> TemplateArgs, |
7652 | sema::TemplateDeductionInfo &DeductionInfo, |
7653 | SourceRange InstantiationRange = SourceRange()); |
7654 | |
7655 | /// Note that we are instantiating a default argument for a function |
7656 | /// parameter. |
7657 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7658 | ParmVarDecl *Param, |
7659 | ArrayRef<TemplateArgument> TemplateArgs, |
7660 | SourceRange InstantiationRange = SourceRange()); |
7661 | |
7662 | /// Note that we are substituting prior template arguments into a |
7663 | /// non-type parameter. |
7664 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7665 | NamedDecl *Template, |
7666 | NonTypeTemplateParmDecl *Param, |
7667 | ArrayRef<TemplateArgument> TemplateArgs, |
7668 | SourceRange InstantiationRange); |
7669 | |
7670 | /// Note that we are substituting prior template arguments into a |
7671 | /// template template parameter. |
7672 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7673 | NamedDecl *Template, |
7674 | TemplateTemplateParmDecl *Param, |
7675 | ArrayRef<TemplateArgument> TemplateArgs, |
7676 | SourceRange InstantiationRange); |
7677 | |
7678 | /// Note that we are checking the default template argument |
7679 | /// against the template parameter for a given template-id. |
7680 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7681 | TemplateDecl *Template, |
7682 | NamedDecl *Param, |
7683 | ArrayRef<TemplateArgument> TemplateArgs, |
7684 | SourceRange InstantiationRange); |
7685 | |
7686 | |
7687 | /// Note that we have finished instantiating this template. |
7688 | void Clear(); |
7689 | |
7690 | ~InstantiatingTemplate() { Clear(); } |
7691 | |
7692 | /// Determines whether we have exceeded the maximum |
7693 | /// recursive template instantiations. |
7694 | bool isInvalid() const { return Invalid; } |
7695 | |
7696 | /// Determine whether we are already instantiating this |
7697 | /// specialization in some surrounding active instantiation. |
7698 | bool isAlreadyInstantiating() const { return AlreadyInstantiating; } |
7699 | |
7700 | private: |
7701 | Sema &SemaRef; |
7702 | bool Invalid; |
7703 | bool AlreadyInstantiating; |
7704 | bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, |
7705 | SourceRange InstantiationRange); |
7706 | |
7707 | InstantiatingTemplate( |
7708 | Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, |
7709 | SourceLocation PointOfInstantiation, SourceRange InstantiationRange, |
7710 | Decl *Entity, NamedDecl *Template = nullptr, |
7711 | ArrayRef<TemplateArgument> TemplateArgs = None, |
7712 | sema::TemplateDeductionInfo *DeductionInfo = nullptr); |
7713 | |
7714 | InstantiatingTemplate(const InstantiatingTemplate&) = delete; |
7715 | |
7716 | InstantiatingTemplate& |
7717 | operator=(const InstantiatingTemplate&) = delete; |
7718 | }; |
7719 | |
7720 | void pushCodeSynthesisContext(CodeSynthesisContext Ctx); |
7721 | void popCodeSynthesisContext(); |
7722 | |
7723 | /// Determine whether we are currently performing template instantiation. |
7724 | bool inTemplateInstantiation() const { |
7725 | return CodeSynthesisContexts.size() > NonInstantiationEntries; |
7726 | } |
7727 | |
7728 | void PrintContextStack() { |
7729 | if (!CodeSynthesisContexts.empty() && |
7730 | CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { |
7731 | PrintInstantiationStack(); |
7732 | LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); |
7733 | } |
7734 | if (PragmaAttributeCurrentTargetDecl) |
7735 | PrintPragmaAttributeInstantiationPoint(); |
7736 | } |
7737 | void PrintInstantiationStack(); |
7738 | |
7739 | void PrintPragmaAttributeInstantiationPoint(); |
7740 | |
7741 | /// Determines whether we are currently in a context where |
7742 | /// template argument substitution failures are not considered |
7743 | /// errors. |
7744 | /// |
7745 | /// \returns An empty \c Optional if we're not in a SFINAE context. |
7746 | /// Otherwise, contains a pointer that, if non-NULL, contains the nearest |
7747 | /// template-deduction context object, which can be used to capture |
7748 | /// diagnostics that will be suppressed. |
7749 | Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; |
7750 | |
7751 | /// Determines whether we are currently in a context that |
7752 | /// is not evaluated as per C++ [expr] p5. |
7753 | bool isUnevaluatedContext() const { |
7754 | assert(!ExprEvalContexts.empty() &&((!ExprEvalContexts.empty() && "Must be in an expression evaluation context" ) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7755, __PRETTY_FUNCTION__)) |
7755 | "Must be in an expression evaluation context")((!ExprEvalContexts.empty() && "Must be in an expression evaluation context" ) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7755, __PRETTY_FUNCTION__)); |
7756 | return ExprEvalContexts.back().isUnevaluated(); |
7757 | } |
7758 | |
7759 | /// RAII class used to determine whether SFINAE has |
7760 | /// trapped any errors that occur during template argument |
7761 | /// deduction. |
7762 | class SFINAETrap { |
7763 | Sema &SemaRef; |
7764 | unsigned PrevSFINAEErrors; |
7765 | bool PrevInNonInstantiationSFINAEContext; |
7766 | bool PrevAccessCheckingSFINAE; |
7767 | bool PrevLastDiagnosticIgnored; |
7768 | |
7769 | public: |
7770 | explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) |
7771 | : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), |
7772 | PrevInNonInstantiationSFINAEContext( |
7773 | SemaRef.InNonInstantiationSFINAEContext), |
7774 | PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), |
7775 | PrevLastDiagnosticIgnored( |
7776 | SemaRef.getDiagnostics().isLastDiagnosticIgnored()) |
7777 | { |
7778 | if (!SemaRef.isSFINAEContext()) |
7779 | SemaRef.InNonInstantiationSFINAEContext = true; |
7780 | SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; |
7781 | } |
7782 | |
7783 | ~SFINAETrap() { |
7784 | SemaRef.NumSFINAEErrors = PrevSFINAEErrors; |
7785 | SemaRef.InNonInstantiationSFINAEContext |
7786 | = PrevInNonInstantiationSFINAEContext; |
7787 | SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; |
7788 | SemaRef.getDiagnostics().setLastDiagnosticIgnored( |
7789 | PrevLastDiagnosticIgnored); |
7790 | } |
7791 | |
7792 | /// Determine whether any SFINAE errors have been trapped. |
7793 | bool hasErrorOccurred() const { |
7794 | return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; |
7795 | } |
7796 | }; |
7797 | |
7798 | /// RAII class used to indicate that we are performing provisional |
7799 | /// semantic analysis to determine the validity of a construct, so |
7800 | /// typo-correction and diagnostics in the immediate context (not within |
7801 | /// implicitly-instantiated templates) should be suppressed. |
7802 | class TentativeAnalysisScope { |
7803 | Sema &SemaRef; |
7804 | // FIXME: Using a SFINAETrap for this is a hack. |
7805 | SFINAETrap Trap; |
7806 | bool PrevDisableTypoCorrection; |
7807 | public: |
7808 | explicit TentativeAnalysisScope(Sema &SemaRef) |
7809 | : SemaRef(SemaRef), Trap(SemaRef, true), |
7810 | PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { |
7811 | SemaRef.DisableTypoCorrection = true; |
7812 | } |
7813 | ~TentativeAnalysisScope() { |
7814 | SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; |
7815 | } |
7816 | }; |
7817 | |
7818 | /// The current instantiation scope used to store local |
7819 | /// variables. |
7820 | LocalInstantiationScope *CurrentInstantiationScope; |
7821 | |
7822 | /// Tracks whether we are in a context where typo correction is |
7823 | /// disabled. |
7824 | bool DisableTypoCorrection; |
7825 | |
7826 | /// The number of typos corrected by CorrectTypo. |
7827 | unsigned TyposCorrected; |
7828 | |
7829 | typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; |
7830 | typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; |
7831 | |
7832 | /// A cache containing identifiers for which typo correction failed and |
7833 | /// their locations, so that repeated attempts to correct an identifier in a |
7834 | /// given location are ignored if typo correction already failed for it. |
7835 | IdentifierSourceLocations TypoCorrectionFailures; |
7836 | |
7837 | /// Worker object for performing CFG-based warnings. |
7838 | sema::AnalysisBasedWarnings AnalysisWarnings; |
7839 | threadSafety::BeforeSet *ThreadSafetyDeclCache; |
7840 | |
7841 | /// An entity for which implicit template instantiation is required. |
7842 | /// |
7843 | /// The source location associated with the declaration is the first place in |
7844 | /// the source code where the declaration was "used". It is not necessarily |
7845 | /// the point of instantiation (which will be either before or after the |
7846 | /// namespace-scope declaration that triggered this implicit instantiation), |
7847 | /// However, it is the location that diagnostics should generally refer to, |
7848 | /// because users will need to know what code triggered the instantiation. |
7849 | typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; |
7850 | |
7851 | /// The queue of implicit template instantiations that are required |
7852 | /// but have not yet been performed. |
7853 | std::deque<PendingImplicitInstantiation> PendingInstantiations; |
7854 | |
7855 | /// Queue of implicit template instantiations that cannot be performed |
7856 | /// eagerly. |
7857 | SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; |
7858 | |
7859 | class GlobalEagerInstantiationScope { |
7860 | public: |
7861 | GlobalEagerInstantiationScope(Sema &S, bool Enabled) |
7862 | : S(S), Enabled(Enabled) { |
7863 | if (!Enabled) return; |
7864 | |
7865 | SavedPendingInstantiations.swap(S.PendingInstantiations); |
7866 | SavedVTableUses.swap(S.VTableUses); |
7867 | } |
7868 | |
7869 | void perform() { |
7870 | if (Enabled) { |
7871 | S.DefineUsedVTables(); |
7872 | S.PerformPendingInstantiations(); |
7873 | } |
7874 | } |
7875 | |
7876 | ~GlobalEagerInstantiationScope() { |
7877 | if (!Enabled) return; |
7878 | |
7879 | // Restore the set of pending vtables. |
7880 | assert(S.VTableUses.empty() &&((S.VTableUses.empty() && "VTableUses should be empty before it is discarded." ) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7881, __PRETTY_FUNCTION__)) |
7881 | "VTableUses should be empty before it is discarded.")((S.VTableUses.empty() && "VTableUses should be empty before it is discarded." ) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7881, __PRETTY_FUNCTION__)); |
7882 | S.VTableUses.swap(SavedVTableUses); |
7883 | |
7884 | // Restore the set of pending implicit instantiations. |
7885 | assert(S.PendingInstantiations.empty() &&((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded." ) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7886, __PRETTY_FUNCTION__)) |
7886 | "PendingInstantiations should be empty before it is discarded.")((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded." ) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7886, __PRETTY_FUNCTION__)); |
7887 | S.PendingInstantiations.swap(SavedPendingInstantiations); |
7888 | } |
7889 | |
7890 | private: |
7891 | Sema &S; |
7892 | SmallVector<VTableUse, 16> SavedVTableUses; |
7893 | std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; |
7894 | bool Enabled; |
7895 | }; |
7896 | |
7897 | /// The queue of implicit template instantiations that are required |
7898 | /// and must be performed within the current local scope. |
7899 | /// |
7900 | /// This queue is only used for member functions of local classes in |
7901 | /// templates, which must be instantiated in the same scope as their |
7902 | /// enclosing function, so that they can reference function-local |
7903 | /// types, static variables, enumerators, etc. |
7904 | std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; |
7905 | |
7906 | class LocalEagerInstantiationScope { |
7907 | public: |
7908 | LocalEagerInstantiationScope(Sema &S) : S(S) { |
7909 | SavedPendingLocalImplicitInstantiations.swap( |
7910 | S.PendingLocalImplicitInstantiations); |
7911 | } |
7912 | |
7913 | void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } |
7914 | |
7915 | ~LocalEagerInstantiationScope() { |
7916 | assert(S.PendingLocalImplicitInstantiations.empty() &&((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations" ) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7917, __PRETTY_FUNCTION__)) |
7917 | "there shouldn't be any pending local implicit instantiations")((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations" ) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7917, __PRETTY_FUNCTION__)); |
7918 | SavedPendingLocalImplicitInstantiations.swap( |
7919 | S.PendingLocalImplicitInstantiations); |
7920 | } |
7921 | |
7922 | private: |
7923 | Sema &S; |
7924 | std::deque<PendingImplicitInstantiation> |
7925 | SavedPendingLocalImplicitInstantiations; |
7926 | }; |
7927 | |
7928 | /// A helper class for building up ExtParameterInfos. |
7929 | class ExtParameterInfoBuilder { |
7930 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; |
7931 | bool HasInteresting = false; |
7932 | |
7933 | public: |
7934 | /// Set the ExtParameterInfo for the parameter at the given index, |
7935 | /// |
7936 | void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { |
7937 | assert(Infos.size() <= index)((Infos.size() <= index) ? static_cast<void> (0) : __assert_fail ("Infos.size() <= index", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 7937, __PRETTY_FUNCTION__)); |
7938 | Infos.resize(index); |
7939 | Infos.push_back(info); |
7940 | |
7941 | if (!HasInteresting) |
7942 | HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); |
7943 | } |
7944 | |
7945 | /// Return a pointer (suitable for setting in an ExtProtoInfo) to the |
7946 | /// ExtParameterInfo array we've built up. |
7947 | const FunctionProtoType::ExtParameterInfo * |
7948 | getPointerOrNull(unsigned numParams) { |
7949 | if (!HasInteresting) return nullptr; |
7950 | Infos.resize(numParams); |
7951 | return Infos.data(); |
7952 | } |
7953 | }; |
7954 | |
7955 | void PerformPendingInstantiations(bool LocalOnly = false); |
7956 | |
7957 | TypeSourceInfo *SubstType(TypeSourceInfo *T, |
7958 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7959 | SourceLocation Loc, DeclarationName Entity, |
7960 | bool AllowDeducedTST = false); |
7961 | |
7962 | QualType SubstType(QualType T, |
7963 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7964 | SourceLocation Loc, DeclarationName Entity); |
7965 | |
7966 | TypeSourceInfo *SubstType(TypeLoc TL, |
7967 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7968 | SourceLocation Loc, DeclarationName Entity); |
7969 | |
7970 | TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, |
7971 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7972 | SourceLocation Loc, |
7973 | DeclarationName Entity, |
7974 | CXXRecordDecl *ThisContext, |
7975 | Qualifiers ThisTypeQuals); |
7976 | void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, |
7977 | const MultiLevelTemplateArgumentList &Args); |
7978 | bool SubstExceptionSpec(SourceLocation Loc, |
7979 | FunctionProtoType::ExceptionSpecInfo &ESI, |
7980 | SmallVectorImpl<QualType> &ExceptionStorage, |
7981 | const MultiLevelTemplateArgumentList &Args); |
7982 | ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, |
7983 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7984 | int indexAdjustment, |
7985 | Optional<unsigned> NumExpansions, |
7986 | bool ExpectParameterPack); |
7987 | bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, |
7988 | const FunctionProtoType::ExtParameterInfo *ExtParamInfos, |
7989 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7990 | SmallVectorImpl<QualType> &ParamTypes, |
7991 | SmallVectorImpl<ParmVarDecl *> *OutParams, |
7992 | ExtParameterInfoBuilder &ParamInfos); |
7993 | ExprResult SubstExpr(Expr *E, |
7994 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7995 | |
7996 | /// Substitute the given template arguments into a list of |
7997 | /// expressions, expanding pack expansions if required. |
7998 | /// |
7999 | /// \param Exprs The list of expressions to substitute into. |
8000 | /// |
8001 | /// \param IsCall Whether this is some form of call, in which case |
8002 | /// default arguments will be dropped. |
8003 | /// |
8004 | /// \param TemplateArgs The set of template arguments to substitute. |
8005 | /// |
8006 | /// \param Outputs Will receive all of the substituted arguments. |
8007 | /// |
8008 | /// \returns true if an error occurred, false otherwise. |
8009 | bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, |
8010 | const MultiLevelTemplateArgumentList &TemplateArgs, |
8011 | SmallVectorImpl<Expr *> &Outputs); |
8012 | |
8013 | StmtResult SubstStmt(Stmt *S, |
8014 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8015 | |
8016 | TemplateParameterList * |
8017 | SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, |
8018 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8019 | |
8020 | Decl *SubstDecl(Decl *D, DeclContext *Owner, |
8021 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8022 | |
8023 | ExprResult SubstInitializer(Expr *E, |
8024 | const MultiLevelTemplateArgumentList &TemplateArgs, |
8025 | bool CXXDirectInit); |
8026 | |
8027 | bool |
8028 | SubstBaseSpecifiers(CXXRecordDecl *Instantiation, |
8029 | CXXRecordDecl *Pattern, |
8030 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8031 | |
8032 | bool |
8033 | InstantiateClass(SourceLocation PointOfInstantiation, |
8034 | CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, |
8035 | const MultiLevelTemplateArgumentList &TemplateArgs, |
8036 | TemplateSpecializationKind TSK, |
8037 | bool Complain = true); |
8038 | |
8039 | bool InstantiateEnum(SourceLocation PointOfInstantiation, |
8040 | EnumDecl *Instantiation, EnumDecl *Pattern, |
8041 | const MultiLevelTemplateArgumentList &TemplateArgs, |
8042 | TemplateSpecializationKind TSK); |
8043 | |
8044 | bool InstantiateInClassInitializer( |
8045 | SourceLocation PointOfInstantiation, FieldDecl *Instantiation, |
8046 | FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); |
8047 | |
8048 | struct LateInstantiatedAttribute { |
8049 | const Attr *TmplAttr; |
8050 | LocalInstantiationScope *Scope; |
8051 | Decl *NewDecl; |
8052 | |
8053 | LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, |
8054 | Decl *D) |
8055 | : TmplAttr(A), Scope(S), NewDecl(D) |
8056 | { } |
8057 | }; |
8058 | typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; |
8059 | |
8060 | void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, |
8061 | const Decl *Pattern, Decl *Inst, |
8062 | LateInstantiatedAttrVec *LateAttrs = nullptr, |
8063 | LocalInstantiationScope *OuterMostScope = nullptr); |
8064 | |
8065 | void |
8066 | InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, |
8067 | const Decl *Pattern, Decl *Inst, |
8068 | LateInstantiatedAttrVec *LateAttrs = nullptr, |
8069 | LocalInstantiationScope *OuterMostScope = nullptr); |
8070 | |
8071 | bool usesPartialOrExplicitSpecialization( |
8072 | SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); |
8073 | |
8074 | bool |
8075 | InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, |
8076 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
8077 | TemplateSpecializationKind TSK, |
8078 | bool Complain = true); |
8079 | |
8080 | void InstantiateClassMembers(SourceLocation PointOfInstantiation, |
8081 | CXXRecordDecl *Instantiation, |
8082 | const MultiLevelTemplateArgumentList &TemplateArgs, |
8083 | TemplateSpecializationKind TSK); |
8084 | |
8085 | void InstantiateClassTemplateSpecializationMembers( |
8086 | SourceLocation PointOfInstantiation, |
8087 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
8088 | TemplateSpecializationKind TSK); |
8089 | |
8090 | NestedNameSpecifierLoc |
8091 | SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, |
8092 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8093 | |
8094 | DeclarationNameInfo |
8095 | SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, |
8096 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8097 | TemplateName |
8098 | SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, |
8099 | SourceLocation Loc, |
8100 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8101 | bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, |
8102 | TemplateArgumentListInfo &Result, |
8103 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8104 | |
8105 | void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, |
8106 | FunctionDecl *Function); |
8107 | FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, |
8108 | const TemplateArgumentList *Args, |
8109 | SourceLocation Loc); |
8110 | void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, |
8111 | FunctionDecl *Function, |
8112 | bool Recursive = false, |
8113 | bool DefinitionRequired = false, |
8114 | bool AtEndOfTU = false); |
8115 | VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( |
8116 | VarTemplateDecl *VarTemplate, VarDecl *FromVar, |
8117 | const TemplateArgumentList &TemplateArgList, |
8118 | const TemplateArgumentListInfo &TemplateArgsInfo, |
8119 | SmallVectorImpl<TemplateArgument> &Converted, |
8120 | SourceLocation PointOfInstantiation, void *InsertPos, |
8121 | LateInstantiatedAttrVec *LateAttrs = nullptr, |
8122 | LocalInstantiationScope *StartingScope = nullptr); |
8123 | VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( |
8124 | VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, |
8125 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8126 | void |
8127 | BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, |
8128 | const MultiLevelTemplateArgumentList &TemplateArgs, |
8129 | LateInstantiatedAttrVec *LateAttrs, |
8130 | DeclContext *Owner, |
8131 | LocalInstantiationScope *StartingScope, |
8132 | bool InstantiatingVarTemplate = false, |
8133 | VarTemplateSpecializationDecl *PrevVTSD = nullptr); |
8134 | void InstantiateVariableInitializer( |
8135 | VarDecl *Var, VarDecl *OldVar, |
8136 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8137 | void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, |
8138 | VarDecl *Var, bool Recursive = false, |
8139 | bool DefinitionRequired = false, |
8140 | bool AtEndOfTU = false); |
8141 | |
8142 | void InstantiateMemInitializers(CXXConstructorDecl *New, |
8143 | const CXXConstructorDecl *Tmpl, |
8144 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8145 | |
8146 | NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, |
8147 | const MultiLevelTemplateArgumentList &TemplateArgs, |
8148 | bool FindingInstantiatedContext = false); |
8149 | DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, |
8150 | const MultiLevelTemplateArgumentList &TemplateArgs); |
8151 | |
8152 | // Objective-C declarations. |
8153 | enum ObjCContainerKind { |
8154 | OCK_None = -1, |
8155 | OCK_Interface = 0, |
8156 | OCK_Protocol, |
8157 | OCK_Category, |
8158 | OCK_ClassExtension, |
8159 | OCK_Implementation, |
8160 | OCK_CategoryImplementation |
8161 | }; |
8162 | ObjCContainerKind getObjCContainerKind() const; |
8163 | |
8164 | DeclResult actOnObjCTypeParam(Scope *S, |
8165 | ObjCTypeParamVariance variance, |
8166 | SourceLocation varianceLoc, |
8167 | unsigned index, |
8168 | IdentifierInfo *paramName, |
8169 | SourceLocation paramLoc, |
8170 | SourceLocation colonLoc, |
8171 | ParsedType typeBound); |
8172 | |
8173 | ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, |
8174 | ArrayRef<Decl *> typeParams, |
8175 | SourceLocation rAngleLoc); |
8176 | void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); |
8177 | |
8178 | Decl *ActOnStartClassInterface( |
8179 | Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, |
8180 | SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, |
8181 | IdentifierInfo *SuperName, SourceLocation SuperLoc, |
8182 | ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, |
8183 | Decl *const *ProtoRefs, unsigned NumProtoRefs, |
8184 | const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, |
8185 | const ParsedAttributesView &AttrList); |
8186 | |
8187 | void ActOnSuperClassOfClassInterface(Scope *S, |
8188 | SourceLocation AtInterfaceLoc, |
8189 | ObjCInterfaceDecl *IDecl, |
8190 | IdentifierInfo *ClassName, |
8191 | SourceLocation ClassLoc, |
8192 | IdentifierInfo *SuperName, |
8193 | SourceLocation SuperLoc, |
8194 | ArrayRef<ParsedType> SuperTypeArgs, |
8195 | SourceRange SuperTypeArgsRange); |
8196 | |
8197 | void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, |
8198 | SmallVectorImpl<SourceLocation> &ProtocolLocs, |
8199 | IdentifierInfo *SuperName, |
8200 | SourceLocation SuperLoc); |
8201 | |
8202 | Decl *ActOnCompatibilityAlias( |
8203 | SourceLocation AtCompatibilityAliasLoc, |
8204 | IdentifierInfo *AliasName, SourceLocation AliasLocation, |
8205 | IdentifierInfo *ClassName, SourceLocation ClassLocation); |
8206 | |
8207 | bool CheckForwardProtocolDeclarationForCircularDependency( |
8208 | IdentifierInfo *PName, |
8209 | SourceLocation &PLoc, SourceLocation PrevLoc, |
8210 | const ObjCList<ObjCProtocolDecl> &PList); |
8211 | |
8212 | Decl *ActOnStartProtocolInterface( |
8213 | SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, |
8214 | SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, |
8215 | unsigned NumProtoRefs, const SourceLocation *ProtoLocs, |
8216 | SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); |
8217 | |
8218 | Decl *ActOnStartCategoryInterface( |
8219 | SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, |
8220 | SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, |
8221 | IdentifierInfo *CategoryName, SourceLocation CategoryLoc, |
8222 | Decl *const *ProtoRefs, unsigned NumProtoRefs, |
8223 | const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, |
8224 | const ParsedAttributesView &AttrList); |
8225 | |
8226 | Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, |
8227 | IdentifierInfo *ClassName, |
8228 | SourceLocation ClassLoc, |
8229 | IdentifierInfo *SuperClassname, |
8230 | SourceLocation SuperClassLoc, |
8231 | const ParsedAttributesView &AttrList); |
8232 | |
8233 | Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, |
8234 | IdentifierInfo *ClassName, |
8235 | SourceLocation ClassLoc, |
8236 | IdentifierInfo *CatName, |
8237 | SourceLocation CatLoc, |
8238 | const ParsedAttributesView &AttrList); |
8239 | |
8240 | DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, |
8241 | ArrayRef<Decl *> Decls); |
8242 | |
8243 | DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, |
8244 | IdentifierInfo **IdentList, |
8245 | SourceLocation *IdentLocs, |
8246 | ArrayRef<ObjCTypeParamList *> TypeParamLists, |
8247 | unsigned NumElts); |
8248 | |
8249 | DeclGroupPtrTy |
8250 | ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, |
8251 | ArrayRef<IdentifierLocPair> IdentList, |
8252 | const ParsedAttributesView &attrList); |
8253 | |
8254 | void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, |
8255 | ArrayRef<IdentifierLocPair> ProtocolId, |
8256 | SmallVectorImpl<Decl *> &Protocols); |
8257 | |
8258 | void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, |
8259 | SourceLocation ProtocolLoc, |
8260 | IdentifierInfo *TypeArgId, |
8261 | SourceLocation TypeArgLoc, |
8262 | bool SelectProtocolFirst = false); |
8263 | |
8264 | /// Given a list of identifiers (and their locations), resolve the |
8265 | /// names to either Objective-C protocol qualifiers or type |
8266 | /// arguments, as appropriate. |
8267 | void actOnObjCTypeArgsOrProtocolQualifiers( |
8268 | Scope *S, |
8269 | ParsedType baseType, |
8270 | SourceLocation lAngleLoc, |
8271 | ArrayRef<IdentifierInfo *> identifiers, |
8272 | ArrayRef<SourceLocation> identifierLocs, |
8273 | SourceLocation rAngleLoc, |
8274 | SourceLocation &typeArgsLAngleLoc, |
8275 | SmallVectorImpl<ParsedType> &typeArgs, |
8276 | SourceLocation &typeArgsRAngleLoc, |
8277 | SourceLocation &protocolLAngleLoc, |
8278 | SmallVectorImpl<Decl *> &protocols, |
8279 | SourceLocation &protocolRAngleLoc, |
8280 | bool warnOnIncompleteProtocols); |
8281 | |
8282 | /// Build a an Objective-C protocol-qualified 'id' type where no |
8283 | /// base type was specified. |
8284 | TypeResult actOnObjCProtocolQualifierType( |
8285 | SourceLocation lAngleLoc, |
8286 | ArrayRef<Decl *> protocols, |
8287 | ArrayRef<SourceLocation> protocolLocs, |
8288 | SourceLocation rAngleLoc); |
8289 | |
8290 | /// Build a specialized and/or protocol-qualified Objective-C type. |
8291 | TypeResult actOnObjCTypeArgsAndProtocolQualifiers( |
8292 | Scope *S, |
8293 | SourceLocation Loc, |
8294 | ParsedType BaseType, |
8295 | SourceLocation TypeArgsLAngleLoc, |
8296 | ArrayRef<ParsedType> TypeArgs, |
8297 | SourceLocation TypeArgsRAngleLoc, |
8298 | SourceLocation ProtocolLAngleLoc, |
8299 | ArrayRef<Decl *> Protocols, |
8300 | ArrayRef<SourceLocation> ProtocolLocs, |
8301 | SourceLocation ProtocolRAngleLoc); |
8302 | |
8303 | /// Build an Objective-C type parameter type. |
8304 | QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, |
8305 | SourceLocation ProtocolLAngleLoc, |
8306 | ArrayRef<ObjCProtocolDecl *> Protocols, |
8307 | ArrayRef<SourceLocation> ProtocolLocs, |
8308 | SourceLocation ProtocolRAngleLoc, |
8309 | bool FailOnError = false); |
8310 | |
8311 | /// Build an Objective-C object pointer type. |
8312 | QualType BuildObjCObjectType(QualType BaseType, |
8313 | SourceLocation Loc, |
8314 | SourceLocation TypeArgsLAngleLoc, |
8315 | ArrayRef<TypeSourceInfo *> TypeArgs, |
8316 | SourceLocation TypeArgsRAngleLoc, |
8317 | SourceLocation ProtocolLAngleLoc, |
8318 | ArrayRef<ObjCProtocolDecl *> Protocols, |
8319 | ArrayRef<SourceLocation> ProtocolLocs, |
8320 | SourceLocation ProtocolRAngleLoc, |
8321 | bool FailOnError = false); |
8322 | |
8323 | /// Ensure attributes are consistent with type. |
8324 | /// \param [in, out] Attributes The attributes to check; they will |
8325 | /// be modified to be consistent with \p PropertyTy. |
8326 | void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, |
8327 | SourceLocation Loc, |
8328 | unsigned &Attributes, |
8329 | bool propertyInPrimaryClass); |
8330 | |
8331 | /// Process the specified property declaration and create decls for the |
8332 | /// setters and getters as needed. |
8333 | /// \param property The property declaration being processed |
8334 | void ProcessPropertyDecl(ObjCPropertyDecl *property); |
8335 | |
8336 | |
8337 | void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, |
8338 | ObjCPropertyDecl *SuperProperty, |
8339 | const IdentifierInfo *Name, |
8340 | bool OverridingProtocolProperty); |
8341 | |
8342 | void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, |
8343 | ObjCInterfaceDecl *ID); |
8344 | |
8345 | Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, |
8346 | ArrayRef<Decl *> allMethods = None, |
8347 | ArrayRef<DeclGroupPtrTy> allTUVars = None); |
8348 | |
8349 | Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, |
8350 | SourceLocation LParenLoc, |
8351 | FieldDeclarator &FD, ObjCDeclSpec &ODS, |
8352 | Selector GetterSel, Selector SetterSel, |
8353 | tok::ObjCKeywordKind MethodImplKind, |
8354 | DeclContext *lexicalDC = nullptr); |
8355 | |
8356 | Decl *ActOnPropertyImplDecl(Scope *S, |
8357 | SourceLocation AtLoc, |
8358 | SourceLocation PropertyLoc, |
8359 | bool ImplKind, |
8360 | IdentifierInfo *PropertyId, |
8361 | IdentifierInfo *PropertyIvar, |
8362 | SourceLocation PropertyIvarLoc, |
8363 | ObjCPropertyQueryKind QueryKind); |
8364 | |
8365 | enum ObjCSpecialMethodKind { |
8366 | OSMK_None, |
8367 | OSMK_Alloc, |
8368 | OSMK_New, |
8369 | OSMK_Copy, |
8370 | OSMK_RetainingInit, |
8371 | OSMK_NonRetainingInit |
8372 | }; |
8373 | |
8374 | struct ObjCArgInfo { |
8375 | IdentifierInfo *Name; |
8376 | SourceLocation NameLoc; |
8377 | // The Type is null if no type was specified, and the DeclSpec is invalid |
8378 | // in this case. |
8379 | ParsedType Type; |
8380 | ObjCDeclSpec DeclSpec; |
8381 | |
8382 | /// ArgAttrs - Attribute list for this argument. |
8383 | ParsedAttributesView ArgAttrs; |
8384 | }; |
8385 | |
8386 | Decl *ActOnMethodDeclaration( |
8387 | Scope *S, |
8388 | SourceLocation BeginLoc, // location of the + or -. |
8389 | SourceLocation EndLoc, // location of the ; or {. |
8390 | tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, |
8391 | ArrayRef<SourceLocation> SelectorLocs, Selector Sel, |
8392 | // optional arguments. The number of types/arguments is obtained |
8393 | // from the Sel.getNumArgs(). |
8394 | ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, |
8395 | unsigned CNumArgs, // c-style args |
8396 | const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, |
8397 | bool isVariadic, bool MethodDefinition); |
8398 | |
8399 | ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, |
8400 | const ObjCObjectPointerType *OPT, |
8401 | bool IsInstance); |
8402 | ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, |
8403 | bool IsInstance); |
8404 | |
8405 | bool CheckARCMethodDecl(ObjCMethodDecl *method); |
8406 | bool inferObjCARCLifetime(ValueDecl *decl); |
8407 | |
8408 | ExprResult |
8409 | HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, |
8410 | Expr *BaseExpr, |
8411 | SourceLocation OpLoc, |
8412 | DeclarationName MemberName, |
8413 | SourceLocation MemberLoc, |
8414 | SourceLocation SuperLoc, QualType SuperType, |
8415 | bool Super); |
8416 | |
8417 | ExprResult |
8418 | ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, |
8419 | IdentifierInfo &propertyName, |
8420 | SourceLocation receiverNameLoc, |
8421 | SourceLocation propertyNameLoc); |
8422 | |
8423 | ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); |
8424 | |
8425 | /// Describes the kind of message expression indicated by a message |
8426 | /// send that starts with an identifier. |
8427 | enum ObjCMessageKind { |
8428 | /// The message is sent to 'super'. |
8429 | ObjCSuperMessage, |
8430 | /// The message is an instance message. |
8431 | ObjCInstanceMessage, |
8432 | /// The message is a class message, and the identifier is a type |
8433 | /// name. |
8434 | ObjCClassMessage |
8435 | }; |
8436 | |
8437 | ObjCMessageKind getObjCMessageKind(Scope *S, |
8438 | IdentifierInfo *Name, |
8439 | SourceLocation NameLoc, |
8440 | bool IsSuper, |
8441 | bool HasTrailingDot, |
8442 | ParsedType &ReceiverType); |
8443 | |
8444 | ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, |
8445 | Selector Sel, |
8446 | SourceLocation LBracLoc, |
8447 | ArrayRef<SourceLocation> SelectorLocs, |
8448 | SourceLocation RBracLoc, |
8449 | MultiExprArg Args); |
8450 | |
8451 | ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, |
8452 | QualType ReceiverType, |
8453 | SourceLocation SuperLoc, |
8454 | Selector Sel, |
8455 | ObjCMethodDecl *Method, |
8456 | SourceLocation LBracLoc, |
8457 | ArrayRef<SourceLocation> SelectorLocs, |
8458 | SourceLocation RBracLoc, |
8459 | MultiExprArg Args, |
8460 | bool isImplicit = false); |
8461 | |
8462 | ExprResult BuildClassMessageImplicit(QualType ReceiverType, |
8463 | bool isSuperReceiver, |
8464 | SourceLocation Loc, |
8465 | Selector Sel, |
8466 | ObjCMethodDecl *Method, |
8467 | MultiExprArg Args); |
8468 | |
8469 | ExprResult ActOnClassMessage(Scope *S, |
8470 | ParsedType Receiver, |
8471 | Selector Sel, |
8472 | SourceLocation LBracLoc, |
8473 | ArrayRef<SourceLocation> SelectorLocs, |
8474 | SourceLocation RBracLoc, |
8475 | MultiExprArg Args); |
8476 | |
8477 | ExprResult BuildInstanceMessage(Expr *Receiver, |
8478 | QualType ReceiverType, |
8479 | SourceLocation SuperLoc, |
8480 | Selector Sel, |
8481 | ObjCMethodDecl *Method, |
8482 | SourceLocation LBracLoc, |
8483 | ArrayRef<SourceLocation> SelectorLocs, |
8484 | SourceLocation RBracLoc, |
8485 | MultiExprArg Args, |
8486 | bool isImplicit = false); |
8487 | |
8488 | ExprResult BuildInstanceMessageImplicit(Expr *Receiver, |
8489 | QualType ReceiverType, |
8490 | SourceLocation Loc, |
8491 | Selector Sel, |
8492 | ObjCMethodDecl *Method, |
8493 | MultiExprArg Args); |
8494 | |
8495 | ExprResult ActOnInstanceMessage(Scope *S, |
8496 | Expr *Receiver, |
8497 | Selector Sel, |
8498 | SourceLocation LBracLoc, |
8499 | ArrayRef<SourceLocation> SelectorLocs, |
8500 | SourceLocation RBracLoc, |
8501 | MultiExprArg Args); |
8502 | |
8503 | ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, |
8504 | ObjCBridgeCastKind Kind, |
8505 | SourceLocation BridgeKeywordLoc, |
8506 | TypeSourceInfo *TSInfo, |
8507 | Expr *SubExpr); |
8508 | |
8509 | ExprResult ActOnObjCBridgedCast(Scope *S, |
8510 | SourceLocation LParenLoc, |
8511 | ObjCBridgeCastKind Kind, |
8512 | SourceLocation BridgeKeywordLoc, |
8513 | ParsedType Type, |
8514 | SourceLocation RParenLoc, |
8515 | Expr *SubExpr); |
8516 | |
8517 | void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); |
8518 | |
8519 | void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); |
8520 | |
8521 | bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, |
8522 | CastKind &Kind); |
8523 | |
8524 | bool checkObjCBridgeRelatedComponents(SourceLocation Loc, |
8525 | QualType DestType, QualType SrcType, |
8526 | ObjCInterfaceDecl *&RelatedClass, |
8527 | ObjCMethodDecl *&ClassMethod, |
8528 | ObjCMethodDecl *&InstanceMethod, |
8529 | TypedefNameDecl *&TDNDecl, |
8530 | bool CfToNs, bool Diagnose = true); |
8531 | |
8532 | bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, |
8533 | QualType DestType, QualType SrcType, |
8534 | Expr *&SrcExpr, bool Diagnose = true); |
8535 | |
8536 | bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, |
8537 | bool Diagnose = true); |
8538 | |
8539 | bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); |
8540 | |
8541 | /// Check whether the given new method is a valid override of the |
8542 | /// given overridden method, and set any properties that should be inherited. |
8543 | void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, |
8544 | const ObjCMethodDecl *Overridden); |
8545 | |
8546 | /// Describes the compatibility of a result type with its method. |
8547 | enum ResultTypeCompatibilityKind { |
8548 | RTC_Compatible, |
8549 | RTC_Incompatible, |
8550 | RTC_Unknown |
8551 | }; |
8552 | |
8553 | void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, |
8554 | ObjCInterfaceDecl *CurrentClass, |
8555 | ResultTypeCompatibilityKind RTC); |
8556 | |
8557 | enum PragmaOptionsAlignKind { |
8558 | POAK_Native, // #pragma options align=native |
8559 | POAK_Natural, // #pragma options align=natural |
8560 | POAK_Packed, // #pragma options align=packed |
8561 | POAK_Power, // #pragma options align=power |
8562 | POAK_Mac68k, // #pragma options align=mac68k |
8563 | POAK_Reset // #pragma options align=reset |
8564 | }; |
8565 | |
8566 | /// ActOnPragmaClangSection - Called on well formed \#pragma clang section |
8567 | void ActOnPragmaClangSection(SourceLocation PragmaLoc, |
8568 | PragmaClangSectionAction Action, |
8569 | PragmaClangSectionKind SecKind, StringRef SecName); |
8570 | |
8571 | /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. |
8572 | void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, |
8573 | SourceLocation PragmaLoc); |
8574 | |
8575 | /// ActOnPragmaPack - Called on well formed \#pragma pack(...). |
8576 | void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, |
8577 | StringRef SlotLabel, Expr *Alignment); |
8578 | |
8579 | enum class PragmaPackDiagnoseKind { |
8580 | NonDefaultStateAtInclude, |
8581 | ChangedStateAtExit |
8582 | }; |
8583 | |
8584 | void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, |
8585 | SourceLocation IncludeLoc); |
8586 | void DiagnoseUnterminatedPragmaPack(); |
8587 | |
8588 | /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. |
8589 | void ActOnPragmaMSStruct(PragmaMSStructKind Kind); |
8590 | |
8591 | /// ActOnPragmaMSComment - Called on well formed |
8592 | /// \#pragma comment(kind, "arg"). |
8593 | void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, |
8594 | StringRef Arg); |
8595 | |
8596 | /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma |
8597 | /// pointers_to_members(representation method[, general purpose |
8598 | /// representation]). |
8599 | void ActOnPragmaMSPointersToMembers( |
8600 | LangOptions::PragmaMSPointersToMembersKind Kind, |
8601 | SourceLocation PragmaLoc); |
8602 | |
8603 | /// Called on well formed \#pragma vtordisp(). |
8604 | void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, |
8605 | SourceLocation PragmaLoc, |
8606 | MSVtorDispAttr::Mode Value); |
8607 | |
8608 | enum PragmaSectionKind { |
8609 | PSK_DataSeg, |
8610 | PSK_BSSSeg, |
8611 | PSK_ConstSeg, |
8612 | PSK_CodeSeg, |
8613 | }; |
8614 | |
8615 | bool UnifySection(StringRef SectionName, |
8616 | int SectionFlags, |
8617 | DeclaratorDecl *TheDecl); |
8618 | bool UnifySection(StringRef SectionName, |
8619 | int SectionFlags, |
8620 | SourceLocation PragmaSectionLocation); |
8621 | |
8622 | /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. |
8623 | void ActOnPragmaMSSeg(SourceLocation PragmaLocation, |
8624 | PragmaMsStackAction Action, |
8625 | llvm::StringRef StackSlotLabel, |
8626 | StringLiteral *SegmentName, |
8627 | llvm::StringRef PragmaName); |
8628 | |
8629 | /// Called on well formed \#pragma section(). |
8630 | void ActOnPragmaMSSection(SourceLocation PragmaLocation, |
8631 | int SectionFlags, StringLiteral *SegmentName); |
8632 | |
8633 | /// Called on well-formed \#pragma init_seg(). |
8634 | void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, |
8635 | StringLiteral *SegmentName); |
8636 | |
8637 | /// Called on #pragma clang __debug dump II |
8638 | void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); |
8639 | |
8640 | /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch |
8641 | void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, |
8642 | StringRef Value); |
8643 | |
8644 | /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. |
8645 | void ActOnPragmaUnused(const Token &Identifier, |
8646 | Scope *curScope, |
8647 | SourceLocation PragmaLoc); |
8648 | |
8649 | /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . |
8650 | void ActOnPragmaVisibility(const IdentifierInfo* VisType, |
8651 | SourceLocation PragmaLoc); |
8652 | |
8653 | NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, |
8654 | SourceLocation Loc); |
8655 | void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); |
8656 | |
8657 | /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. |
8658 | void ActOnPragmaWeakID(IdentifierInfo* WeakName, |
8659 | SourceLocation PragmaLoc, |
8660 | SourceLocation WeakNameLoc); |
8661 | |
8662 | /// ActOnPragmaRedefineExtname - Called on well formed |
8663 | /// \#pragma redefine_extname oldname newname. |
8664 | void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, |
8665 | IdentifierInfo* AliasName, |
8666 | SourceLocation PragmaLoc, |
8667 | SourceLocation WeakNameLoc, |
8668 | SourceLocation AliasNameLoc); |
8669 | |
8670 | /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. |
8671 | void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, |
8672 | IdentifierInfo* AliasName, |
8673 | SourceLocation PragmaLoc, |
8674 | SourceLocation WeakNameLoc, |
8675 | SourceLocation AliasNameLoc); |
8676 | |
8677 | /// ActOnPragmaFPContract - Called on well formed |
8678 | /// \#pragma {STDC,OPENCL} FP_CONTRACT and |
8679 | /// \#pragma clang fp contract |
8680 | void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC); |
8681 | |
8682 | /// ActOnPragmaFenvAccess - Called on well formed |
8683 | /// \#pragma STDC FENV_ACCESS |
8684 | void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC); |
8685 | |
8686 | /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to |
8687 | /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. |
8688 | void AddAlignmentAttributesForRecord(RecordDecl *RD); |
8689 | |
8690 | /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. |
8691 | void AddMsStructLayoutForRecord(RecordDecl *RD); |
8692 | |
8693 | /// FreePackedContext - Deallocate and null out PackContext. |
8694 | void FreePackedContext(); |
8695 | |
8696 | /// PushNamespaceVisibilityAttr - Note that we've entered a |
8697 | /// namespace with a visibility attribute. |
8698 | void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, |
8699 | SourceLocation Loc); |
8700 | |
8701 | /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, |
8702 | /// add an appropriate visibility attribute. |
8703 | void AddPushedVisibilityAttribute(Decl *RD); |
8704 | |
8705 | /// PopPragmaVisibility - Pop the top element of the visibility stack; used |
8706 | /// for '\#pragma GCC visibility' and visibility attributes on namespaces. |
8707 | void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); |
8708 | |
8709 | /// FreeVisContext - Deallocate and null out VisContext. |
8710 | void FreeVisContext(); |
8711 | |
8712 | /// AddCFAuditedAttribute - Check whether we're currently within |
8713 | /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding |
8714 | /// the appropriate attribute. |
8715 | void AddCFAuditedAttribute(Decl *D); |
8716 | |
8717 | void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, |
8718 | SourceLocation PragmaLoc, |
8719 | attr::ParsedSubjectMatchRuleSet Rules); |
8720 | void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, |
8721 | const IdentifierInfo *Namespace); |
8722 | |
8723 | /// Called on well-formed '\#pragma clang attribute pop'. |
8724 | void ActOnPragmaAttributePop(SourceLocation PragmaLoc, |
8725 | const IdentifierInfo *Namespace); |
8726 | |
8727 | /// Adds the attributes that have been specified using the |
8728 | /// '\#pragma clang attribute push' directives to the given declaration. |
8729 | void AddPragmaAttributes(Scope *S, Decl *D); |
8730 | |
8731 | void DiagnoseUnterminatedPragmaAttribute(); |
8732 | |
8733 | /// Called on well formed \#pragma clang optimize. |
8734 | void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); |
8735 | |
8736 | /// Get the location for the currently active "\#pragma clang optimize |
8737 | /// off". If this location is invalid, then the state of the pragma is "on". |
8738 | SourceLocation getOptimizeOffPragmaLocation() const { |
8739 | return OptimizeOffPragmaLocation; |
8740 | } |
8741 | |
8742 | /// Only called on function definitions; if there is a pragma in scope |
8743 | /// with the effect of a range-based optnone, consider marking the function |
8744 | /// with attribute optnone. |
8745 | void AddRangeBasedOptnone(FunctionDecl *FD); |
8746 | |
8747 | /// Adds the 'optnone' attribute to the function declaration if there |
8748 | /// are no conflicts; Loc represents the location causing the 'optnone' |
8749 | /// attribute to be added (usually because of a pragma). |
8750 | void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); |
8751 | |
8752 | /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. |
8753 | void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, |
8754 | unsigned SpellingListIndex, bool IsPackExpansion); |
8755 | void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, |
8756 | unsigned SpellingListIndex, bool IsPackExpansion); |
8757 | |
8758 | /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular |
8759 | /// declaration. |
8760 | void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, |
8761 | unsigned SpellingListIndex); |
8762 | |
8763 | /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular |
8764 | /// declaration. |
8765 | void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, |
8766 | unsigned SpellingListIndex); |
8767 | |
8768 | /// AddAlignValueAttr - Adds an align_value attribute to a particular |
8769 | /// declaration. |
8770 | void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, |
8771 | unsigned SpellingListIndex); |
8772 | |
8773 | /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular |
8774 | /// declaration. |
8775 | void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, |
8776 | Expr *MinBlocks, unsigned SpellingListIndex); |
8777 | |
8778 | /// AddModeAttr - Adds a mode attribute to a particular declaration. |
8779 | void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, |
8780 | unsigned SpellingListIndex, bool InInstantiation = false); |
8781 | |
8782 | void AddParameterABIAttr(SourceRange AttrRange, Decl *D, |
8783 | ParameterABI ABI, unsigned SpellingListIndex); |
8784 | |
8785 | enum class RetainOwnershipKind {NS, CF, OS}; |
8786 | void AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex, |
8787 | RetainOwnershipKind K, bool IsTemplateInstantiation); |
8788 | |
8789 | /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size |
8790 | /// attribute to a particular declaration. |
8791 | void addAMDGPUFlatWorkGroupSizeAttr(SourceRange AttrRange, Decl *D, Expr *Min, |
8792 | Expr *Max, unsigned SpellingListIndex); |
8793 | |
8794 | /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a |
8795 | /// particular declaration. |
8796 | void addAMDGPUWavesPerEUAttr(SourceRange AttrRange, Decl *D, Expr *Min, |
8797 | Expr *Max, unsigned SpellingListIndex); |
8798 | |
8799 | bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); |
8800 | |
8801 | //===--------------------------------------------------------------------===// |
8802 | // C++ Coroutines TS |
8803 | // |
8804 | bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, |
8805 | StringRef Keyword); |
8806 | ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); |
8807 | ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); |
8808 | StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); |
8809 | |
8810 | ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, |
8811 | bool IsImplicit = false); |
8812 | ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, |
8813 | UnresolvedLookupExpr* Lookup); |
8814 | ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); |
8815 | StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, |
8816 | bool IsImplicit = false); |
8817 | StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); |
8818 | bool buildCoroutineParameterMoves(SourceLocation Loc); |
8819 | VarDecl *buildCoroutinePromise(SourceLocation Loc); |
8820 | void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); |
8821 | ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, |
8822 | SourceLocation FuncLoc); |
8823 | |
8824 | //===--------------------------------------------------------------------===// |
8825 | // OpenCL extensions. |
8826 | // |
8827 | private: |
8828 | std::string CurrOpenCLExtension; |
8829 | /// Extensions required by an OpenCL type. |
8830 | llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; |
8831 | /// Extensions required by an OpenCL declaration. |
8832 | llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; |
8833 | public: |
8834 | llvm::StringRef getCurrentOpenCLExtension() const { |
8835 | return CurrOpenCLExtension; |
8836 | } |
8837 | |
8838 | /// Check if a function declaration \p FD associates with any |
8839 | /// extensions present in OpenCLDeclExtMap and if so return the |
8840 | /// extension(s) name(s). |
8841 | std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); |
8842 | |
8843 | /// Check if a function type \p FT associates with any |
8844 | /// extensions present in OpenCLTypeExtMap and if so return the |
8845 | /// extension(s) name(s). |
8846 | std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); |
8847 | |
8848 | /// Find an extension in an appropriate extension map and return its name |
8849 | template<typename T, typename MapT> |
8850 | std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); |
8851 | |
8852 | void setCurrentOpenCLExtension(llvm::StringRef Ext) { |
8853 | CurrOpenCLExtension = Ext; |
8854 | } |
8855 | |
8856 | /// Set OpenCL extensions for a type which can only be used when these |
8857 | /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. |
8858 | /// \param Exts A space separated list of OpenCL extensions. |
8859 | void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); |
8860 | |
8861 | /// Set OpenCL extensions for a declaration which can only be |
8862 | /// used when these OpenCL extensions are enabled. If \p Exts is empty, do |
8863 | /// nothing. |
8864 | /// \param Exts A space separated list of OpenCL extensions. |
8865 | void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); |
8866 | |
8867 | /// Set current OpenCL extensions for a type which can only be used |
8868 | /// when these OpenCL extensions are enabled. If current OpenCL extension is |
8869 | /// empty, do nothing. |
8870 | void setCurrentOpenCLExtensionForType(QualType T); |
8871 | |
8872 | /// Set current OpenCL extensions for a declaration which |
8873 | /// can only be used when these OpenCL extensions are enabled. If current |
8874 | /// OpenCL extension is empty, do nothing. |
8875 | void setCurrentOpenCLExtensionForDecl(Decl *FD); |
8876 | |
8877 | bool isOpenCLDisabledDecl(Decl *FD); |
8878 | |
8879 | /// Check if type \p T corresponding to declaration specifier \p DS |
8880 | /// is disabled due to required OpenCL extensions being disabled. If so, |
8881 | /// emit diagnostics. |
8882 | /// \return true if type is disabled. |
8883 | bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); |
8884 | |
8885 | /// Check if declaration \p D used by expression \p E |
8886 | /// is disabled due to required OpenCL extensions being disabled. If so, |
8887 | /// emit diagnostics. |
8888 | /// \return true if type is disabled. |
8889 | bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); |
8890 | |
8891 | //===--------------------------------------------------------------------===// |
8892 | // OpenMP directives and clauses. |
8893 | // |
8894 | private: |
8895 | void *VarDataSharingAttributesStack; |
8896 | /// Number of nested '#pragma omp declare target' directives. |
8897 | unsigned DeclareTargetNestingLevel = 0; |
8898 | /// Initialization of data-sharing attributes stack. |
8899 | void InitDataSharingAttributesStack(); |
8900 | void DestroyDataSharingAttributesStack(); |
8901 | ExprResult |
8902 | VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, |
8903 | bool StrictlyPositive = true); |
8904 | /// Returns OpenMP nesting level for current directive. |
8905 | unsigned getOpenMPNestingLevel() const; |
8906 | |
8907 | /// Adjusts the function scopes index for the target-based regions. |
8908 | void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, |
8909 | unsigned Level) const; |
8910 | |
8911 | /// Push new OpenMP function region for non-capturing function. |
8912 | void pushOpenMPFunctionRegion(); |
8913 | |
8914 | /// Pop OpenMP function region for non-capturing function. |
8915 | void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); |
8916 | |
8917 | /// Check whether we're allowed to call Callee from the current function. |
8918 | void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); |
8919 | |
8920 | /// Check if the expression is allowed to be used in expressions for the |
8921 | /// OpenMP devices. |
8922 | void checkOpenMPDeviceExpr(const Expr *E); |
8923 | |
8924 | /// Checks if a type or a declaration is disabled due to the owning extension |
8925 | /// being disabled, and emits diagnostic messages if it is disabled. |
8926 | /// \param D type or declaration to be checked. |
8927 | /// \param DiagLoc source location for the diagnostic message. |
8928 | /// \param DiagInfo information to be emitted for the diagnostic message. |
8929 | /// \param SrcRange source range of the declaration. |
8930 | /// \param Map maps type or declaration to the extensions. |
8931 | /// \param Selector selects diagnostic message: 0 for type and 1 for |
8932 | /// declaration. |
8933 | /// \return true if the type or declaration is disabled. |
8934 | template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> |
8935 | bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, |
8936 | MapT &Map, unsigned Selector = 0, |
8937 | SourceRange SrcRange = SourceRange()); |
8938 | |
8939 | public: |
8940 | /// Return true if the provided declaration \a VD should be captured by |
8941 | /// reference. |
8942 | /// \param Level Relative level of nested OpenMP construct for that the check |
8943 | /// is performed. |
8944 | bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const; |
8945 | |
8946 | /// Check if the specified variable is used in one of the private |
8947 | /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP |
8948 | /// constructs. |
8949 | VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, |
8950 | unsigned StopAt = 0); |
8951 | ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, |
8952 | ExprObjectKind OK, SourceLocation Loc); |
8953 | |
8954 | /// If the current region is a loop-based region, mark the start of the loop |
8955 | /// construct. |
8956 | void startOpenMPLoop(); |
8957 | |
8958 | /// Check if the specified variable is used in 'private' clause. |
8959 | /// \param Level Relative level of nested OpenMP construct for that the check |
8960 | /// is performed. |
8961 | bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const; |
8962 | |
8963 | /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) |
8964 | /// for \p FD based on DSA for the provided corresponding captured declaration |
8965 | /// \p D. |
8966 | void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); |
8967 | |
8968 | /// Check if the specified variable is captured by 'target' directive. |
8969 | /// \param Level Relative level of nested OpenMP construct for that the check |
8970 | /// is performed. |
8971 | bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const; |
8972 | |
8973 | ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, |
8974 | Expr *Op); |
8975 | /// Called on start of new data sharing attribute block. |
8976 | void StartOpenMPDSABlock(OpenMPDirectiveKind K, |
8977 | const DeclarationNameInfo &DirName, Scope *CurScope, |
8978 | SourceLocation Loc); |
8979 | /// Start analysis of clauses. |
8980 | void StartOpenMPClause(OpenMPClauseKind K); |
8981 | /// End analysis of clauses. |
8982 | void EndOpenMPClause(); |
8983 | /// Called on end of data sharing attribute block. |
8984 | void EndOpenMPDSABlock(Stmt *CurDirective); |
8985 | |
8986 | /// Check if the current region is an OpenMP loop region and if it is, |
8987 | /// mark loop control variable, used in \p Init for loop initialization, as |
8988 | /// private by default. |
8989 | /// \param Init First part of the for loop. |
8990 | void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); |
8991 | |
8992 | // OpenMP directives and clauses. |
8993 | /// Called on correct id-expression from the '#pragma omp |
8994 | /// threadprivate'. |
8995 | ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, |
8996 | const DeclarationNameInfo &Id, |
8997 | OpenMPDirectiveKind Kind); |
8998 | /// Called on well-formed '#pragma omp threadprivate'. |
8999 | DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( |
9000 | SourceLocation Loc, |
9001 | ArrayRef<Expr *> VarList); |
9002 | /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. |
9003 | OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, |
9004 | ArrayRef<Expr *> VarList); |
9005 | /// Called on well-formed '#pragma omp allocate'. |
9006 | DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, |
9007 | ArrayRef<Expr *> VarList, |
9008 | ArrayRef<OMPClause *> Clauses, |
9009 | DeclContext *Owner = nullptr); |
9010 | /// Called on well-formed '#pragma omp requires'. |
9011 | DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, |
9012 | ArrayRef<OMPClause *> ClauseList); |
9013 | /// Check restrictions on Requires directive |
9014 | OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, |
9015 | ArrayRef<OMPClause *> Clauses); |
9016 | /// Check if the specified type is allowed to be used in 'omp declare |
9017 | /// reduction' construct. |
9018 | QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, |
9019 | TypeResult ParsedType); |
9020 | /// Called on start of '#pragma omp declare reduction'. |
9021 | DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( |
9022 | Scope *S, DeclContext *DC, DeclarationName Name, |
9023 | ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, |
9024 | AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); |
9025 | /// Initialize declare reduction construct initializer. |
9026 | void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); |
9027 | /// Finish current declare reduction construct initializer. |
9028 | void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); |
9029 | /// Initialize declare reduction construct initializer. |
9030 | /// \return omp_priv variable. |
9031 | VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); |
9032 | /// Finish current declare reduction construct initializer. |
9033 | void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, |
9034 | VarDecl *OmpPrivParm); |
9035 | /// Called at the end of '#pragma omp declare reduction'. |
9036 | DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( |
9037 | Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); |
9038 | |
9039 | /// Check variable declaration in 'omp declare mapper' construct. |
9040 | TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); |
9041 | /// Check if the specified type is allowed to be used in 'omp declare |
9042 | /// mapper' construct. |
9043 | QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, |
9044 | TypeResult ParsedType); |
9045 | /// Called on start of '#pragma omp declare mapper'. |
9046 | OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( |
9047 | Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, |
9048 | SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, |
9049 | Decl *PrevDeclInScope = nullptr); |
9050 | /// Build the mapper variable of '#pragma omp declare mapper'. |
9051 | void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, |
9052 | Scope *S, QualType MapperType, |
9053 | SourceLocation StartLoc, |
9054 | DeclarationName VN); |
9055 | /// Called at the end of '#pragma omp declare mapper'. |
9056 | DeclGroupPtrTy |
9057 | ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, |
9058 | ArrayRef<OMPClause *> ClauseList); |
9059 | |
9060 | /// Called on the start of target region i.e. '#pragma omp declare target'. |
9061 | bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); |
9062 | /// Called at the end of target region i.e. '#pragme omp end declare target'. |
9063 | void ActOnFinishOpenMPDeclareTargetDirective(); |
9064 | /// Called on correct id-expression from the '#pragma omp declare target'. |
9065 | void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, |
9066 | const DeclarationNameInfo &Id, |
9067 | OMPDeclareTargetDeclAttr::MapTypeTy MT, |
9068 | NamedDeclSetType &SameDirectiveDecls); |
9069 | /// Check declaration inside target region. |
9070 | void |
9071 | checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, |
9072 | SourceLocation IdLoc = SourceLocation()); |
9073 | /// Return true inside OpenMP declare target region. |
9074 | bool isInOpenMPDeclareTargetContext() const { |
9075 | return DeclareTargetNestingLevel > 0; |
9076 | } |
9077 | /// Return true inside OpenMP target region. |
9078 | bool isInOpenMPTargetExecutionDirective() const; |
9079 | /// Return true if (un)supported features for the current target should be |
9080 | /// diagnosed if OpenMP (offloading) is enabled. |
9081 | bool shouldDiagnoseTargetSupportFromOpenMP() const { |
9082 | return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() || |
9083 | isInOpenMPTargetExecutionDirective(); |
9084 | } |
9085 | |
9086 | /// Return the number of captured regions created for an OpenMP directive. |
9087 | static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); |
9088 | |
9089 | /// Initialization of captured region for OpenMP region. |
9090 | void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); |
9091 | /// End of OpenMP region. |
9092 | /// |
9093 | /// \param S Statement associated with the current OpenMP region. |
9094 | /// \param Clauses List of clauses for the current OpenMP region. |
9095 | /// |
9096 | /// \returns Statement for finished OpenMP region. |
9097 | StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); |
9098 | StmtResult ActOnOpenMPExecutableDirective( |
9099 | OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, |
9100 | OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, |
9101 | Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); |
9102 | /// Called on well-formed '\#pragma omp parallel' after parsing |
9103 | /// of the associated statement. |
9104 | StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, |
9105 | Stmt *AStmt, |
9106 | SourceLocation StartLoc, |
9107 | SourceLocation EndLoc); |
9108 | using VarsWithInheritedDSAType = |
9109 | llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; |
9110 | /// Called on well-formed '\#pragma omp simd' after parsing |
9111 | /// of the associated statement. |
9112 | StmtResult |
9113 | ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, |
9114 | SourceLocation StartLoc, SourceLocation EndLoc, |
9115 | VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9116 | /// Called on well-formed '\#pragma omp for' after parsing |
9117 | /// of the associated statement. |
9118 | StmtResult |
9119 | ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, |
9120 | SourceLocation StartLoc, SourceLocation EndLoc, |
9121 | VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9122 | /// Called on well-formed '\#pragma omp for simd' after parsing |
9123 | /// of the associated statement. |
9124 | StmtResult |
9125 | ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, |
9126 | SourceLocation StartLoc, SourceLocation EndLoc, |
9127 | VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9128 | /// Called on well-formed '\#pragma omp sections' after parsing |
9129 | /// of the associated statement. |
9130 | StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, |
9131 | Stmt *AStmt, SourceLocation StartLoc, |
9132 | SourceLocation EndLoc); |
9133 | /// Called on well-formed '\#pragma omp section' after parsing of the |
9134 | /// associated statement. |
9135 | StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, |
9136 | SourceLocation EndLoc); |
9137 | /// Called on well-formed '\#pragma omp single' after parsing of the |
9138 | /// associated statement. |
9139 | StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, |
9140 | Stmt *AStmt, SourceLocation StartLoc, |
9141 | SourceLocation EndLoc); |
9142 | /// Called on well-formed '\#pragma omp master' after parsing of the |
9143 | /// associated statement. |
9144 | StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, |
9145 | SourceLocation EndLoc); |
9146 | /// Called on well-formed '\#pragma omp critical' after parsing of the |
9147 | /// associated statement. |
9148 | StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, |
9149 | ArrayRef<OMPClause *> Clauses, |
9150 | Stmt *AStmt, SourceLocation StartLoc, |
9151 | SourceLocation EndLoc); |
9152 | /// Called on well-formed '\#pragma omp parallel for' after parsing |
9153 | /// of the associated statement. |
9154 | StmtResult ActOnOpenMPParallelForDirective( |
9155 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9156 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9157 | /// Called on well-formed '\#pragma omp parallel for simd' after |
9158 | /// parsing of the associated statement. |
9159 | StmtResult ActOnOpenMPParallelForSimdDirective( |
9160 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9161 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9162 | /// Called on well-formed '\#pragma omp parallel sections' after |
9163 | /// parsing of the associated statement. |
9164 | StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, |
9165 | Stmt *AStmt, |
9166 | SourceLocation StartLoc, |
9167 | SourceLocation EndLoc); |
9168 | /// Called on well-formed '\#pragma omp task' after parsing of the |
9169 | /// associated statement. |
9170 | StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, |
9171 | Stmt *AStmt, SourceLocation StartLoc, |
9172 | SourceLocation EndLoc); |
9173 | /// Called on well-formed '\#pragma omp taskyield'. |
9174 | StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, |
9175 | SourceLocation EndLoc); |
9176 | /// Called on well-formed '\#pragma omp barrier'. |
9177 | StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, |
9178 | SourceLocation EndLoc); |
9179 | /// Called on well-formed '\#pragma omp taskwait'. |
9180 | StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, |
9181 | SourceLocation EndLoc); |
9182 | /// Called on well-formed '\#pragma omp taskgroup'. |
9183 | StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, |
9184 | Stmt *AStmt, SourceLocation StartLoc, |
9185 | SourceLocation EndLoc); |
9186 | /// Called on well-formed '\#pragma omp flush'. |
9187 | StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, |
9188 | SourceLocation StartLoc, |
9189 | SourceLocation EndLoc); |
9190 | /// Called on well-formed '\#pragma omp ordered' after parsing of the |
9191 | /// associated statement. |
9192 | StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, |
9193 | Stmt *AStmt, SourceLocation StartLoc, |
9194 | SourceLocation EndLoc); |
9195 | /// Called on well-formed '\#pragma omp atomic' after parsing of the |
9196 | /// associated statement. |
9197 | StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, |
9198 | Stmt *AStmt, SourceLocation StartLoc, |
9199 | SourceLocation EndLoc); |
9200 | /// Called on well-formed '\#pragma omp target' after parsing of the |
9201 | /// associated statement. |
9202 | StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, |
9203 | Stmt *AStmt, SourceLocation StartLoc, |
9204 | SourceLocation EndLoc); |
9205 | /// Called on well-formed '\#pragma omp target data' after parsing of |
9206 | /// the associated statement. |
9207 | StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, |
9208 | Stmt *AStmt, SourceLocation StartLoc, |
9209 | SourceLocation EndLoc); |
9210 | /// Called on well-formed '\#pragma omp target enter data' after |
9211 | /// parsing of the associated statement. |
9212 | StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, |
9213 | SourceLocation StartLoc, |
9214 | SourceLocation EndLoc, |
9215 | Stmt *AStmt); |
9216 | /// Called on well-formed '\#pragma omp target exit data' after |
9217 | /// parsing of the associated statement. |
9218 | StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, |
9219 | SourceLocation StartLoc, |
9220 | SourceLocation EndLoc, |
9221 | Stmt *AStmt); |
9222 | /// Called on well-formed '\#pragma omp target parallel' after |
9223 | /// parsing of the associated statement. |
9224 | StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, |
9225 | Stmt *AStmt, |
9226 | SourceLocation StartLoc, |
9227 | SourceLocation EndLoc); |
9228 | /// Called on well-formed '\#pragma omp target parallel for' after |
9229 | /// parsing of the associated statement. |
9230 | StmtResult ActOnOpenMPTargetParallelForDirective( |
9231 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9232 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9233 | /// Called on well-formed '\#pragma omp teams' after parsing of the |
9234 | /// associated statement. |
9235 | StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, |
9236 | Stmt *AStmt, SourceLocation StartLoc, |
9237 | SourceLocation EndLoc); |
9238 | /// Called on well-formed '\#pragma omp cancellation point'. |
9239 | StmtResult |
9240 | ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, |
9241 | SourceLocation EndLoc, |
9242 | OpenMPDirectiveKind CancelRegion); |
9243 | /// Called on well-formed '\#pragma omp cancel'. |
9244 | StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, |
9245 | SourceLocation StartLoc, |
9246 | SourceLocation EndLoc, |
9247 | OpenMPDirectiveKind CancelRegion); |
9248 | /// Called on well-formed '\#pragma omp taskloop' after parsing of the |
9249 | /// associated statement. |
9250 | StmtResult |
9251 | ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, |
9252 | SourceLocation StartLoc, SourceLocation EndLoc, |
9253 | VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9254 | /// Called on well-formed '\#pragma omp taskloop simd' after parsing of |
9255 | /// the associated statement. |
9256 | StmtResult ActOnOpenMPTaskLoopSimdDirective( |
9257 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9258 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9259 | /// Called on well-formed '\#pragma omp distribute' after parsing |
9260 | /// of the associated statement. |
9261 | StmtResult |
9262 | ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, |
9263 | SourceLocation StartLoc, SourceLocation EndLoc, |
9264 | VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9265 | /// Called on well-formed '\#pragma omp target update'. |
9266 | StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, |
9267 | SourceLocation StartLoc, |
9268 | SourceLocation EndLoc, |
9269 | Stmt *AStmt); |
9270 | /// Called on well-formed '\#pragma omp distribute parallel for' after |
9271 | /// parsing of the associated statement. |
9272 | StmtResult ActOnOpenMPDistributeParallelForDirective( |
9273 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9274 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9275 | /// Called on well-formed '\#pragma omp distribute parallel for simd' |
9276 | /// after parsing of the associated statement. |
9277 | StmtResult ActOnOpenMPDistributeParallelForSimdDirective( |
9278 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9279 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9280 | /// Called on well-formed '\#pragma omp distribute simd' after |
9281 | /// parsing of the associated statement. |
9282 | StmtResult ActOnOpenMPDistributeSimdDirective( |
9283 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9284 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9285 | /// Called on well-formed '\#pragma omp target parallel for simd' after |
9286 | /// parsing of the associated statement. |
9287 | StmtResult ActOnOpenMPTargetParallelForSimdDirective( |
9288 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9289 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9290 | /// Called on well-formed '\#pragma omp target simd' after parsing of |
9291 | /// the associated statement. |
9292 | StmtResult |
9293 | ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, |
9294 | SourceLocation StartLoc, SourceLocation EndLoc, |
9295 | VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9296 | /// Called on well-formed '\#pragma omp teams distribute' after parsing of |
9297 | /// the associated statement. |
9298 | StmtResult ActOnOpenMPTeamsDistributeDirective( |
9299 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9300 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9301 | /// Called on well-formed '\#pragma omp teams distribute simd' after parsing |
9302 | /// of the associated statement. |
9303 | StmtResult ActOnOpenMPTeamsDistributeSimdDirective( |
9304 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9305 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9306 | /// Called on well-formed '\#pragma omp teams distribute parallel for simd' |
9307 | /// after parsing of the associated statement. |
9308 | StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( |
9309 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9310 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9311 | /// Called on well-formed '\#pragma omp teams distribute parallel for' |
9312 | /// after parsing of the associated statement. |
9313 | StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( |
9314 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9315 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9316 | /// Called on well-formed '\#pragma omp target teams' after parsing of the |
9317 | /// associated statement. |
9318 | StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, |
9319 | Stmt *AStmt, |
9320 | SourceLocation StartLoc, |
9321 | SourceLocation EndLoc); |
9322 | /// Called on well-formed '\#pragma omp target teams distribute' after parsing |
9323 | /// of the associated statement. |
9324 | StmtResult ActOnOpenMPTargetTeamsDistributeDirective( |
9325 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9326 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9327 | /// Called on well-formed '\#pragma omp target teams distribute parallel for' |
9328 | /// after parsing of the associated statement. |
9329 | StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( |
9330 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9331 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9332 | /// Called on well-formed '\#pragma omp target teams distribute parallel for |
9333 | /// simd' after parsing of the associated statement. |
9334 | StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( |
9335 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9336 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9337 | /// Called on well-formed '\#pragma omp target teams distribute simd' after |
9338 | /// parsing of the associated statement. |
9339 | StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( |
9340 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
9341 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); |
9342 | |
9343 | /// Checks correctness of linear modifiers. |
9344 | bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, |
9345 | SourceLocation LinLoc); |
9346 | /// Checks that the specified declaration matches requirements for the linear |
9347 | /// decls. |
9348 | bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, |
9349 | OpenMPLinearClauseKind LinKind, QualType Type); |
9350 | |
9351 | /// Called on well-formed '\#pragma omp declare simd' after parsing of |
9352 | /// the associated method/function. |
9353 | DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( |
9354 | DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, |
9355 | Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, |
9356 | ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, |
9357 | ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); |
9358 | |
9359 | OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, |
9360 | Expr *Expr, |
9361 | SourceLocation StartLoc, |
9362 | SourceLocation LParenLoc, |
9363 | SourceLocation EndLoc); |
9364 | /// Called on well-formed 'allocator' clause. |
9365 | OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, |
9366 | SourceLocation StartLoc, |
9367 | SourceLocation LParenLoc, |
9368 | SourceLocation EndLoc); |
9369 | /// Called on well-formed 'if' clause. |
9370 | OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, |
9371 | Expr *Condition, SourceLocation StartLoc, |
9372 | SourceLocation LParenLoc, |
9373 | SourceLocation NameModifierLoc, |
9374 | SourceLocation ColonLoc, |
9375 | SourceLocation EndLoc); |
9376 | /// Called on well-formed 'final' clause. |
9377 | OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, |
9378 | SourceLocation LParenLoc, |
9379 | SourceLocation EndLoc); |
9380 | /// Called on well-formed 'num_threads' clause. |
9381 | OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, |
9382 | SourceLocation StartLoc, |
9383 | SourceLocation LParenLoc, |
9384 | SourceLocation EndLoc); |
9385 | /// Called on well-formed 'safelen' clause. |
9386 | OMPClause *ActOnOpenMPSafelenClause(Expr *Length, |
9387 | SourceLocation StartLoc, |
9388 | SourceLocation LParenLoc, |
9389 | SourceLocation EndLoc); |
9390 | /// Called on well-formed 'simdlen' clause. |
9391 | OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, |
9392 | SourceLocation LParenLoc, |
9393 | SourceLocation EndLoc); |
9394 | /// Called on well-formed 'collapse' clause. |
9395 | OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, |
9396 | SourceLocation StartLoc, |
9397 | SourceLocation LParenLoc, |
9398 | SourceLocation EndLoc); |
9399 | /// Called on well-formed 'ordered' clause. |
9400 | OMPClause * |
9401 | ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, |
9402 | SourceLocation LParenLoc = SourceLocation(), |
9403 | Expr *NumForLoops = nullptr); |
9404 | /// Called on well-formed 'grainsize' clause. |
9405 | OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, |
9406 | SourceLocation LParenLoc, |
9407 | SourceLocation EndLoc); |
9408 | /// Called on well-formed 'num_tasks' clause. |
9409 | OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, |
9410 | SourceLocation LParenLoc, |
9411 | SourceLocation EndLoc); |
9412 | /// Called on well-formed 'hint' clause. |
9413 | OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, |
9414 | SourceLocation LParenLoc, |
9415 | SourceLocation EndLoc); |
9416 | |
9417 | OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, |
9418 | unsigned Argument, |
9419 | SourceLocation ArgumentLoc, |
9420 | SourceLocation StartLoc, |
9421 | SourceLocation LParenLoc, |
9422 | SourceLocation EndLoc); |
9423 | /// Called on well-formed 'default' clause. |
9424 | OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, |
9425 | SourceLocation KindLoc, |
9426 | SourceLocation StartLoc, |
9427 | SourceLocation LParenLoc, |
9428 | SourceLocation EndLoc); |
9429 | /// Called on well-formed 'proc_bind' clause. |
9430 | OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, |
9431 | SourceLocation KindLoc, |
9432 | SourceLocation StartLoc, |
9433 | SourceLocation LParenLoc, |
9434 | SourceLocation EndLoc); |
9435 | |
9436 | OMPClause *ActOnOpenMPSingleExprWithArgClause( |
9437 | OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, |
9438 | SourceLocation StartLoc, SourceLocation LParenLoc, |
9439 | ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, |
9440 | SourceLocation EndLoc); |
9441 | /// Called on well-formed 'schedule' clause. |
9442 | OMPClause *ActOnOpenMPScheduleClause( |
9443 | OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, |
9444 | OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, |
9445 | SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, |
9446 | SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); |
9447 | |
9448 | OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, |
9449 | SourceLocation EndLoc); |
9450 | /// Called on well-formed 'nowait' clause. |
9451 | OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, |
9452 | SourceLocation EndLoc); |
9453 | /// Called on well-formed 'untied' clause. |
9454 | OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, |
9455 | SourceLocation EndLoc); |
9456 | /// Called on well-formed 'mergeable' clause. |
9457 | OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, |
9458 | SourceLocation EndLoc); |
9459 | /// Called on well-formed 'read' clause. |
9460 | OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, |
9461 | SourceLocation EndLoc); |
9462 | /// Called on well-formed 'write' clause. |
9463 | OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, |
9464 | SourceLocation EndLoc); |
9465 | /// Called on well-formed 'update' clause. |
9466 | OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, |
9467 | SourceLocation EndLoc); |
9468 | /// Called on well-formed 'capture' clause. |
9469 | OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, |
9470 | SourceLocation EndLoc); |
9471 | /// Called on well-formed 'seq_cst' clause. |
9472 | OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, |
9473 | SourceLocation EndLoc); |
9474 | /// Called on well-formed 'threads' clause. |
9475 | OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, |
9476 | SourceLocation EndLoc); |
9477 | /// Called on well-formed 'simd' clause. |
9478 | OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, |
9479 | SourceLocation EndLoc); |
9480 | /// Called on well-formed 'nogroup' clause. |
9481 | OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, |
9482 | SourceLocation EndLoc); |
9483 | /// Called on well-formed 'unified_address' clause. |
9484 | OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, |
9485 | SourceLocation EndLoc); |
9486 | |
9487 | /// Called on well-formed 'unified_address' clause. |
9488 | OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, |
9489 | SourceLocation EndLoc); |
9490 | |
9491 | /// Called on well-formed 'reverse_offload' clause. |
9492 | OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, |
9493 | SourceLocation EndLoc); |
9494 | |
9495 | /// Called on well-formed 'dynamic_allocators' clause. |
9496 | OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, |
9497 | SourceLocation EndLoc); |
9498 | |
9499 | /// Called on well-formed 'atomic_default_mem_order' clause. |
9500 | OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( |
9501 | OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, |
9502 | SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); |
9503 | |
9504 | OMPClause *ActOnOpenMPVarListClause( |
9505 | OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, |
9506 | const OMPVarListLocTy &Locs, SourceLocation ColonLoc, |
9507 | CXXScopeSpec &ReductionOrMapperIdScopeSpec, |
9508 | DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind, |
9509 | OpenMPLinearClauseKind LinKind, |
9510 | ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, |
9511 | ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, |
9512 | bool IsMapTypeImplicit, SourceLocation DepLinMapLoc); |
9513 | /// Called on well-formed 'allocate' clause. |
9514 | OMPClause * |
9515 | ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, |
9516 | SourceLocation StartLoc, SourceLocation ColonLoc, |
9517 | SourceLocation LParenLoc, SourceLocation EndLoc); |
9518 | /// Called on well-formed 'private' clause. |
9519 | OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, |
9520 | SourceLocation StartLoc, |
9521 | SourceLocation LParenLoc, |
9522 | SourceLocation EndLoc); |
9523 | /// Called on well-formed 'firstprivate' clause. |
9524 | OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, |
9525 | SourceLocation StartLoc, |
9526 | SourceLocation LParenLoc, |
9527 | SourceLocation EndLoc); |
9528 | /// Called on well-formed 'lastprivate' clause. |
9529 | OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, |
9530 | SourceLocation StartLoc, |
9531 | SourceLocation LParenLoc, |
9532 | SourceLocation EndLoc); |
9533 | /// Called on well-formed 'shared' clause. |
9534 | OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, |
9535 | SourceLocation StartLoc, |
9536 | SourceLocation LParenLoc, |
9537 | SourceLocation EndLoc); |
9538 | /// Called on well-formed 'reduction' clause. |
9539 | OMPClause *ActOnOpenMPReductionClause( |
9540 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, |
9541 | SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, |
9542 | CXXScopeSpec &ReductionIdScopeSpec, |
9543 | const DeclarationNameInfo &ReductionId, |
9544 | ArrayRef<Expr *> UnresolvedReductions = llvm::None); |
9545 | /// Called on well-formed 'task_reduction' clause. |
9546 | OMPClause *ActOnOpenMPTaskReductionClause( |
9547 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, |
9548 | SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, |
9549 | CXXScopeSpec &ReductionIdScopeSpec, |
9550 | const DeclarationNameInfo &ReductionId, |
9551 | ArrayRef<Expr *> UnresolvedReductions = llvm::None); |
9552 | /// Called on well-formed 'in_reduction' clause. |
9553 | OMPClause *ActOnOpenMPInReductionClause( |
9554 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, |
9555 | SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, |
9556 | CXXScopeSpec &ReductionIdScopeSpec, |
9557 | const DeclarationNameInfo &ReductionId, |
9558 | ArrayRef<Expr *> UnresolvedReductions = llvm::None); |
9559 | /// Called on well-formed 'linear' clause. |
9560 | OMPClause * |
9561 | ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, |
9562 | SourceLocation StartLoc, SourceLocation LParenLoc, |
9563 | OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, |
9564 | SourceLocation ColonLoc, SourceLocation EndLoc); |
9565 | /// Called on well-formed 'aligned' clause. |
9566 | OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, |
9567 | Expr *Alignment, |
9568 | SourceLocation StartLoc, |
9569 | SourceLocation LParenLoc, |
9570 | SourceLocation ColonLoc, |
9571 | SourceLocation EndLoc); |
9572 | /// Called on well-formed 'copyin' clause. |
9573 | OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, |
9574 | SourceLocation StartLoc, |
9575 | SourceLocation LParenLoc, |
9576 | SourceLocation EndLoc); |
9577 | /// Called on well-formed 'copyprivate' clause. |
9578 | OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, |
9579 | SourceLocation StartLoc, |
9580 | SourceLocation LParenLoc, |
9581 | SourceLocation EndLoc); |
9582 | /// Called on well-formed 'flush' pseudo clause. |
9583 | OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, |
9584 | SourceLocation StartLoc, |
9585 | SourceLocation LParenLoc, |
9586 | SourceLocation EndLoc); |
9587 | /// Called on well-formed 'depend' clause. |
9588 | OMPClause * |
9589 | ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, |
9590 | SourceLocation ColonLoc, ArrayRef<Expr *> VarList, |
9591 | SourceLocation StartLoc, SourceLocation LParenLoc, |
9592 | SourceLocation EndLoc); |
9593 | /// Called on well-formed 'device' clause. |
9594 | OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, |
9595 | SourceLocation LParenLoc, |
9596 | SourceLocation EndLoc); |
9597 | /// Called on well-formed 'map' clause. |
9598 | OMPClause * |
9599 | ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, |
9600 | ArrayRef<SourceLocation> MapTypeModifiersLoc, |
9601 | CXXScopeSpec &MapperIdScopeSpec, |
9602 | DeclarationNameInfo &MapperId, |
9603 | OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, |
9604 | SourceLocation MapLoc, SourceLocation ColonLoc, |
9605 | ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, |
9606 | ArrayRef<Expr *> UnresolvedMappers = llvm::None); |
9607 | /// Called on well-formed 'num_teams' clause. |
9608 | OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, |
9609 | SourceLocation LParenLoc, |
9610 | SourceLocation EndLoc); |
9611 | /// Called on well-formed 'thread_limit' clause. |
9612 | OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, |
9613 | SourceLocation StartLoc, |
9614 | SourceLocation LParenLoc, |
9615 | SourceLocation EndLoc); |
9616 | /// Called on well-formed 'priority' clause. |
9617 | OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, |
9618 | SourceLocation LParenLoc, |
9619 | SourceLocation EndLoc); |
9620 | /// Called on well-formed 'dist_schedule' clause. |
9621 | OMPClause *ActOnOpenMPDistScheduleClause( |
9622 | OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, |
9623 | SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, |
9624 | SourceLocation CommaLoc, SourceLocation EndLoc); |
9625 | /// Called on well-formed 'defaultmap' clause. |
9626 | OMPClause *ActOnOpenMPDefaultmapClause( |
9627 | OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, |
9628 | SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, |
9629 | SourceLocation KindLoc, SourceLocation EndLoc); |
9630 | /// Called on well-formed 'to' clause. |
9631 | OMPClause * |
9632 | ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, |
9633 | DeclarationNameInfo &MapperId, |
9634 | const OMPVarListLocTy &Locs, |
9635 | ArrayRef<Expr *> UnresolvedMappers = llvm::None); |
9636 | /// Called on well-formed 'from' clause. |
9637 | OMPClause *ActOnOpenMPFromClause( |
9638 | ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, |
9639 | DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, |
9640 | ArrayRef<Expr *> UnresolvedMappers = llvm::None); |
9641 | /// Called on well-formed 'use_device_ptr' clause. |
9642 | OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, |
9643 | const OMPVarListLocTy &Locs); |
9644 | /// Called on well-formed 'is_device_ptr' clause. |
9645 | OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, |
9646 | const OMPVarListLocTy &Locs); |
9647 | |
9648 | /// The kind of conversion being performed. |
9649 | enum CheckedConversionKind { |
9650 | /// An implicit conversion. |
9651 | CCK_ImplicitConversion, |
9652 | /// A C-style cast. |
9653 | CCK_CStyleCast, |
9654 | /// A functional-style cast. |
9655 | CCK_FunctionalCast, |
9656 | /// A cast other than a C-style cast. |
9657 | CCK_OtherCast, |
9658 | /// A conversion for an operand of a builtin overloaded operator. |
9659 | CCK_ForBuiltinOverloadedOp |
9660 | }; |
9661 | |
9662 | static bool isCast(CheckedConversionKind CCK) { |
9663 | return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || |
9664 | CCK == CCK_OtherCast; |
9665 | } |
9666 | |
9667 | /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit |
9668 | /// cast. If there is already an implicit cast, merge into the existing one. |
9669 | /// If isLvalue, the result of the cast is an lvalue. |
9670 | ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, |
9671 | ExprValueKind VK = VK_RValue, |
9672 | const CXXCastPath *BasePath = nullptr, |
9673 | CheckedConversionKind CCK |
9674 | = CCK_ImplicitConversion); |
9675 | |
9676 | /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding |
9677 | /// to the conversion from scalar type ScalarTy to the Boolean type. |
9678 | static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); |
9679 | |
9680 | /// IgnoredValueConversions - Given that an expression's result is |
9681 | /// syntactically ignored, perform any conversions that are |
9682 | /// required. |
9683 | ExprResult IgnoredValueConversions(Expr *E); |
9684 | |
9685 | // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts |
9686 | // functions and arrays to their respective pointers (C99 6.3.2.1). |
9687 | ExprResult UsualUnaryConversions(Expr *E); |
9688 | |
9689 | /// CallExprUnaryConversions - a special case of an unary conversion |
9690 | /// performed on a function designator of a call expression. |
9691 | ExprResult CallExprUnaryConversions(Expr *E); |
9692 | |
9693 | // DefaultFunctionArrayConversion - converts functions and arrays |
9694 | // to their respective pointers (C99 6.3.2.1). |
9695 | ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); |
9696 | |
9697 | // DefaultFunctionArrayLvalueConversion - converts functions and |
9698 | // arrays to their respective pointers and performs the |
9699 | // lvalue-to-rvalue conversion. |
9700 | ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, |
9701 | bool Diagnose = true); |
9702 | |
9703 | // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on |
9704 | // the operand. This is DefaultFunctionArrayLvalueConversion, |
9705 | // except that it assumes the operand isn't of function or array |
9706 | // type. |
9707 | ExprResult DefaultLvalueConversion(Expr *E); |
9708 | |
9709 | // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that |
9710 | // do not have a prototype. Integer promotions are performed on each |
9711 | // argument, and arguments that have type float are promoted to double. |
9712 | ExprResult DefaultArgumentPromotion(Expr *E); |
9713 | |
9714 | /// If \p E is a prvalue denoting an unmaterialized temporary, materialize |
9715 | /// it as an xvalue. In C++98, the result will still be a prvalue, because |
9716 | /// we don't have xvalues there. |
9717 | ExprResult TemporaryMaterializationConversion(Expr *E); |
9718 | |
9719 | // Used for emitting the right warning by DefaultVariadicArgumentPromotion |
9720 | enum VariadicCallType { |
9721 | VariadicFunction, |
9722 | VariadicBlock, |
9723 | VariadicMethod, |
9724 | VariadicConstructor, |
9725 | VariadicDoesNotApply |
9726 | }; |
9727 | |
9728 | VariadicCallType getVariadicCallType(FunctionDecl *FDecl, |
9729 | const FunctionProtoType *Proto, |
9730 | Expr *Fn); |
9731 | |
9732 | // Used for determining in which context a type is allowed to be passed to a |
9733 | // vararg function. |
9734 | enum VarArgKind { |
9735 | VAK_Valid, |
9736 | VAK_ValidInCXX11, |
9737 | VAK_Undefined, |
9738 | VAK_MSVCUndefined, |
9739 | VAK_Invalid |
9740 | }; |
9741 | |
9742 | // Determines which VarArgKind fits an expression. |
9743 | VarArgKind isValidVarArgType(const QualType &Ty); |
9744 | |
9745 | /// Check to see if the given expression is a valid argument to a variadic |
9746 | /// function, issuing a diagnostic if not. |
9747 | void checkVariadicArgument(const Expr *E, VariadicCallType CT); |
9748 | |
9749 | /// Check to see if a given expression could have '.c_str()' called on it. |
9750 | bool hasCStrMethod(const Expr *E); |
9751 | |
9752 | /// GatherArgumentsForCall - Collector argument expressions for various |
9753 | /// form of call prototypes. |
9754 | bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, |
9755 | const FunctionProtoType *Proto, |
9756 | unsigned FirstParam, ArrayRef<Expr *> Args, |
9757 | SmallVectorImpl<Expr *> &AllArgs, |
9758 | VariadicCallType CallType = VariadicDoesNotApply, |
9759 | bool AllowExplicit = false, |
9760 | bool IsListInitialization = false); |
9761 | |
9762 | // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but |
9763 | // will create a runtime trap if the resulting type is not a POD type. |
9764 | ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, |
9765 | FunctionDecl *FDecl); |
9766 | |
9767 | // UsualArithmeticConversions - performs the UsualUnaryConversions on it's |
9768 | // operands and then handles various conversions that are common to binary |
9769 | // operators (C99 6.3.1.8). If both operands aren't arithmetic, this |
9770 | // routine returns the first non-arithmetic type found. The client is |
9771 | // responsible for emitting appropriate error diagnostics. |
9772 | QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, |
9773 | bool IsCompAssign = false); |
9774 | |
9775 | /// AssignConvertType - All of the 'assignment' semantic checks return this |
9776 | /// enum to indicate whether the assignment was allowed. These checks are |
9777 | /// done for simple assignments, as well as initialization, return from |
9778 | /// function, argument passing, etc. The query is phrased in terms of a |
9779 | /// source and destination type. |
9780 | enum AssignConvertType { |
9781 | /// Compatible - the types are compatible according to the standard. |
9782 | Compatible, |
9783 | |
9784 | /// PointerToInt - The assignment converts a pointer to an int, which we |
9785 | /// accept as an extension. |
9786 | PointerToInt, |
9787 | |
9788 | /// IntToPointer - The assignment converts an int to a pointer, which we |
9789 | /// accept as an extension. |
9790 | IntToPointer, |
9791 | |
9792 | /// FunctionVoidPointer - The assignment is between a function pointer and |
9793 | /// void*, which the standard doesn't allow, but we accept as an extension. |
9794 | FunctionVoidPointer, |
9795 | |
9796 | /// IncompatiblePointer - The assignment is between two pointers types that |
9797 | /// are not compatible, but we accept them as an extension. |
9798 | IncompatiblePointer, |
9799 | |
9800 | /// IncompatiblePointerSign - The assignment is between two pointers types |
9801 | /// which point to integers which have a different sign, but are otherwise |
9802 | /// identical. This is a subset of the above, but broken out because it's by |
9803 | /// far the most common case of incompatible pointers. |
9804 | IncompatiblePointerSign, |
9805 | |
9806 | /// CompatiblePointerDiscardsQualifiers - The assignment discards |
9807 | /// c/v/r qualifiers, which we accept as an extension. |
9808 | CompatiblePointerDiscardsQualifiers, |
9809 | |
9810 | /// IncompatiblePointerDiscardsQualifiers - The assignment |
9811 | /// discards qualifiers that we don't permit to be discarded, |
9812 | /// like address spaces. |
9813 | IncompatiblePointerDiscardsQualifiers, |
9814 | |
9815 | /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment |
9816 | /// changes address spaces in nested pointer types which is not allowed. |
9817 | /// For instance, converting __private int ** to __generic int ** is |
9818 | /// illegal even though __private could be converted to __generic. |
9819 | IncompatibleNestedPointerAddressSpaceMismatch, |
9820 | |
9821 | /// IncompatibleNestedPointerQualifiers - The assignment is between two |
9822 | /// nested pointer types, and the qualifiers other than the first two |
9823 | /// levels differ e.g. char ** -> const char **, but we accept them as an |
9824 | /// extension. |
9825 | IncompatibleNestedPointerQualifiers, |
9826 | |
9827 | /// IncompatibleVectors - The assignment is between two vector types that |
9828 | /// have the same size, which we accept as an extension. |
9829 | IncompatibleVectors, |
9830 | |
9831 | /// IntToBlockPointer - The assignment converts an int to a block |
9832 | /// pointer. We disallow this. |
9833 | IntToBlockPointer, |
9834 | |
9835 | /// IncompatibleBlockPointer - The assignment is between two block |
9836 | /// pointers types that are not compatible. |
9837 | IncompatibleBlockPointer, |
9838 | |
9839 | /// IncompatibleObjCQualifiedId - The assignment is between a qualified |
9840 | /// id type and something else (that is incompatible with it). For example, |
9841 | /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. |
9842 | IncompatibleObjCQualifiedId, |
9843 | |
9844 | /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an |
9845 | /// object with __weak qualifier. |
9846 | IncompatibleObjCWeakRef, |
9847 | |
9848 | /// Incompatible - We reject this conversion outright, it is invalid to |
9849 | /// represent it in the AST. |
9850 | Incompatible |
9851 | }; |
9852 | |
9853 | /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the |
9854 | /// assignment conversion type specified by ConvTy. This returns true if the |
9855 | /// conversion was invalid or false if the conversion was accepted. |
9856 | bool DiagnoseAssignmentResult(AssignConvertType ConvTy, |
9857 | SourceLocation Loc, |
9858 | QualType DstType, QualType SrcType, |
9859 | Expr *SrcExpr, AssignmentAction Action, |
9860 | bool *Complained = nullptr); |
9861 | |
9862 | /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag |
9863 | /// enum. If AllowMask is true, then we also allow the complement of a valid |
9864 | /// value, to be used as a mask. |
9865 | bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, |
9866 | bool AllowMask) const; |
9867 | |
9868 | /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant |
9869 | /// integer not in the range of enum values. |
9870 | void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, |
9871 | Expr *SrcExpr); |
9872 | |
9873 | /// CheckAssignmentConstraints - Perform type checking for assignment, |
9874 | /// argument passing, variable initialization, and function return values. |
9875 | /// C99 6.5.16. |
9876 | AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, |
9877 | QualType LHSType, |
9878 | QualType RHSType); |
9879 | |
9880 | /// Check assignment constraints and optionally prepare for a conversion of |
9881 | /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS |
9882 | /// is true. |
9883 | AssignConvertType CheckAssignmentConstraints(QualType LHSType, |
9884 | ExprResult &RHS, |
9885 | CastKind &Kind, |
9886 | bool ConvertRHS = true); |
9887 | |
9888 | /// Check assignment constraints for an assignment of RHS to LHSType. |
9889 | /// |
9890 | /// \param LHSType The destination type for the assignment. |
9891 | /// \param RHS The source expression for the assignment. |
9892 | /// \param Diagnose If \c true, diagnostics may be produced when checking |
9893 | /// for assignability. If a diagnostic is produced, \p RHS will be |
9894 | /// set to ExprError(). Note that this function may still return |
9895 | /// without producing a diagnostic, even for an invalid assignment. |
9896 | /// \param DiagnoseCFAudited If \c true, the target is a function parameter |
9897 | /// in an audited Core Foundation API and does not need to be checked |
9898 | /// for ARC retain issues. |
9899 | /// \param ConvertRHS If \c true, \p RHS will be updated to model the |
9900 | /// conversions necessary to perform the assignment. If \c false, |
9901 | /// \p Diagnose must also be \c false. |
9902 | AssignConvertType CheckSingleAssignmentConstraints( |
9903 | QualType LHSType, ExprResult &RHS, bool Diagnose = true, |
9904 | bool DiagnoseCFAudited = false, bool ConvertRHS = true); |
9905 | |
9906 | // If the lhs type is a transparent union, check whether we |
9907 | // can initialize the transparent union with the given expression. |
9908 | AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, |
9909 | ExprResult &RHS); |
9910 | |
9911 | bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); |
9912 | |
9913 | bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); |
9914 | |
9915 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
9916 | AssignmentAction Action, |
9917 | bool AllowExplicit = false); |
9918 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
9919 | AssignmentAction Action, |
9920 | bool AllowExplicit, |
9921 | ImplicitConversionSequence& ICS); |
9922 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
9923 | const ImplicitConversionSequence& ICS, |
9924 | AssignmentAction Action, |
9925 | CheckedConversionKind CCK |
9926 | = CCK_ImplicitConversion); |
9927 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
9928 | const StandardConversionSequence& SCS, |
9929 | AssignmentAction Action, |
9930 | CheckedConversionKind CCK); |
9931 | |
9932 | ExprResult PerformQualificationConversion( |
9933 | Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, |
9934 | CheckedConversionKind CCK = CCK_ImplicitConversion); |
9935 | |
9936 | /// the following "Check" methods will return a valid/converted QualType |
9937 | /// or a null QualType (indicating an error diagnostic was issued). |
9938 | |
9939 | /// type checking binary operators (subroutines of CreateBuiltinBinOp). |
9940 | QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, |
9941 | ExprResult &RHS); |
9942 | QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, |
9943 | ExprResult &RHS); |
9944 | QualType CheckPointerToMemberOperands( // C++ 5.5 |
9945 | ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, |
9946 | SourceLocation OpLoc, bool isIndirect); |
9947 | QualType CheckMultiplyDivideOperands( // C99 6.5.5 |
9948 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, |
9949 | bool IsDivide); |
9950 | QualType CheckRemainderOperands( // C99 6.5.5 |
9951 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9952 | bool IsCompAssign = false); |
9953 | QualType CheckAdditionOperands( // C99 6.5.6 |
9954 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9955 | BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); |
9956 | QualType CheckSubtractionOperands( // C99 6.5.6 |
9957 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9958 | QualType* CompLHSTy = nullptr); |
9959 | QualType CheckShiftOperands( // C99 6.5.7 |
9960 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9961 | BinaryOperatorKind Opc, bool IsCompAssign = false); |
9962 | QualType CheckCompareOperands( // C99 6.5.8/9 |
9963 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9964 | BinaryOperatorKind Opc); |
9965 | QualType CheckBitwiseOperands( // C99 6.5.[10...12] |
9966 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9967 | BinaryOperatorKind Opc); |
9968 | QualType CheckLogicalOperands( // C99 6.5.[13,14] |
9969 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9970 | BinaryOperatorKind Opc); |
9971 | // CheckAssignmentOperands is used for both simple and compound assignment. |
9972 | // For simple assignment, pass both expressions and a null converted type. |
9973 | // For compound assignment, pass both expressions and the converted type. |
9974 | QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] |
9975 | Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); |
9976 | |
9977 | ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, |
9978 | UnaryOperatorKind Opcode, Expr *Op); |
9979 | ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, |
9980 | BinaryOperatorKind Opcode, |
9981 | Expr *LHS, Expr *RHS); |
9982 | ExprResult checkPseudoObjectRValue(Expr *E); |
9983 | Expr *recreateSyntacticForm(PseudoObjectExpr *E); |
9984 | |
9985 | QualType CheckConditionalOperands( // C99 6.5.15 |
9986 | ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, |
9987 | ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); |
9988 | QualType CXXCheckConditionalOperands( // C++ 5.16 |
9989 | ExprResult &cond, ExprResult &lhs, ExprResult &rhs, |
9990 | ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); |
9991 | QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, |
9992 | bool ConvertArgs = true); |
9993 | QualType FindCompositePointerType(SourceLocation Loc, |
9994 | ExprResult &E1, ExprResult &E2, |
9995 | bool ConvertArgs = true) { |
9996 | Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); |
9997 | QualType Composite = |
9998 | FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); |
9999 | E1 = E1Tmp; |
10000 | E2 = E2Tmp; |
10001 | return Composite; |
10002 | } |
10003 | |
10004 | QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, |
10005 | SourceLocation QuestionLoc); |
10006 | |
10007 | bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, |
10008 | SourceLocation QuestionLoc); |
10009 | |
10010 | void DiagnoseAlwaysNonNullPointer(Expr *E, |
10011 | Expr::NullPointerConstantKind NullType, |
10012 | bool IsEqual, SourceRange Range); |
10013 | |
10014 | /// type checking for vector binary operators. |
10015 | QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, |
10016 | SourceLocation Loc, bool IsCompAssign, |
10017 | bool AllowBothBool, bool AllowBoolConversion); |
10018 | QualType GetSignedVectorType(QualType V); |
10019 | QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, |
10020 | SourceLocation Loc, |
10021 | BinaryOperatorKind Opc); |
10022 | QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
10023 | SourceLocation Loc); |
10024 | |
10025 | bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); |
10026 | bool isLaxVectorConversion(QualType srcType, QualType destType); |
10027 | |
10028 | /// type checking declaration initializers (C99 6.7.8) |
10029 | bool CheckForConstantInitializer(Expr *e, QualType t); |
10030 | |
10031 | // type checking C++ declaration initializers (C++ [dcl.init]). |
10032 | |
10033 | /// ReferenceCompareResult - Expresses the result of comparing two |
10034 | /// types (cv1 T1 and cv2 T2) to determine their compatibility for the |
10035 | /// purposes of initialization by reference (C++ [dcl.init.ref]p4). |
10036 | enum ReferenceCompareResult { |
10037 | /// Ref_Incompatible - The two types are incompatible, so direct |
10038 | /// reference binding is not possible. |
10039 | Ref_Incompatible = 0, |
10040 | /// Ref_Related - The two types are reference-related, which means |
10041 | /// that their unqualified forms (T1 and T2) are either the same |
10042 | /// or T1 is a base class of T2. |
10043 | Ref_Related, |
10044 | /// Ref_Compatible - The two types are reference-compatible. |
10045 | Ref_Compatible |
10046 | }; |
10047 | |
10048 | ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, |
10049 | QualType T1, QualType T2, |
10050 | bool &DerivedToBase, |
10051 | bool &ObjCConversion, |
10052 | bool &ObjCLifetimeConversion); |
10053 | |
10054 | ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, |
10055 | Expr *CastExpr, CastKind &CastKind, |
10056 | ExprValueKind &VK, CXXCastPath &Path); |
10057 | |
10058 | /// Force an expression with unknown-type to an expression of the |
10059 | /// given type. |
10060 | ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); |
10061 | |
10062 | /// Type-check an expression that's being passed to an |
10063 | /// __unknown_anytype parameter. |
10064 | ExprResult checkUnknownAnyArg(SourceLocation callLoc, |
10065 | Expr *result, QualType ¶mType); |
10066 | |
10067 | // CheckVectorCast - check type constraints for vectors. |
10068 | // Since vectors are an extension, there are no C standard reference for this. |
10069 | // We allow casting between vectors and integer datatypes of the same size. |
10070 | // returns true if the cast is invalid |
10071 | bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, |
10072 | CastKind &Kind); |
10073 | |
10074 | /// Prepare `SplattedExpr` for a vector splat operation, adding |
10075 | /// implicit casts if necessary. |
10076 | ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); |
10077 | |
10078 | // CheckExtVectorCast - check type constraints for extended vectors. |
10079 | // Since vectors are an extension, there are no C standard reference for this. |
10080 | // We allow casting between vectors and integer datatypes of the same size, |
10081 | // or vectors and the element type of that vector. |
10082 | // returns the cast expr |
10083 | ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, |
10084 | CastKind &Kind); |
10085 | |
10086 | ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, |
10087 | SourceLocation LParenLoc, |
10088 | Expr *CastExpr, |
10089 | SourceLocation RParenLoc); |
10090 | |
10091 | enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; |
10092 | |
10093 | /// Checks for invalid conversions and casts between |
10094 | /// retainable pointers and other pointer kinds for ARC and Weak. |
10095 | ARCConversionResult CheckObjCConversion(SourceRange castRange, |
10096 | QualType castType, Expr *&op, |
10097 | CheckedConversionKind CCK, |
10098 | bool Diagnose = true, |
10099 | bool DiagnoseCFAudited = false, |
10100 | BinaryOperatorKind Opc = BO_PtrMemD |
10101 | ); |
10102 | |
10103 | Expr *stripARCUnbridgedCast(Expr *e); |
10104 | void diagnoseARCUnbridgedCast(Expr *e); |
10105 | |
10106 | bool CheckObjCARCUnavailableWeakConversion(QualType castType, |
10107 | QualType ExprType); |
10108 | |
10109 | /// checkRetainCycles - Check whether an Objective-C message send |
10110 | /// might create an obvious retain cycle. |
10111 | void checkRetainCycles(ObjCMessageExpr *msg); |
10112 | void checkRetainCycles(Expr *receiver, Expr *argument); |
10113 | void checkRetainCycles(VarDecl *Var, Expr *Init); |
10114 | |
10115 | /// checkUnsafeAssigns - Check whether +1 expr is being assigned |
10116 | /// to weak/__unsafe_unretained type. |
10117 | bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); |
10118 | |
10119 | /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned |
10120 | /// to weak/__unsafe_unretained expression. |
10121 | void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); |
10122 | |
10123 | /// CheckMessageArgumentTypes - Check types in an Obj-C message send. |
10124 | /// \param Method - May be null. |
10125 | /// \param [out] ReturnType - The return type of the send. |
10126 | /// \return true iff there were any incompatible types. |
10127 | bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, |
10128 | MultiExprArg Args, Selector Sel, |
10129 | ArrayRef<SourceLocation> SelectorLocs, |
10130 | ObjCMethodDecl *Method, bool isClassMessage, |
10131 | bool isSuperMessage, SourceLocation lbrac, |
10132 | SourceLocation rbrac, SourceRange RecRange, |
10133 | QualType &ReturnType, ExprValueKind &VK); |
10134 | |
10135 | /// Determine the result of a message send expression based on |
10136 | /// the type of the receiver, the method expected to receive the message, |
10137 | /// and the form of the message send. |
10138 | QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, |
10139 | ObjCMethodDecl *Method, bool isClassMessage, |
10140 | bool isSuperMessage); |
10141 | |
10142 | /// If the given expression involves a message send to a method |
10143 | /// with a related result type, emit a note describing what happened. |
10144 | void EmitRelatedResultTypeNote(const Expr *E); |
10145 | |
10146 | /// Given that we had incompatible pointer types in a return |
10147 | /// statement, check whether we're in a method with a related result |
10148 | /// type, and if so, emit a note describing what happened. |
10149 | void EmitRelatedResultTypeNoteForReturn(QualType destType); |
10150 | |
10151 | class ConditionResult { |
10152 | Decl *ConditionVar; |
10153 | FullExprArg Condition; |
10154 | bool Invalid; |
10155 | bool HasKnownValue; |
10156 | bool KnownValue; |
10157 | |
10158 | friend class Sema; |
10159 | ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, |
10160 | bool IsConstexpr) |
10161 | : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), |
10162 | HasKnownValue(IsConstexpr && Condition.get() && |
10163 | !Condition.get()->isValueDependent()), |
10164 | KnownValue(HasKnownValue && |
10165 | !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} |
10166 | explicit ConditionResult(bool Invalid) |
10167 | : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), |
10168 | HasKnownValue(false), KnownValue(false) {} |
10169 | |
10170 | public: |
10171 | ConditionResult() : ConditionResult(false) {} |
10172 | bool isInvalid() const { return Invalid; } |
10173 | std::pair<VarDecl *, Expr *> get() const { |
10174 | return std::make_pair(cast_or_null<VarDecl>(ConditionVar), |
10175 | Condition.get()); |
10176 | } |
10177 | llvm::Optional<bool> getKnownValue() const { |
10178 | if (!HasKnownValue) |
10179 | return None; |
10180 | return KnownValue; |
10181 | } |
10182 | }; |
10183 | static ConditionResult ConditionError() { return ConditionResult(true); } |
10184 | |
10185 | enum class ConditionKind { |
10186 | Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. |
10187 | ConstexprIf, ///< A constant boolean condition from 'if constexpr'. |
10188 | Switch ///< An integral condition for a 'switch' statement. |
10189 | }; |
10190 | |
10191 | ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, |
10192 | Expr *SubExpr, ConditionKind CK); |
10193 | |
10194 | ConditionResult ActOnConditionVariable(Decl *ConditionVar, |
10195 | SourceLocation StmtLoc, |
10196 | ConditionKind CK); |
10197 | |
10198 | DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); |
10199 | |
10200 | ExprResult CheckConditionVariable(VarDecl *ConditionVar, |
10201 | SourceLocation StmtLoc, |
10202 | ConditionKind CK); |
10203 | ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); |
10204 | |
10205 | /// CheckBooleanCondition - Diagnose problems involving the use of |
10206 | /// the given expression as a boolean condition (e.g. in an if |
10207 | /// statement). Also performs the standard function and array |
10208 | /// decays, possibly changing the input variable. |
10209 | /// |
10210 | /// \param Loc - A location associated with the condition, e.g. the |
10211 | /// 'if' keyword. |
10212 | /// \return true iff there were any errors |
10213 | ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, |
10214 | bool IsConstexpr = false); |
10215 | |
10216 | /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression |
10217 | /// found in an explicit(bool) specifier. |
10218 | ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); |
10219 | |
10220 | /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. |
10221 | /// Returns true if the explicit specifier is now resolved. |
10222 | bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); |
10223 | |
10224 | /// DiagnoseAssignmentAsCondition - Given that an expression is |
10225 | /// being used as a boolean condition, warn if it's an assignment. |
10226 | void DiagnoseAssignmentAsCondition(Expr *E); |
10227 | |
10228 | /// Redundant parentheses over an equality comparison can indicate |
10229 | /// that the user intended an assignment used as condition. |
10230 | void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); |
10231 | |
10232 | /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. |
10233 | ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); |
10234 | |
10235 | /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have |
10236 | /// the specified width and sign. If an overflow occurs, detect it and emit |
10237 | /// the specified diagnostic. |
10238 | void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, |
10239 | unsigned NewWidth, bool NewSign, |
10240 | SourceLocation Loc, unsigned DiagID); |
10241 | |
10242 | /// Checks that the Objective-C declaration is declared in the global scope. |
10243 | /// Emits an error and marks the declaration as invalid if it's not declared |
10244 | /// in the global scope. |
10245 | bool CheckObjCDeclScope(Decl *D); |
10246 | |
10247 | /// Abstract base class used for diagnosing integer constant |
10248 | /// expression violations. |
10249 | class VerifyICEDiagnoser { |
10250 | public: |
10251 | bool Suppress; |
10252 | |
10253 | VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } |
10254 | |
10255 | virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; |
10256 | virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); |
10257 | virtual ~VerifyICEDiagnoser() { } |
10258 | }; |
10259 | |
10260 | /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, |
10261 | /// and reports the appropriate diagnostics. Returns false on success. |
10262 | /// Can optionally return the value of the expression. |
10263 | ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
10264 | VerifyICEDiagnoser &Diagnoser, |
10265 | bool AllowFold = true); |
10266 | ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
10267 | unsigned DiagID, |
10268 | bool AllowFold = true); |
10269 | ExprResult VerifyIntegerConstantExpression(Expr *E, |
10270 | llvm::APSInt *Result = nullptr); |
10271 | |
10272 | /// VerifyBitField - verifies that a bit field expression is an ICE and has |
10273 | /// the correct width, and that the field type is valid. |
10274 | /// Returns false on success. |
10275 | /// Can optionally return whether the bit-field is of width 0 |
10276 | ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, |
10277 | QualType FieldTy, bool IsMsStruct, |
10278 | Expr *BitWidth, bool *ZeroWidth = nullptr); |
10279 | |
10280 | private: |
10281 | unsigned ForceCUDAHostDeviceDepth = 0; |
10282 | |
10283 | public: |
10284 | /// Increments our count of the number of times we've seen a pragma forcing |
10285 | /// functions to be __host__ __device__. So long as this count is greater |
10286 | /// than zero, all functions encountered will be __host__ __device__. |
10287 | void PushForceCUDAHostDevice(); |
10288 | |
10289 | /// Decrements our count of the number of times we've seen a pragma forcing |
10290 | /// functions to be __host__ __device__. Returns false if the count is 0 |
10291 | /// before incrementing, so you can emit an error. |
10292 | bool PopForceCUDAHostDevice(); |
10293 | |
10294 | /// Diagnostics that are emitted only if we discover that the given function |
10295 | /// must be codegen'ed. Because handling these correctly adds overhead to |
10296 | /// compilation, this is currently only enabled for CUDA compilations. |
10297 | llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, |
10298 | std::vector<PartialDiagnosticAt>> |
10299 | DeviceDeferredDiags; |
10300 | |
10301 | /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the |
10302 | /// key in a hashtable, both the FD and location are hashed. |
10303 | struct FunctionDeclAndLoc { |
10304 | CanonicalDeclPtr<FunctionDecl> FD; |
10305 | SourceLocation Loc; |
10306 | }; |
10307 | |
10308 | /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a |
10309 | /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the |
10310 | /// same deferred diag twice. |
10311 | llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; |
10312 | |
10313 | /// An inverse call graph, mapping known-emitted functions to one of their |
10314 | /// known-emitted callers (plus the location of the call). |
10315 | /// |
10316 | /// Functions that we can tell a priori must be emitted aren't added to this |
10317 | /// map. |
10318 | llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, |
10319 | /* Caller = */ FunctionDeclAndLoc> |
10320 | DeviceKnownEmittedFns; |
10321 | |
10322 | /// A partial call graph maintained during CUDA/OpenMP device code compilation |
10323 | /// to support deferred diagnostics. |
10324 | /// |
10325 | /// Functions are only added here if, at the time they're considered, they are |
10326 | /// not known-emitted. As soon as we discover that a function is |
10327 | /// known-emitted, we remove it and everything it transitively calls from this |
10328 | /// set and add those functions to DeviceKnownEmittedFns. |
10329 | llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>, |
10330 | /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>, |
10331 | SourceLocation>> |
10332 | DeviceCallGraph; |
10333 | |
10334 | /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be |
10335 | /// deferred. |
10336 | /// |
10337 | /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) |
10338 | /// which are not allowed to appear inside __device__ functions and are |
10339 | /// allowed to appear in __host__ __device__ functions only if the host+device |
10340 | /// function is never codegen'ed. |
10341 | /// |
10342 | /// To handle this, we use the notion of "deferred diagnostics", where we |
10343 | /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. |
10344 | /// |
10345 | /// This class lets you emit either a regular diagnostic, a deferred |
10346 | /// diagnostic, or no diagnostic at all, according to an argument you pass to |
10347 | /// its constructor, thus simplifying the process of creating these "maybe |
10348 | /// deferred" diagnostics. |
10349 | class DeviceDiagBuilder { |
10350 | public: |
10351 | enum Kind { |
10352 | /// Emit no diagnostics. |
10353 | K_Nop, |
10354 | /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). |
10355 | K_Immediate, |
10356 | /// Emit the diagnostic immediately, and, if it's a warning or error, also |
10357 | /// emit a call stack showing how this function can be reached by an a |
10358 | /// priori known-emitted function. |
10359 | K_ImmediateWithCallStack, |
10360 | /// Create a deferred diagnostic, which is emitted only if the function |
10361 | /// it's attached to is codegen'ed. Also emit a call stack as with |
10362 | /// K_ImmediateWithCallStack. |
10363 | K_Deferred |
10364 | }; |
10365 | |
10366 | DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, |
10367 | FunctionDecl *Fn, Sema &S); |
10368 | DeviceDiagBuilder(DeviceDiagBuilder &&D); |
10369 | DeviceDiagBuilder(const DeviceDiagBuilder &) = default; |
10370 | ~DeviceDiagBuilder(); |
10371 | |
10372 | /// Convertible to bool: True if we immediately emitted an error, false if |
10373 | /// we didn't emit an error or we created a deferred error. |
10374 | /// |
10375 | /// Example usage: |
10376 | /// |
10377 | /// if (DeviceDiagBuilder(...) << foo << bar) |
10378 | /// return ExprError(); |
10379 | /// |
10380 | /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably |
10381 | /// want to use these instead of creating a DeviceDiagBuilder yourself. |
10382 | operator bool() const { return ImmediateDiag.hasValue(); } |
10383 | |
10384 | template <typename T> |
10385 | friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, |
10386 | const T &Value) { |
10387 | if (Diag.ImmediateDiag.hasValue()) |
10388 | *Diag.ImmediateDiag << Value; |
10389 | else if (Diag.PartialDiagId.hasValue()) |
10390 | Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second |
10391 | << Value; |
10392 | return Diag; |
10393 | } |
10394 | |
10395 | private: |
10396 | Sema &S; |
10397 | SourceLocation Loc; |
10398 | unsigned DiagID; |
10399 | FunctionDecl *Fn; |
10400 | bool ShowCallStack; |
10401 | |
10402 | // Invariant: At most one of these Optionals has a value. |
10403 | // FIXME: Switch these to a Variant once that exists. |
10404 | llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; |
10405 | llvm::Optional<unsigned> PartialDiagId; |
10406 | }; |
10407 | |
10408 | /// Indicate that this function (and thus everything it transtively calls) |
10409 | /// will be codegen'ed, and emit any deferred diagnostics on this function and |
10410 | /// its (transitive) callees. |
10411 | void markKnownEmitted( |
10412 | Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee, |
10413 | SourceLocation OrigLoc, |
10414 | const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted); |
10415 | |
10416 | /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context |
10417 | /// is "used as device code". |
10418 | /// |
10419 | /// - If CurContext is a __host__ function, does not emit any diagnostics. |
10420 | /// - If CurContext is a __device__ or __global__ function, emits the |
10421 | /// diagnostics immediately. |
10422 | /// - If CurContext is a __host__ __device__ function and we are compiling for |
10423 | /// the device, creates a diagnostic which is emitted if and when we realize |
10424 | /// that the function will be codegen'ed. |
10425 | /// |
10426 | /// Example usage: |
10427 | /// |
10428 | /// // Variable-length arrays are not allowed in CUDA device code. |
10429 | /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) |
10430 | /// return ExprError(); |
10431 | /// // Otherwise, continue parsing as normal. |
10432 | DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); |
10433 | |
10434 | /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context |
10435 | /// is "used as host code". |
10436 | /// |
10437 | /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. |
10438 | DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); |
10439 | |
10440 | /// Creates a DeviceDiagBuilder that emits the diagnostic if the current |
10441 | /// context is "used as device code". |
10442 | /// |
10443 | /// - If CurContext is a `declare target` function or it is known that the |
10444 | /// function is emitted for the device, emits the diagnostics immediately. |
10445 | /// - If CurContext is a non-`declare target` function and we are compiling |
10446 | /// for the device, creates a diagnostic which is emitted if and when we |
10447 | /// realize that the function will be codegen'ed. |
10448 | /// |
10449 | /// Example usage: |
10450 | /// |
10451 | /// // Variable-length arrays are not allowed in NVPTX device code. |
10452 | /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) |
10453 | /// return ExprError(); |
10454 | /// // Otherwise, continue parsing as normal. |
10455 | DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); |
10456 | |
10457 | DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); |
10458 | |
10459 | enum CUDAFunctionTarget { |
10460 | CFT_Device, |
10461 | CFT_Global, |
10462 | CFT_Host, |
10463 | CFT_HostDevice, |
10464 | CFT_InvalidTarget |
10465 | }; |
10466 | |
10467 | /// Determines whether the given function is a CUDA device/host/kernel/etc. |
10468 | /// function. |
10469 | /// |
10470 | /// Use this rather than examining the function's attributes yourself -- you |
10471 | /// will get it wrong. Returns CFT_Host if D is null. |
10472 | CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, |
10473 | bool IgnoreImplicitHDAttr = false); |
10474 | CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); |
10475 | |
10476 | /// Gets the CUDA target for the current context. |
10477 | CUDAFunctionTarget CurrentCUDATarget() { |
10478 | return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); |
10479 | } |
10480 | |
10481 | // CUDA function call preference. Must be ordered numerically from |
10482 | // worst to best. |
10483 | enum CUDAFunctionPreference { |
10484 | CFP_Never, // Invalid caller/callee combination. |
10485 | CFP_WrongSide, // Calls from host-device to host or device |
10486 | // function that do not match current compilation |
10487 | // mode. |
10488 | CFP_HostDevice, // Any calls to host/device functions. |
10489 | CFP_SameSide, // Calls from host-device to host or device |
10490 | // function matching current compilation mode. |
10491 | CFP_Native, // host-to-host or device-to-device calls. |
10492 | }; |
10493 | |
10494 | /// Identifies relative preference of a given Caller/Callee |
10495 | /// combination, based on their host/device attributes. |
10496 | /// \param Caller function which needs address of \p Callee. |
10497 | /// nullptr in case of global context. |
10498 | /// \param Callee target function |
10499 | /// |
10500 | /// \returns preference value for particular Caller/Callee combination. |
10501 | CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, |
10502 | const FunctionDecl *Callee); |
10503 | |
10504 | /// Determines whether Caller may invoke Callee, based on their CUDA |
10505 | /// host/device attributes. Returns false if the call is not allowed. |
10506 | /// |
10507 | /// Note: Will return true for CFP_WrongSide calls. These may appear in |
10508 | /// semantically correct CUDA programs, but only if they're never codegen'ed. |
10509 | bool IsAllowedCUDACall(const FunctionDecl *Caller, |
10510 | const FunctionDecl *Callee) { |
10511 | return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; |
10512 | } |
10513 | |
10514 | /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, |
10515 | /// depending on FD and the current compilation settings. |
10516 | void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, |
10517 | const LookupResult &Previous); |
10518 | |
10519 | public: |
10520 | /// Check whether we're allowed to call Callee from the current context. |
10521 | /// |
10522 | /// - If the call is never allowed in a semantically-correct program |
10523 | /// (CFP_Never), emits an error and returns false. |
10524 | /// |
10525 | /// - If the call is allowed in semantically-correct programs, but only if |
10526 | /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to |
10527 | /// be emitted if and when the caller is codegen'ed, and returns true. |
10528 | /// |
10529 | /// Will only create deferred diagnostics for a given SourceLocation once, |
10530 | /// so you can safely call this multiple times without generating duplicate |
10531 | /// deferred errors. |
10532 | /// |
10533 | /// - Otherwise, returns true without emitting any diagnostics. |
10534 | bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); |
10535 | |
10536 | /// Set __device__ or __host__ __device__ attributes on the given lambda |
10537 | /// operator() method. |
10538 | /// |
10539 | /// CUDA lambdas declared inside __device__ or __global__ functions inherit |
10540 | /// the __device__ attribute. Similarly, lambdas inside __host__ __device__ |
10541 | /// functions become __host__ __device__ themselves. |
10542 | void CUDASetLambdaAttrs(CXXMethodDecl *Method); |
10543 | |
10544 | /// Finds a function in \p Matches with highest calling priority |
10545 | /// from \p Caller context and erases all functions with lower |
10546 | /// calling priority. |
10547 | void EraseUnwantedCUDAMatches( |
10548 | const FunctionDecl *Caller, |
10549 | SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); |
10550 | |
10551 | /// Given a implicit special member, infer its CUDA target from the |
10552 | /// calls it needs to make to underlying base/field special members. |
10553 | /// \param ClassDecl the class for which the member is being created. |
10554 | /// \param CSM the kind of special member. |
10555 | /// \param MemberDecl the special member itself. |
10556 | /// \param ConstRHS true if this is a copy operation with a const object on |
10557 | /// its RHS. |
10558 | /// \param Diagnose true if this call should emit diagnostics. |
10559 | /// \return true if there was an error inferring. |
10560 | /// The result of this call is implicit CUDA target attribute(s) attached to |
10561 | /// the member declaration. |
10562 | bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, |
10563 | CXXSpecialMember CSM, |
10564 | CXXMethodDecl *MemberDecl, |
10565 | bool ConstRHS, |
10566 | bool Diagnose); |
10567 | |
10568 | /// \return true if \p CD can be considered empty according to CUDA |
10569 | /// (E.2.3.1 in CUDA 7.5 Programming guide). |
10570 | bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); |
10571 | bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); |
10572 | |
10573 | // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In |
10574 | // case of error emits appropriate diagnostic and invalidates \p Var. |
10575 | // |
10576 | // \details CUDA allows only empty constructors as initializers for global |
10577 | // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all |
10578 | // __shared__ variables whether they are local or not (they all are implicitly |
10579 | // static in CUDA). One exception is that CUDA allows constant initializers |
10580 | // for __constant__ and __device__ variables. |
10581 | void checkAllowedCUDAInitializer(VarDecl *VD); |
10582 | |
10583 | /// Check whether NewFD is a valid overload for CUDA. Emits |
10584 | /// diagnostics and invalidates NewFD if not. |
10585 | void checkCUDATargetOverload(FunctionDecl *NewFD, |
10586 | const LookupResult &Previous); |
10587 | /// Copies target attributes from the template TD to the function FD. |
10588 | void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); |
10589 | |
10590 | /// Returns the name of the launch configuration function. This is the name |
10591 | /// of the function that will be called to configure kernel call, with the |
10592 | /// parameters specified via <<<>>>. |
10593 | std::string getCudaConfigureFuncName() const; |
10594 | |
10595 | /// \name Code completion |
10596 | //@{ |
10597 | /// Describes the context in which code completion occurs. |
10598 | enum ParserCompletionContext { |
10599 | /// Code completion occurs at top-level or namespace context. |
10600 | PCC_Namespace, |
10601 | /// Code completion occurs within a class, struct, or union. |
10602 | PCC_Class, |
10603 | /// Code completion occurs within an Objective-C interface, protocol, |
10604 | /// or category. |
10605 | PCC_ObjCInterface, |
10606 | /// Code completion occurs within an Objective-C implementation or |
10607 | /// category implementation |
10608 | PCC_ObjCImplementation, |
10609 | /// Code completion occurs within the list of instance variables |
10610 | /// in an Objective-C interface, protocol, category, or implementation. |
10611 | PCC_ObjCInstanceVariableList, |
10612 | /// Code completion occurs following one or more template |
10613 | /// headers. |
10614 | PCC_Template, |
10615 | /// Code completion occurs following one or more template |
10616 | /// headers within a class. |
10617 | PCC_MemberTemplate, |
10618 | /// Code completion occurs within an expression. |
10619 | PCC_Expression, |
10620 | /// Code completion occurs within a statement, which may |
10621 | /// also be an expression or a declaration. |
10622 | PCC_Statement, |
10623 | /// Code completion occurs at the beginning of the |
10624 | /// initialization statement (or expression) in a for loop. |
10625 | PCC_ForInit, |
10626 | /// Code completion occurs within the condition of an if, |
10627 | /// while, switch, or for statement. |
10628 | PCC_Condition, |
10629 | /// Code completion occurs within the body of a function on a |
10630 | /// recovery path, where we do not have a specific handle on our position |
10631 | /// in the grammar. |
10632 | PCC_RecoveryInFunction, |
10633 | /// Code completion occurs where only a type is permitted. |
10634 | PCC_Type, |
10635 | /// Code completion occurs in a parenthesized expression, which |
10636 | /// might also be a type cast. |
10637 | PCC_ParenthesizedExpression, |
10638 | /// Code completion occurs within a sequence of declaration |
10639 | /// specifiers within a function, method, or block. |
10640 | PCC_LocalDeclarationSpecifiers |
10641 | }; |
10642 | |
10643 | void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); |
10644 | void CodeCompleteOrdinaryName(Scope *S, |
10645 | ParserCompletionContext CompletionContext); |
10646 | void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, |
10647 | bool AllowNonIdentifiers, |
10648 | bool AllowNestedNameSpecifiers); |
10649 | |
10650 | struct CodeCompleteExpressionData; |
10651 | void CodeCompleteExpression(Scope *S, |
10652 | const CodeCompleteExpressionData &Data); |
10653 | void CodeCompleteExpression(Scope *S, QualType PreferredType, |
10654 | bool IsParenthesized = false); |
10655 | void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, |
10656 | SourceLocation OpLoc, bool IsArrow, |
10657 | bool IsBaseExprStatement, |
10658 | QualType PreferredType); |
10659 | void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, |
10660 | QualType PreferredType); |
10661 | void CodeCompleteTag(Scope *S, unsigned TagSpec); |
10662 | void CodeCompleteTypeQualifiers(DeclSpec &DS); |
10663 | void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, |
10664 | const VirtSpecifiers *VS = nullptr); |
10665 | void CodeCompleteBracketDeclarator(Scope *S); |
10666 | void CodeCompleteCase(Scope *S); |
10667 | /// Reports signatures for a call to CodeCompleteConsumer and returns the |
10668 | /// preferred type for the current argument. Returned type can be null. |
10669 | QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, |
10670 | SourceLocation OpenParLoc); |
10671 | QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, |
10672 | SourceLocation Loc, |
10673 | ArrayRef<Expr *> Args, |
10674 | SourceLocation OpenParLoc); |
10675 | QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, |
10676 | CXXScopeSpec SS, |
10677 | ParsedType TemplateTypeTy, |
10678 | ArrayRef<Expr *> ArgExprs, |
10679 | IdentifierInfo *II, |
10680 | SourceLocation OpenParLoc); |
10681 | void CodeCompleteInitializer(Scope *S, Decl *D); |
10682 | void CodeCompleteAfterIf(Scope *S); |
10683 | |
10684 | void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, |
10685 | QualType BaseType, QualType PreferredType); |
10686 | void CodeCompleteUsing(Scope *S); |
10687 | void CodeCompleteUsingDirective(Scope *S); |
10688 | void CodeCompleteNamespaceDecl(Scope *S); |
10689 | void CodeCompleteNamespaceAliasDecl(Scope *S); |
10690 | void CodeCompleteOperatorName(Scope *S); |
10691 | void CodeCompleteConstructorInitializer( |
10692 | Decl *Constructor, |
10693 | ArrayRef<CXXCtorInitializer *> Initializers); |
10694 | |
10695 | void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, |
10696 | bool AfterAmpersand); |
10697 | |
10698 | void CodeCompleteObjCAtDirective(Scope *S); |
10699 | void CodeCompleteObjCAtVisibility(Scope *S); |
10700 | void CodeCompleteObjCAtStatement(Scope *S); |
10701 | void CodeCompleteObjCAtExpression(Scope *S); |
10702 | void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); |
10703 | void CodeCompleteObjCPropertyGetter(Scope *S); |
10704 | void CodeCompleteObjCPropertySetter(Scope *S); |
10705 | void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, |
10706 | bool IsParameter); |
10707 | void CodeCompleteObjCMessageReceiver(Scope *S); |
10708 | void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, |
10709 | ArrayRef<IdentifierInfo *> SelIdents, |
10710 | bool AtArgumentExpression); |
10711 | void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, |
10712 | ArrayRef<IdentifierInfo *> SelIdents, |
10713 | bool AtArgumentExpression, |
10714 | bool IsSuper = false); |
10715 | void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, |
10716 | ArrayRef<IdentifierInfo *> SelIdents, |
10717 | bool AtArgumentExpression, |
10718 | ObjCInterfaceDecl *Super = nullptr); |
10719 | void CodeCompleteObjCForCollection(Scope *S, |
10720 | DeclGroupPtrTy IterationVar); |
10721 | void CodeCompleteObjCSelector(Scope *S, |
10722 | ArrayRef<IdentifierInfo *> SelIdents); |
10723 | void CodeCompleteObjCProtocolReferences( |
10724 | ArrayRef<IdentifierLocPair> Protocols); |
10725 | void CodeCompleteObjCProtocolDecl(Scope *S); |
10726 | void CodeCompleteObjCInterfaceDecl(Scope *S); |
10727 | void CodeCompleteObjCSuperclass(Scope *S, |
10728 | IdentifierInfo *ClassName, |
10729 | SourceLocation ClassNameLoc); |
10730 | void CodeCompleteObjCImplementationDecl(Scope *S); |
10731 | void CodeCompleteObjCInterfaceCategory(Scope *S, |
10732 | IdentifierInfo *ClassName, |
10733 | SourceLocation ClassNameLoc); |
10734 | void CodeCompleteObjCImplementationCategory(Scope *S, |
10735 | IdentifierInfo *ClassName, |
10736 | SourceLocation ClassNameLoc); |
10737 | void CodeCompleteObjCPropertyDefinition(Scope *S); |
10738 | void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, |
10739 | IdentifierInfo *PropertyName); |
10740 | void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, |
10741 | ParsedType ReturnType); |
10742 | void CodeCompleteObjCMethodDeclSelector(Scope *S, |
10743 | bool IsInstanceMethod, |
10744 | bool AtParameterName, |
10745 | ParsedType ReturnType, |
10746 | ArrayRef<IdentifierInfo *> SelIdents); |
10747 | void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, |
10748 | SourceLocation ClassNameLoc, |
10749 | bool IsBaseExprStatement); |
10750 | void CodeCompletePreprocessorDirective(bool InConditional); |
10751 | void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); |
10752 | void CodeCompletePreprocessorMacroName(bool IsDefinition); |
10753 | void CodeCompletePreprocessorExpression(); |
10754 | void CodeCompletePreprocessorMacroArgument(Scope *S, |
10755 | IdentifierInfo *Macro, |
10756 | MacroInfo *MacroInfo, |
10757 | unsigned Argument); |
10758 | void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); |
10759 | void CodeCompleteNaturalLanguage(); |
10760 | void CodeCompleteAvailabilityPlatformName(); |
10761 | void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, |
10762 | CodeCompletionTUInfo &CCTUInfo, |
10763 | SmallVectorImpl<CodeCompletionResult> &Results); |
10764 | //@} |
10765 | |
10766 | //===--------------------------------------------------------------------===// |
10767 | // Extra semantic analysis beyond the C type system |
10768 | |
10769 | public: |
10770 | SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, |
10771 | unsigned ByteNo) const; |
10772 | |
10773 | private: |
10774 | void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, |
10775 | const ArraySubscriptExpr *ASE=nullptr, |
10776 | bool AllowOnePastEnd=true, bool IndexNegated=false); |
10777 | void CheckArrayAccess(const Expr *E); |
10778 | // Used to grab the relevant information from a FormatAttr and a |
10779 | // FunctionDeclaration. |
10780 | struct FormatStringInfo { |
10781 | unsigned FormatIdx; |
10782 | unsigned FirstDataArg; |
10783 | bool HasVAListArg; |
10784 | }; |
10785 | |
10786 | static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, |
10787 | FormatStringInfo *FSI); |
10788 | bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, |
10789 | const FunctionProtoType *Proto); |
10790 | bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, |
10791 | ArrayRef<const Expr *> Args); |
10792 | bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, |
10793 | const FunctionProtoType *Proto); |
10794 | bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); |
10795 | void CheckConstructorCall(FunctionDecl *FDecl, |
10796 | ArrayRef<const Expr *> Args, |
10797 | const FunctionProtoType *Proto, |
10798 | SourceLocation Loc); |
10799 | |
10800 | void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, |
10801 | const Expr *ThisArg, ArrayRef<const Expr *> Args, |
10802 | bool IsMemberFunction, SourceLocation Loc, SourceRange Range, |
10803 | VariadicCallType CallType); |
10804 | |
10805 | bool CheckObjCString(Expr *Arg); |
10806 | ExprResult CheckOSLogFormatStringArg(Expr *Arg); |
10807 | |
10808 | ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, |
10809 | unsigned BuiltinID, CallExpr *TheCall); |
10810 | void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); |
10811 | |
10812 | bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, |
10813 | unsigned MaxWidth); |
10814 | bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10815 | bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10816 | |
10817 | bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10818 | bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10819 | bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall); |
10820 | bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); |
10821 | bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10822 | bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10823 | bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); |
10824 | bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); |
10825 | bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10826 | bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10827 | |
10828 | bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); |
10829 | bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); |
10830 | bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); |
10831 | bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); |
10832 | bool SemaBuiltinVSX(CallExpr *TheCall); |
10833 | bool SemaBuiltinOSLogFormat(CallExpr *TheCall); |
10834 | |
10835 | public: |
10836 | // Used by C++ template instantiation. |
10837 | ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); |
10838 | ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, |
10839 | SourceLocation BuiltinLoc, |
10840 | SourceLocation RParenLoc); |
10841 | |
10842 | private: |
10843 | bool SemaBuiltinPrefetch(CallExpr *TheCall); |
10844 | bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); |
10845 | bool SemaBuiltinAssume(CallExpr *TheCall); |
10846 | bool SemaBuiltinAssumeAligned(CallExpr *TheCall); |
10847 | bool SemaBuiltinLongjmp(CallExpr *TheCall); |
10848 | bool SemaBuiltinSetjmp(CallExpr *TheCall); |
10849 | ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); |
10850 | ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); |
10851 | ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, |
10852 | AtomicExpr::AtomicOp Op); |
10853 | ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, |
10854 | bool IsDelete); |
10855 | bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, |
10856 | llvm::APSInt &Result); |
10857 | bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, |
10858 | int High, bool RangeIsError = true); |
10859 | bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, |
10860 | unsigned Multiple); |
10861 | bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, |
10862 | int ArgNum, unsigned ExpectedFieldNum, |
10863 | bool AllowName); |
10864 | bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); |
10865 | public: |
10866 | enum FormatStringType { |
10867 | FST_Scanf, |
10868 | FST_Printf, |
10869 | FST_NSString, |
10870 | FST_Strftime, |
10871 | FST_Strfmon, |
10872 | FST_Kprintf, |
10873 | FST_FreeBSDKPrintf, |
10874 | FST_OSTrace, |
10875 | FST_OSLog, |
10876 | FST_Unknown |
10877 | }; |
10878 | static FormatStringType GetFormatStringType(const FormatAttr *Format); |
10879 | |
10880 | bool FormatStringHasSArg(const StringLiteral *FExpr); |
10881 | |
10882 | static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); |
10883 | |
10884 | private: |
10885 | bool CheckFormatArguments(const FormatAttr *Format, |
10886 | ArrayRef<const Expr *> Args, |
10887 | bool IsCXXMember, |
10888 | VariadicCallType CallType, |
10889 | SourceLocation Loc, SourceRange Range, |
10890 | llvm::SmallBitVector &CheckedVarArgs); |
10891 | bool CheckFormatArguments(ArrayRef<const Expr *> Args, |
10892 | bool HasVAListArg, unsigned format_idx, |
10893 | unsigned firstDataArg, FormatStringType Type, |
10894 | VariadicCallType CallType, |
10895 | SourceLocation Loc, SourceRange range, |
10896 | llvm::SmallBitVector &CheckedVarArgs); |
10897 | |
10898 | void CheckAbsoluteValueFunction(const CallExpr *Call, |
10899 | const FunctionDecl *FDecl); |
10900 | |
10901 | void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); |
10902 | |
10903 | void CheckMemaccessArguments(const CallExpr *Call, |
10904 | unsigned BId, |
10905 | IdentifierInfo *FnName); |
10906 | |
10907 | void CheckStrlcpycatArguments(const CallExpr *Call, |
10908 | IdentifierInfo *FnName); |
10909 | |
10910 | void CheckStrncatArguments(const CallExpr *Call, |
10911 | IdentifierInfo *FnName); |
10912 | |
10913 | void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, |
10914 | SourceLocation ReturnLoc, |
10915 | bool isObjCMethod = false, |
10916 | const AttrVec *Attrs = nullptr, |
10917 | const FunctionDecl *FD = nullptr); |
10918 | |
10919 | public: |
10920 | void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); |
10921 | |
10922 | private: |
10923 | void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); |
10924 | void CheckBoolLikeConversion(Expr *E, SourceLocation CC); |
10925 | void CheckForIntOverflow(Expr *E); |
10926 | void CheckUnsequencedOperations(Expr *E); |
10927 | |
10928 | /// Perform semantic checks on a completed expression. This will either |
10929 | /// be a full-expression or a default argument expression. |
10930 | void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), |
10931 | bool IsConstexpr = false); |
10932 | |
10933 | void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, |
10934 | Expr *Init); |
10935 | |
10936 | /// Check if there is a field shadowing. |
10937 | void CheckShadowInheritedFields(const SourceLocation &Loc, |
10938 | DeclarationName FieldName, |
10939 | const CXXRecordDecl *RD, |
10940 | bool DeclIsField = true); |
10941 | |
10942 | /// Check if the given expression contains 'break' or 'continue' |
10943 | /// statement that produces control flow different from GCC. |
10944 | void CheckBreakContinueBinding(Expr *E); |
10945 | |
10946 | /// Check whether receiver is mutable ObjC container which |
10947 | /// attempts to add itself into the container |
10948 | void CheckObjCCircularContainer(ObjCMessageExpr *Message); |
10949 | |
10950 | void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); |
10951 | void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, |
10952 | bool DeleteWasArrayForm); |
10953 | public: |
10954 | /// Register a magic integral constant to be used as a type tag. |
10955 | void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, |
10956 | uint64_t MagicValue, QualType Type, |
10957 | bool LayoutCompatible, bool MustBeNull); |
10958 | |
10959 | struct TypeTagData { |
10960 | TypeTagData() {} |
10961 | |
10962 | TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : |
10963 | Type(Type), LayoutCompatible(LayoutCompatible), |
10964 | MustBeNull(MustBeNull) |
10965 | {} |
10966 | |
10967 | QualType Type; |
10968 | |
10969 | /// If true, \c Type should be compared with other expression's types for |
10970 | /// layout-compatibility. |
10971 | unsigned LayoutCompatible : 1; |
10972 | unsigned MustBeNull : 1; |
10973 | }; |
10974 | |
10975 | /// A pair of ArgumentKind identifier and magic value. This uniquely |
10976 | /// identifies the magic value. |
10977 | typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; |
10978 | |
10979 | private: |
10980 | /// A map from magic value to type information. |
10981 | std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> |
10982 | TypeTagForDatatypeMagicValues; |
10983 | |
10984 | /// Peform checks on a call of a function with argument_with_type_tag |
10985 | /// or pointer_with_type_tag attributes. |
10986 | void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, |
10987 | const ArrayRef<const Expr *> ExprArgs, |
10988 | SourceLocation CallSiteLoc); |
10989 | |
10990 | /// Check if we are taking the address of a packed field |
10991 | /// as this may be a problem if the pointer value is dereferenced. |
10992 | void CheckAddressOfPackedMember(Expr *rhs); |
10993 | |
10994 | /// The parser's current scope. |
10995 | /// |
10996 | /// The parser maintains this state here. |
10997 | Scope *CurScope; |
10998 | |
10999 | mutable IdentifierInfo *Ident_super; |
11000 | mutable IdentifierInfo *Ident___float128; |
11001 | |
11002 | /// Nullability type specifiers. |
11003 | IdentifierInfo *Ident__Nonnull = nullptr; |
11004 | IdentifierInfo *Ident__Nullable = nullptr; |
11005 | IdentifierInfo *Ident__Null_unspecified = nullptr; |
11006 | |
11007 | IdentifierInfo *Ident_NSError = nullptr; |
11008 | |
11009 | /// The handler for the FileChanged preprocessor events. |
11010 | /// |
11011 | /// Used for diagnostics that implement custom semantic analysis for #include |
11012 | /// directives, like -Wpragma-pack. |
11013 | sema::SemaPPCallbacks *SemaPPCallbackHandler; |
11014 | |
11015 | protected: |
11016 | friend class Parser; |
11017 | friend class InitializationSequence; |
11018 | friend class ASTReader; |
11019 | friend class ASTDeclReader; |
11020 | friend class ASTWriter; |
11021 | |
11022 | public: |
11023 | /// Retrieve the keyword associated |
11024 | IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); |
11025 | |
11026 | /// The struct behind the CFErrorRef pointer. |
11027 | RecordDecl *CFError = nullptr; |
11028 | |
11029 | /// Retrieve the identifier "NSError". |
11030 | IdentifierInfo *getNSErrorIdent(); |
11031 | |
11032 | /// Retrieve the parser's current scope. |
11033 | /// |
11034 | /// This routine must only be used when it is certain that semantic analysis |
11035 | /// and the parser are in precisely the same context, which is not the case |
11036 | /// when, e.g., we are performing any kind of template instantiation. |
11037 | /// Therefore, the only safe places to use this scope are in the parser |
11038 | /// itself and in routines directly invoked from the parser and *never* from |
11039 | /// template substitution or instantiation. |
11040 | Scope *getCurScope() const { return CurScope; } |
11041 | |
11042 | void incrementMSManglingNumber() const { |
11043 | return CurScope->incrementMSManglingNumber(); |
11044 | } |
11045 | |
11046 | IdentifierInfo *getSuperIdentifier() const; |
11047 | IdentifierInfo *getFloat128Identifier() const; |
11048 | |
11049 | Decl *getObjCDeclContext() const; |
11050 | |
11051 | DeclContext *getCurLexicalContext() const { |
11052 | return OriginalLexicalContext ? OriginalLexicalContext : CurContext; |
11053 | } |
11054 | |
11055 | const DeclContext *getCurObjCLexicalContext() const { |
11056 | const DeclContext *DC = getCurLexicalContext(); |
11057 | // A category implicitly has the attribute of the interface. |
11058 | if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) |
11059 | DC = CatD->getClassInterface(); |
11060 | return DC; |
11061 | } |
11062 | |
11063 | /// To be used for checking whether the arguments being passed to |
11064 | /// function exceeds the number of parameters expected for it. |
11065 | static bool TooManyArguments(size_t NumParams, size_t NumArgs, |
11066 | bool PartialOverloading = false) { |
11067 | // We check whether we're just after a comma in code-completion. |
11068 | if (NumArgs > 0 && PartialOverloading) |
11069 | return NumArgs + 1 > NumParams; // If so, we view as an extra argument. |
11070 | return NumArgs > NumParams; |
11071 | } |
11072 | |
11073 | // Emitting members of dllexported classes is delayed until the class |
11074 | // (including field initializers) is fully parsed. |
11075 | SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; |
11076 | |
11077 | private: |
11078 | class SavePendingParsedClassStateRAII { |
11079 | public: |
11080 | SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } |
11081 | |
11082 | ~SavePendingParsedClassStateRAII() { |
11083 | assert(S.DelayedOverridingExceptionSpecChecks.empty() &&((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 11084, __PRETTY_FUNCTION__)) |
11084 | "there shouldn't be any pending delayed exception spec checks")((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 11084, __PRETTY_FUNCTION__)); |
11085 | assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 11086, __PRETTY_FUNCTION__)) |
11086 | "there shouldn't be any pending delayed exception spec checks")((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 11086, __PRETTY_FUNCTION__)); |
11087 | assert(S.DelayedDllExportClasses.empty() &&((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 11088, __PRETTY_FUNCTION__)) |
11088 | "there shouldn't be any pending delayed DLL export classes")((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include/clang/Sema/Sema.h" , 11088, __PRETTY_FUNCTION__)); |
11089 | swapSavedState(); |
11090 | } |
11091 | |
11092 | private: |
11093 | Sema &S; |
11094 | decltype(DelayedOverridingExceptionSpecChecks) |
11095 | SavedOverridingExceptionSpecChecks; |
11096 | decltype(DelayedEquivalentExceptionSpecChecks) |
11097 | SavedEquivalentExceptionSpecChecks; |
11098 | decltype(DelayedDllExportClasses) SavedDllExportClasses; |
11099 | |
11100 | void swapSavedState() { |
11101 | SavedOverridingExceptionSpecChecks.swap( |
11102 | S.DelayedOverridingExceptionSpecChecks); |
11103 | SavedEquivalentExceptionSpecChecks.swap( |
11104 | S.DelayedEquivalentExceptionSpecChecks); |
11105 | SavedDllExportClasses.swap(S.DelayedDllExportClasses); |
11106 | } |
11107 | }; |
11108 | |
11109 | /// Helper class that collects misaligned member designations and |
11110 | /// their location info for delayed diagnostics. |
11111 | struct MisalignedMember { |
11112 | Expr *E; |
11113 | RecordDecl *RD; |
11114 | ValueDecl *MD; |
11115 | CharUnits Alignment; |
11116 | |
11117 | MisalignedMember() : E(), RD(), MD(), Alignment() {} |
11118 | MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, |
11119 | CharUnits Alignment) |
11120 | : E(E), RD(RD), MD(MD), Alignment(Alignment) {} |
11121 | explicit MisalignedMember(Expr *E) |
11122 | : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} |
11123 | |
11124 | bool operator==(const MisalignedMember &m) { return this->E == m.E; } |
11125 | }; |
11126 | /// Small set of gathered accesses to potentially misaligned members |
11127 | /// due to the packed attribute. |
11128 | SmallVector<MisalignedMember, 4> MisalignedMembers; |
11129 | |
11130 | /// Adds an expression to the set of gathered misaligned members. |
11131 | void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, |
11132 | CharUnits Alignment); |
11133 | |
11134 | public: |
11135 | /// Diagnoses the current set of gathered accesses. This typically |
11136 | /// happens at full expression level. The set is cleared after emitting the |
11137 | /// diagnostics. |
11138 | void DiagnoseMisalignedMembers(); |
11139 | |
11140 | /// This function checks if the expression is in the sef of potentially |
11141 | /// misaligned members and it is converted to some pointer type T with lower |
11142 | /// or equal alignment requirements. If so it removes it. This is used when |
11143 | /// we do not want to diagnose such misaligned access (e.g. in conversions to |
11144 | /// void*). |
11145 | void DiscardMisalignedMemberAddress(const Type *T, Expr *E); |
11146 | |
11147 | /// This function calls Action when it determines that E designates a |
11148 | /// misaligned member due to the packed attribute. This is used to emit |
11149 | /// local diagnostics like in reference binding. |
11150 | void RefersToMemberWithReducedAlignment( |
11151 | Expr *E, |
11152 | llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> |
11153 | Action); |
11154 | |
11155 | /// Describes the reason a calling convention specification was ignored, used |
11156 | /// for diagnostics. |
11157 | enum class CallingConventionIgnoredReason { |
11158 | ForThisTarget = 0, |
11159 | VariadicFunction, |
11160 | ConstructorDestructor, |
11161 | BuiltinFunction |
11162 | }; |
11163 | }; |
11164 | |
11165 | /// RAII object that enters a new expression evaluation context. |
11166 | class EnterExpressionEvaluationContext { |
11167 | Sema &Actions; |
11168 | bool Entered = true; |
11169 | |
11170 | public: |
11171 | EnterExpressionEvaluationContext( |
11172 | Sema &Actions, Sema::ExpressionEvaluationContext NewContext, |
11173 | Decl *LambdaContextDecl = nullptr, |
11174 | Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = |
11175 | Sema::ExpressionEvaluationContextRecord::EK_Other, |
11176 | bool ShouldEnter = true) |
11177 | : Actions(Actions), Entered(ShouldEnter) { |
11178 | if (Entered) |
11179 | Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, |
11180 | ExprContext); |
11181 | } |
11182 | EnterExpressionEvaluationContext( |
11183 | Sema &Actions, Sema::ExpressionEvaluationContext NewContext, |
11184 | Sema::ReuseLambdaContextDecl_t, |
11185 | Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = |
11186 | Sema::ExpressionEvaluationContextRecord::EK_Other) |
11187 | : Actions(Actions) { |
11188 | Actions.PushExpressionEvaluationContext( |
11189 | NewContext, Sema::ReuseLambdaContextDecl, ExprContext); |
11190 | } |
11191 | |
11192 | enum InitListTag { InitList }; |
11193 | EnterExpressionEvaluationContext(Sema &Actions, InitListTag, |
11194 | bool ShouldEnter = true) |
11195 | : Actions(Actions), Entered(false) { |
11196 | // In C++11 onwards, narrowing checks are performed on the contents of |
11197 | // braced-init-lists, even when they occur within unevaluated operands. |
11198 | // Therefore we still need to instantiate constexpr functions used in such |
11199 | // a context. |
11200 | if (ShouldEnter && Actions.isUnevaluatedContext() && |
11201 | Actions.getLangOpts().CPlusPlus11) { |
11202 | Actions.PushExpressionEvaluationContext( |
11203 | Sema::ExpressionEvaluationContext::UnevaluatedList); |
11204 | Entered = true; |
11205 | } |
11206 | } |
11207 | |
11208 | ~EnterExpressionEvaluationContext() { |
11209 | if (Entered) |
11210 | Actions.PopExpressionEvaluationContext(); |
11211 | } |
11212 | }; |
11213 | |
11214 | DeductionFailureInfo |
11215 | MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, |
11216 | sema::TemplateDeductionInfo &Info); |
11217 | |
11218 | /// Contains a late templated function. |
11219 | /// Will be parsed at the end of the translation unit, used by Sema & Parser. |
11220 | struct LateParsedTemplate { |
11221 | CachedTokens Toks; |
11222 | /// The template function declaration to be late parsed. |
11223 | Decl *D; |
11224 | }; |
11225 | } // end namespace clang |
11226 | |
11227 | namespace llvm { |
11228 | // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its |
11229 | // SourceLocation. |
11230 | template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { |
11231 | using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; |
11232 | using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; |
11233 | |
11234 | static FunctionDeclAndLoc getEmptyKey() { |
11235 | return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; |
11236 | } |
11237 | |
11238 | static FunctionDeclAndLoc getTombstoneKey() { |
11239 | return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; |
11240 | } |
11241 | |
11242 | static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { |
11243 | return hash_combine(FDBaseInfo::getHashValue(FDL.FD), |
11244 | FDL.Loc.getRawEncoding()); |
11245 | } |
11246 | |
11247 | static bool isEqual(const FunctionDeclAndLoc &LHS, |
11248 | const FunctionDeclAndLoc &RHS) { |
11249 | return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; |
11250 | } |
11251 | }; |
11252 | } // namespace llvm |
11253 | |
11254 | #endif |