File: | tools/clang/lib/Sema/SemaType.cpp |
Warning: | line 2199, column 8 Potential leak of memory pointed to by field 'DiagStorage' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// | |||
2 | // | |||
3 | // The LLVM Compiler Infrastructure | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | // | |||
10 | // This file implements type-related semantic analysis. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "TypeLocBuilder.h" | |||
15 | #include "clang/AST/ASTConsumer.h" | |||
16 | #include "clang/AST/ASTContext.h" | |||
17 | #include "clang/AST/ASTMutationListener.h" | |||
18 | #include "clang/AST/ASTStructuralEquivalence.h" | |||
19 | #include "clang/AST/CXXInheritance.h" | |||
20 | #include "clang/AST/DeclObjC.h" | |||
21 | #include "clang/AST/DeclTemplate.h" | |||
22 | #include "clang/AST/Expr.h" | |||
23 | #include "clang/AST/TypeLoc.h" | |||
24 | #include "clang/AST/TypeLocVisitor.h" | |||
25 | #include "clang/Basic/PartialDiagnostic.h" | |||
26 | #include "clang/Basic/TargetInfo.h" | |||
27 | #include "clang/Lex/Preprocessor.h" | |||
28 | #include "clang/Sema/DeclSpec.h" | |||
29 | #include "clang/Sema/DelayedDiagnostic.h" | |||
30 | #include "clang/Sema/Lookup.h" | |||
31 | #include "clang/Sema/ScopeInfo.h" | |||
32 | #include "clang/Sema/SemaInternal.h" | |||
33 | #include "clang/Sema/Template.h" | |||
34 | #include "clang/Sema/TemplateInstCallback.h" | |||
35 | #include "llvm/ADT/SmallPtrSet.h" | |||
36 | #include "llvm/ADT/SmallString.h" | |||
37 | #include "llvm/ADT/StringSwitch.h" | |||
38 | #include "llvm/Support/ErrorHandling.h" | |||
39 | ||||
40 | using namespace clang; | |||
41 | ||||
42 | enum TypeDiagSelector { | |||
43 | TDS_Function, | |||
44 | TDS_Pointer, | |||
45 | TDS_ObjCObjOrBlock | |||
46 | }; | |||
47 | ||||
48 | /// isOmittedBlockReturnType - Return true if this declarator is missing a | |||
49 | /// return type because this is a omitted return type on a block literal. | |||
50 | static bool isOmittedBlockReturnType(const Declarator &D) { | |||
51 | if (D.getContext() != DeclaratorContext::BlockLiteralContext || | |||
52 | D.getDeclSpec().hasTypeSpecifier()) | |||
53 | return false; | |||
54 | ||||
55 | if (D.getNumTypeObjects() == 0) | |||
56 | return true; // ^{ ... } | |||
57 | ||||
58 | if (D.getNumTypeObjects() == 1 && | |||
59 | D.getTypeObject(0).Kind == DeclaratorChunk::Function) | |||
60 | return true; // ^(int X, float Y) { ... } | |||
61 | ||||
62 | return false; | |||
63 | } | |||
64 | ||||
65 | /// diagnoseBadTypeAttribute - Diagnoses a type attribute which | |||
66 | /// doesn't apply to the given type. | |||
67 | static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, | |||
68 | QualType type) { | |||
69 | TypeDiagSelector WhichType; | |||
70 | bool useExpansionLoc = true; | |||
71 | switch (attr.getKind()) { | |||
72 | case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break; | |||
73 | case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break; | |||
74 | default: | |||
75 | // Assume everything else was a function attribute. | |||
76 | WhichType = TDS_Function; | |||
77 | useExpansionLoc = false; | |||
78 | break; | |||
79 | } | |||
80 | ||||
81 | SourceLocation loc = attr.getLoc(); | |||
82 | StringRef name = attr.getName()->getName(); | |||
83 | ||||
84 | // The GC attributes are usually written with macros; special-case them. | |||
85 | IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident | |||
86 | : nullptr; | |||
87 | if (useExpansionLoc && loc.isMacroID() && II) { | |||
88 | if (II->isStr("strong")) { | |||
89 | if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; | |||
90 | } else if (II->isStr("weak")) { | |||
91 | if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; | |||
92 | } | |||
93 | } | |||
94 | ||||
95 | S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType | |||
96 | << type; | |||
97 | } | |||
98 | ||||
99 | // objc_gc applies to Objective-C pointers or, otherwise, to the | |||
100 | // smallest available pointer type (i.e. 'void*' in 'void**'). | |||
101 | #define OBJC_POINTER_TYPE_ATTRS_CASELISTcase AttributeList::AT_ObjCGC: case AttributeList::AT_ObjCOwnership \ | |||
102 | case AttributeList::AT_ObjCGC: \ | |||
103 | case AttributeList::AT_ObjCOwnership | |||
104 | ||||
105 | // Calling convention attributes. | |||
106 | #define CALLING_CONV_ATTRS_CASELISTcase AttributeList::AT_CDecl: case AttributeList::AT_FastCall : case AttributeList::AT_StdCall: case AttributeList::AT_ThisCall : case AttributeList::AT_RegCall: case AttributeList::AT_Pascal : case AttributeList::AT_SwiftCall: case AttributeList::AT_VectorCall : case AttributeList::AT_MSABI: case AttributeList::AT_SysVABI : case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc : case AttributeList::AT_PreserveMost: case AttributeList::AT_PreserveAll \ | |||
107 | case AttributeList::AT_CDecl: \ | |||
108 | case AttributeList::AT_FastCall: \ | |||
109 | case AttributeList::AT_StdCall: \ | |||
110 | case AttributeList::AT_ThisCall: \ | |||
111 | case AttributeList::AT_RegCall: \ | |||
112 | case AttributeList::AT_Pascal: \ | |||
113 | case AttributeList::AT_SwiftCall: \ | |||
114 | case AttributeList::AT_VectorCall: \ | |||
115 | case AttributeList::AT_MSABI: \ | |||
116 | case AttributeList::AT_SysVABI: \ | |||
117 | case AttributeList::AT_Pcs: \ | |||
118 | case AttributeList::AT_IntelOclBicc: \ | |||
119 | case AttributeList::AT_PreserveMost: \ | |||
120 | case AttributeList::AT_PreserveAll | |||
121 | ||||
122 | // Function type attributes. | |||
123 | #define FUNCTION_TYPE_ATTRS_CASELISTcase AttributeList::AT_NSReturnsRetained: case AttributeList:: AT_NoReturn: case AttributeList::AT_Regparm: case AttributeList ::AT_AnyX86NoCallerSavedRegisters: case AttributeList::AT_CDecl : case AttributeList::AT_FastCall: case AttributeList::AT_StdCall : case AttributeList::AT_ThisCall: case AttributeList::AT_RegCall : case AttributeList::AT_Pascal: case AttributeList::AT_SwiftCall : case AttributeList::AT_VectorCall: case AttributeList::AT_MSABI : case AttributeList::AT_SysVABI: case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc: case AttributeList::AT_PreserveMost : case AttributeList::AT_PreserveAll \ | |||
124 | case AttributeList::AT_NSReturnsRetained: \ | |||
125 | case AttributeList::AT_NoReturn: \ | |||
126 | case AttributeList::AT_Regparm: \ | |||
127 | case AttributeList::AT_AnyX86NoCallerSavedRegisters: \ | |||
128 | CALLING_CONV_ATTRS_CASELISTcase AttributeList::AT_CDecl: case AttributeList::AT_FastCall : case AttributeList::AT_StdCall: case AttributeList::AT_ThisCall : case AttributeList::AT_RegCall: case AttributeList::AT_Pascal : case AttributeList::AT_SwiftCall: case AttributeList::AT_VectorCall : case AttributeList::AT_MSABI: case AttributeList::AT_SysVABI : case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc : case AttributeList::AT_PreserveMost: case AttributeList::AT_PreserveAll | |||
129 | ||||
130 | // Microsoft-specific type qualifiers. | |||
131 | #define MS_TYPE_ATTRS_CASELISTcase AttributeList::AT_Ptr32: case AttributeList::AT_Ptr64: case AttributeList::AT_SPtr: case AttributeList::AT_UPtr \ | |||
132 | case AttributeList::AT_Ptr32: \ | |||
133 | case AttributeList::AT_Ptr64: \ | |||
134 | case AttributeList::AT_SPtr: \ | |||
135 | case AttributeList::AT_UPtr | |||
136 | ||||
137 | // Nullability qualifiers. | |||
138 | #define NULLABILITY_TYPE_ATTRS_CASELISTcase AttributeList::AT_TypeNonNull: case AttributeList::AT_TypeNullable : case AttributeList::AT_TypeNullUnspecified \ | |||
139 | case AttributeList::AT_TypeNonNull: \ | |||
140 | case AttributeList::AT_TypeNullable: \ | |||
141 | case AttributeList::AT_TypeNullUnspecified | |||
142 | ||||
143 | namespace { | |||
144 | /// An object which stores processing state for the entire | |||
145 | /// GetTypeForDeclarator process. | |||
146 | class TypeProcessingState { | |||
147 | Sema &sema; | |||
148 | ||||
149 | /// The declarator being processed. | |||
150 | Declarator &declarator; | |||
151 | ||||
152 | /// The index of the declarator chunk we're currently processing. | |||
153 | /// May be the total number of valid chunks, indicating the | |||
154 | /// DeclSpec. | |||
155 | unsigned chunkIndex; | |||
156 | ||||
157 | /// Whether there are non-trivial modifications to the decl spec. | |||
158 | bool trivial; | |||
159 | ||||
160 | /// Whether we saved the attributes in the decl spec. | |||
161 | bool hasSavedAttrs; | |||
162 | ||||
163 | /// The original set of attributes on the DeclSpec. | |||
164 | SmallVector<AttributeList*, 2> savedAttrs; | |||
165 | ||||
166 | /// A list of attributes to diagnose the uselessness of when the | |||
167 | /// processing is complete. | |||
168 | SmallVector<AttributeList*, 2> ignoredTypeAttrs; | |||
169 | ||||
170 | public: | |||
171 | TypeProcessingState(Sema &sema, Declarator &declarator) | |||
172 | : sema(sema), declarator(declarator), | |||
173 | chunkIndex(declarator.getNumTypeObjects()), | |||
174 | trivial(true), hasSavedAttrs(false) {} | |||
175 | ||||
176 | Sema &getSema() const { | |||
177 | return sema; | |||
178 | } | |||
179 | ||||
180 | Declarator &getDeclarator() const { | |||
181 | return declarator; | |||
182 | } | |||
183 | ||||
184 | bool isProcessingDeclSpec() const { | |||
185 | return chunkIndex == declarator.getNumTypeObjects(); | |||
186 | } | |||
187 | ||||
188 | unsigned getCurrentChunkIndex() const { | |||
189 | return chunkIndex; | |||
190 | } | |||
191 | ||||
192 | void setCurrentChunkIndex(unsigned idx) { | |||
193 | assert(idx <= declarator.getNumTypeObjects())(static_cast <bool> (idx <= declarator.getNumTypeObjects ()) ? void (0) : __assert_fail ("idx <= declarator.getNumTypeObjects()" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 193, __extension__ __PRETTY_FUNCTION__)); | |||
194 | chunkIndex = idx; | |||
195 | } | |||
196 | ||||
197 | AttributeList *&getCurrentAttrListRef() const { | |||
198 | if (isProcessingDeclSpec()) | |||
199 | return getMutableDeclSpec().getAttributes().getListRef(); | |||
200 | return declarator.getTypeObject(chunkIndex).getAttrListRef(); | |||
201 | } | |||
202 | ||||
203 | /// Save the current set of attributes on the DeclSpec. | |||
204 | void saveDeclSpecAttrs() { | |||
205 | // Don't try to save them multiple times. | |||
206 | if (hasSavedAttrs) return; | |||
207 | ||||
208 | DeclSpec &spec = getMutableDeclSpec(); | |||
209 | for (AttributeList *attr = spec.getAttributes().getList(); attr; | |||
210 | attr = attr->getNext()) | |||
211 | savedAttrs.push_back(attr); | |||
212 | trivial &= savedAttrs.empty(); | |||
213 | hasSavedAttrs = true; | |||
214 | } | |||
215 | ||||
216 | /// Record that we had nowhere to put the given type attribute. | |||
217 | /// We will diagnose such attributes later. | |||
218 | void addIgnoredTypeAttr(AttributeList &attr) { | |||
219 | ignoredTypeAttrs.push_back(&attr); | |||
220 | } | |||
221 | ||||
222 | /// Diagnose all the ignored type attributes, given that the | |||
223 | /// declarator worked out to the given type. | |||
224 | void diagnoseIgnoredTypeAttrs(QualType type) const { | |||
225 | for (auto *Attr : ignoredTypeAttrs) | |||
226 | diagnoseBadTypeAttribute(getSema(), *Attr, type); | |||
227 | } | |||
228 | ||||
229 | ~TypeProcessingState() { | |||
230 | if (trivial) return; | |||
231 | ||||
232 | restoreDeclSpecAttrs(); | |||
233 | } | |||
234 | ||||
235 | private: | |||
236 | DeclSpec &getMutableDeclSpec() const { | |||
237 | return const_cast<DeclSpec&>(declarator.getDeclSpec()); | |||
238 | } | |||
239 | ||||
240 | void restoreDeclSpecAttrs() { | |||
241 | assert(hasSavedAttrs)(static_cast <bool> (hasSavedAttrs) ? void (0) : __assert_fail ("hasSavedAttrs", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 241, __extension__ __PRETTY_FUNCTION__)); | |||
242 | ||||
243 | if (savedAttrs.empty()) { | |||
244 | getMutableDeclSpec().getAttributes().set(nullptr); | |||
245 | return; | |||
246 | } | |||
247 | ||||
248 | getMutableDeclSpec().getAttributes().set(savedAttrs[0]); | |||
249 | for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) | |||
250 | savedAttrs[i]->setNext(savedAttrs[i+1]); | |||
251 | savedAttrs.back()->setNext(nullptr); | |||
252 | } | |||
253 | }; | |||
254 | } // end anonymous namespace | |||
255 | ||||
256 | static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { | |||
257 | attr.setNext(head); | |||
258 | head = &attr; | |||
259 | } | |||
260 | ||||
261 | static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { | |||
262 | if (head == &attr) { | |||
263 | head = attr.getNext(); | |||
264 | return; | |||
265 | } | |||
266 | ||||
267 | AttributeList *cur = head; | |||
268 | while (true) { | |||
269 | assert(cur && cur->getNext() && "ran out of attrs?")(static_cast <bool> (cur && cur->getNext() && "ran out of attrs?") ? void (0) : __assert_fail ("cur && cur->getNext() && \"ran out of attrs?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 269, __extension__ __PRETTY_FUNCTION__)); | |||
270 | if (cur->getNext() == &attr) { | |||
271 | cur->setNext(attr.getNext()); | |||
272 | return; | |||
273 | } | |||
274 | cur = cur->getNext(); | |||
275 | } | |||
276 | } | |||
277 | ||||
278 | static void moveAttrFromListToList(AttributeList &attr, | |||
279 | AttributeList *&fromList, | |||
280 | AttributeList *&toList) { | |||
281 | spliceAttrOutOfList(attr, fromList); | |||
282 | spliceAttrIntoList(attr, toList); | |||
283 | } | |||
284 | ||||
285 | /// The location of a type attribute. | |||
286 | enum TypeAttrLocation { | |||
287 | /// The attribute is in the decl-specifier-seq. | |||
288 | TAL_DeclSpec, | |||
289 | /// The attribute is part of a DeclaratorChunk. | |||
290 | TAL_DeclChunk, | |||
291 | /// The attribute is immediately after the declaration's name. | |||
292 | TAL_DeclName | |||
293 | }; | |||
294 | ||||
295 | static void processTypeAttrs(TypeProcessingState &state, | |||
296 | QualType &type, TypeAttrLocation TAL, | |||
297 | AttributeList *attrs); | |||
298 | ||||
299 | static bool handleFunctionTypeAttr(TypeProcessingState &state, | |||
300 | AttributeList &attr, | |||
301 | QualType &type); | |||
302 | ||||
303 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, | |||
304 | AttributeList &attr, | |||
305 | QualType &type); | |||
306 | ||||
307 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, | |||
308 | AttributeList &attr, QualType &type); | |||
309 | ||||
310 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | |||
311 | AttributeList &attr, QualType &type); | |||
312 | ||||
313 | static bool handleObjCPointerTypeAttr(TypeProcessingState &state, | |||
314 | AttributeList &attr, QualType &type) { | |||
315 | if (attr.getKind() == AttributeList::AT_ObjCGC) | |||
316 | return handleObjCGCTypeAttr(state, attr, type); | |||
317 | assert(attr.getKind() == AttributeList::AT_ObjCOwnership)(static_cast <bool> (attr.getKind() == AttributeList::AT_ObjCOwnership ) ? void (0) : __assert_fail ("attr.getKind() == AttributeList::AT_ObjCOwnership" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 317, __extension__ __PRETTY_FUNCTION__)); | |||
318 | return handleObjCOwnershipTypeAttr(state, attr, type); | |||
319 | } | |||
320 | ||||
321 | /// Given the index of a declarator chunk, check whether that chunk | |||
322 | /// directly specifies the return type of a function and, if so, find | |||
323 | /// an appropriate place for it. | |||
324 | /// | |||
325 | /// \param i - a notional index which the search will start | |||
326 | /// immediately inside | |||
327 | /// | |||
328 | /// \param onlyBlockPointers Whether we should only look into block | |||
329 | /// pointer types (vs. all pointer types). | |||
330 | static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, | |||
331 | unsigned i, | |||
332 | bool onlyBlockPointers) { | |||
333 | assert(i <= declarator.getNumTypeObjects())(static_cast <bool> (i <= declarator.getNumTypeObjects ()) ? void (0) : __assert_fail ("i <= declarator.getNumTypeObjects()" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 333, __extension__ __PRETTY_FUNCTION__)); | |||
334 | ||||
335 | DeclaratorChunk *result = nullptr; | |||
336 | ||||
337 | // First, look inwards past parens for a function declarator. | |||
338 | for (; i != 0; --i) { | |||
339 | DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); | |||
340 | switch (fnChunk.Kind) { | |||
341 | case DeclaratorChunk::Paren: | |||
342 | continue; | |||
343 | ||||
344 | // If we find anything except a function, bail out. | |||
345 | case DeclaratorChunk::Pointer: | |||
346 | case DeclaratorChunk::BlockPointer: | |||
347 | case DeclaratorChunk::Array: | |||
348 | case DeclaratorChunk::Reference: | |||
349 | case DeclaratorChunk::MemberPointer: | |||
350 | case DeclaratorChunk::Pipe: | |||
351 | return result; | |||
352 | ||||
353 | // If we do find a function declarator, scan inwards from that, | |||
354 | // looking for a (block-)pointer declarator. | |||
355 | case DeclaratorChunk::Function: | |||
356 | for (--i; i != 0; --i) { | |||
357 | DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); | |||
358 | switch (ptrChunk.Kind) { | |||
359 | case DeclaratorChunk::Paren: | |||
360 | case DeclaratorChunk::Array: | |||
361 | case DeclaratorChunk::Function: | |||
362 | case DeclaratorChunk::Reference: | |||
363 | case DeclaratorChunk::Pipe: | |||
364 | continue; | |||
365 | ||||
366 | case DeclaratorChunk::MemberPointer: | |||
367 | case DeclaratorChunk::Pointer: | |||
368 | if (onlyBlockPointers) | |||
369 | continue; | |||
370 | ||||
371 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
372 | ||||
373 | case DeclaratorChunk::BlockPointer: | |||
374 | result = &ptrChunk; | |||
375 | goto continue_outer; | |||
376 | } | |||
377 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 377); | |||
378 | } | |||
379 | ||||
380 | // If we run out of declarators doing that, we're done. | |||
381 | return result; | |||
382 | } | |||
383 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 383); | |||
384 | ||||
385 | // Okay, reconsider from our new point. | |||
386 | continue_outer: ; | |||
387 | } | |||
388 | ||||
389 | // Ran out of chunks, bail out. | |||
390 | return result; | |||
391 | } | |||
392 | ||||
393 | /// Given that an objc_gc attribute was written somewhere on a | |||
394 | /// declaration *other* than on the declarator itself (for which, use | |||
395 | /// distributeObjCPointerTypeAttrFromDeclarator), and given that it | |||
396 | /// didn't apply in whatever position it was written in, try to move | |||
397 | /// it to a more appropriate position. | |||
398 | static void distributeObjCPointerTypeAttr(TypeProcessingState &state, | |||
399 | AttributeList &attr, | |||
400 | QualType type) { | |||
401 | Declarator &declarator = state.getDeclarator(); | |||
402 | ||||
403 | // Move it to the outermost normal or block pointer declarator. | |||
404 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
405 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
406 | switch (chunk.Kind) { | |||
407 | case DeclaratorChunk::Pointer: | |||
408 | case DeclaratorChunk::BlockPointer: { | |||
409 | // But don't move an ARC ownership attribute to the return type | |||
410 | // of a block. | |||
411 | DeclaratorChunk *destChunk = nullptr; | |||
412 | if (state.isProcessingDeclSpec() && | |||
413 | attr.getKind() == AttributeList::AT_ObjCOwnership) | |||
414 | destChunk = maybeMovePastReturnType(declarator, i - 1, | |||
415 | /*onlyBlockPointers=*/true); | |||
416 | if (!destChunk) destChunk = &chunk; | |||
417 | ||||
418 | moveAttrFromListToList(attr, state.getCurrentAttrListRef(), | |||
419 | destChunk->getAttrListRef()); | |||
420 | return; | |||
421 | } | |||
422 | ||||
423 | case DeclaratorChunk::Paren: | |||
424 | case DeclaratorChunk::Array: | |||
425 | continue; | |||
426 | ||||
427 | // We may be starting at the return type of a block. | |||
428 | case DeclaratorChunk::Function: | |||
429 | if (state.isProcessingDeclSpec() && | |||
430 | attr.getKind() == AttributeList::AT_ObjCOwnership) { | |||
431 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | |||
432 | declarator, i, | |||
433 | /*onlyBlockPointers=*/true)) { | |||
434 | moveAttrFromListToList(attr, state.getCurrentAttrListRef(), | |||
435 | dest->getAttrListRef()); | |||
436 | return; | |||
437 | } | |||
438 | } | |||
439 | goto error; | |||
440 | ||||
441 | // Don't walk through these. | |||
442 | case DeclaratorChunk::Reference: | |||
443 | case DeclaratorChunk::MemberPointer: | |||
444 | case DeclaratorChunk::Pipe: | |||
445 | goto error; | |||
446 | } | |||
447 | } | |||
448 | error: | |||
449 | ||||
450 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | |||
451 | } | |||
452 | ||||
453 | /// Distribute an objc_gc type attribute that was written on the | |||
454 | /// declarator. | |||
455 | static void | |||
456 | distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, | |||
457 | AttributeList &attr, | |||
458 | QualType &declSpecType) { | |||
459 | Declarator &declarator = state.getDeclarator(); | |||
460 | ||||
461 | // objc_gc goes on the innermost pointer to something that's not a | |||
462 | // pointer. | |||
463 | unsigned innermost = -1U; | |||
464 | bool considerDeclSpec = true; | |||
465 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
466 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
467 | switch (chunk.Kind) { | |||
468 | case DeclaratorChunk::Pointer: | |||
469 | case DeclaratorChunk::BlockPointer: | |||
470 | innermost = i; | |||
471 | continue; | |||
472 | ||||
473 | case DeclaratorChunk::Reference: | |||
474 | case DeclaratorChunk::MemberPointer: | |||
475 | case DeclaratorChunk::Paren: | |||
476 | case DeclaratorChunk::Array: | |||
477 | case DeclaratorChunk::Pipe: | |||
478 | continue; | |||
479 | ||||
480 | case DeclaratorChunk::Function: | |||
481 | considerDeclSpec = false; | |||
482 | goto done; | |||
483 | } | |||
484 | } | |||
485 | done: | |||
486 | ||||
487 | // That might actually be the decl spec if we weren't blocked by | |||
488 | // anything in the declarator. | |||
489 | if (considerDeclSpec) { | |||
490 | if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { | |||
491 | // Splice the attribute into the decl spec. Prevents the | |||
492 | // attribute from being applied multiple times and gives | |||
493 | // the source-location-filler something to work with. | |||
494 | state.saveDeclSpecAttrs(); | |||
495 | moveAttrFromListToList(attr, declarator.getAttrListRef(), | |||
496 | declarator.getMutableDeclSpec().getAttributes().getListRef()); | |||
497 | return; | |||
498 | } | |||
499 | } | |||
500 | ||||
501 | // Otherwise, if we found an appropriate chunk, splice the attribute | |||
502 | // into it. | |||
503 | if (innermost != -1U) { | |||
504 | moveAttrFromListToList(attr, declarator.getAttrListRef(), | |||
505 | declarator.getTypeObject(innermost).getAttrListRef()); | |||
506 | return; | |||
507 | } | |||
508 | ||||
509 | // Otherwise, diagnose when we're done building the type. | |||
510 | spliceAttrOutOfList(attr, declarator.getAttrListRef()); | |||
511 | state.addIgnoredTypeAttr(attr); | |||
512 | } | |||
513 | ||||
514 | /// A function type attribute was written somewhere in a declaration | |||
515 | /// *other* than on the declarator itself or in the decl spec. Given | |||
516 | /// that it didn't apply in whatever position it was written in, try | |||
517 | /// to move it to a more appropriate position. | |||
518 | static void distributeFunctionTypeAttr(TypeProcessingState &state, | |||
519 | AttributeList &attr, | |||
520 | QualType type) { | |||
521 | Declarator &declarator = state.getDeclarator(); | |||
522 | ||||
523 | // Try to push the attribute from the return type of a function to | |||
524 | // the function itself. | |||
525 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
526 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
527 | switch (chunk.Kind) { | |||
528 | case DeclaratorChunk::Function: | |||
529 | moveAttrFromListToList(attr, state.getCurrentAttrListRef(), | |||
530 | chunk.getAttrListRef()); | |||
531 | return; | |||
532 | ||||
533 | case DeclaratorChunk::Paren: | |||
534 | case DeclaratorChunk::Pointer: | |||
535 | case DeclaratorChunk::BlockPointer: | |||
536 | case DeclaratorChunk::Array: | |||
537 | case DeclaratorChunk::Reference: | |||
538 | case DeclaratorChunk::MemberPointer: | |||
539 | case DeclaratorChunk::Pipe: | |||
540 | continue; | |||
541 | } | |||
542 | } | |||
543 | ||||
544 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | |||
545 | } | |||
546 | ||||
547 | /// Try to distribute a function type attribute to the innermost | |||
548 | /// function chunk or type. Returns true if the attribute was | |||
549 | /// distributed, false if no location was found. | |||
550 | static bool | |||
551 | distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, | |||
552 | AttributeList &attr, | |||
553 | AttributeList *&attrList, | |||
554 | QualType &declSpecType) { | |||
555 | Declarator &declarator = state.getDeclarator(); | |||
556 | ||||
557 | // Put it on the innermost function chunk, if there is one. | |||
558 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
559 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
560 | if (chunk.Kind != DeclaratorChunk::Function) continue; | |||
561 | ||||
562 | moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); | |||
563 | return true; | |||
564 | } | |||
565 | ||||
566 | return handleFunctionTypeAttr(state, attr, declSpecType); | |||
567 | } | |||
568 | ||||
569 | /// A function type attribute was written in the decl spec. Try to | |||
570 | /// apply it somewhere. | |||
571 | static void | |||
572 | distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, | |||
573 | AttributeList &attr, | |||
574 | QualType &declSpecType) { | |||
575 | state.saveDeclSpecAttrs(); | |||
576 | ||||
577 | // C++11 attributes before the decl specifiers actually appertain to | |||
578 | // the declarators. Move them straight there. We don't support the | |||
579 | // 'put them wherever you like' semantics we allow for GNU attributes. | |||
580 | if (attr.isCXX11Attribute()) { | |||
581 | moveAttrFromListToList(attr, state.getCurrentAttrListRef(), | |||
582 | state.getDeclarator().getAttrListRef()); | |||
583 | return; | |||
584 | } | |||
585 | ||||
586 | // Try to distribute to the innermost. | |||
587 | if (distributeFunctionTypeAttrToInnermost(state, attr, | |||
588 | state.getCurrentAttrListRef(), | |||
589 | declSpecType)) | |||
590 | return; | |||
591 | ||||
592 | // If that failed, diagnose the bad attribute when the declarator is | |||
593 | // fully built. | |||
594 | state.addIgnoredTypeAttr(attr); | |||
595 | } | |||
596 | ||||
597 | /// A function type attribute was written on the declarator. Try to | |||
598 | /// apply it somewhere. | |||
599 | static void | |||
600 | distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, | |||
601 | AttributeList &attr, | |||
602 | QualType &declSpecType) { | |||
603 | Declarator &declarator = state.getDeclarator(); | |||
604 | ||||
605 | // Try to distribute to the innermost. | |||
606 | if (distributeFunctionTypeAttrToInnermost(state, attr, | |||
607 | declarator.getAttrListRef(), | |||
608 | declSpecType)) | |||
609 | return; | |||
610 | ||||
611 | // If that failed, diagnose the bad attribute when the declarator is | |||
612 | // fully built. | |||
613 | spliceAttrOutOfList(attr, declarator.getAttrListRef()); | |||
614 | state.addIgnoredTypeAttr(attr); | |||
615 | } | |||
616 | ||||
617 | /// \brief Given that there are attributes written on the declarator | |||
618 | /// itself, try to distribute any type attributes to the appropriate | |||
619 | /// declarator chunk. | |||
620 | /// | |||
621 | /// These are attributes like the following: | |||
622 | /// int f ATTR; | |||
623 | /// int (f ATTR)(); | |||
624 | /// but not necessarily this: | |||
625 | /// int f() ATTR; | |||
626 | static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, | |||
627 | QualType &declSpecType) { | |||
628 | // Collect all the type attributes from the declarator itself. | |||
629 | assert(state.getDeclarator().getAttributes() && "declarator has no attrs!")(static_cast <bool> (state.getDeclarator().getAttributes () && "declarator has no attrs!") ? void (0) : __assert_fail ("state.getDeclarator().getAttributes() && \"declarator has no attrs!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 629, __extension__ __PRETTY_FUNCTION__)); | |||
630 | AttributeList *attr = state.getDeclarator().getAttributes(); | |||
631 | AttributeList *next; | |||
632 | do { | |||
633 | next = attr->getNext(); | |||
634 | ||||
635 | // Do not distribute C++11 attributes. They have strict rules for what | |||
636 | // they appertain to. | |||
637 | if (attr->isCXX11Attribute()) | |||
638 | continue; | |||
639 | ||||
640 | switch (attr->getKind()) { | |||
641 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase AttributeList::AT_ObjCGC: case AttributeList::AT_ObjCOwnership: | |||
642 | distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); | |||
643 | break; | |||
644 | ||||
645 | FUNCTION_TYPE_ATTRS_CASELISTcase AttributeList::AT_NSReturnsRetained: case AttributeList:: AT_NoReturn: case AttributeList::AT_Regparm: case AttributeList ::AT_AnyX86NoCallerSavedRegisters: case AttributeList::AT_CDecl : case AttributeList::AT_FastCall: case AttributeList::AT_StdCall : case AttributeList::AT_ThisCall: case AttributeList::AT_RegCall : case AttributeList::AT_Pascal: case AttributeList::AT_SwiftCall : case AttributeList::AT_VectorCall: case AttributeList::AT_MSABI : case AttributeList::AT_SysVABI: case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc: case AttributeList::AT_PreserveMost : case AttributeList::AT_PreserveAll: | |||
646 | distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); | |||
647 | break; | |||
648 | ||||
649 | MS_TYPE_ATTRS_CASELISTcase AttributeList::AT_Ptr32: case AttributeList::AT_Ptr64: case AttributeList::AT_SPtr: case AttributeList::AT_UPtr: | |||
650 | // Microsoft type attributes cannot go after the declarator-id. | |||
651 | continue; | |||
652 | ||||
653 | NULLABILITY_TYPE_ATTRS_CASELISTcase AttributeList::AT_TypeNonNull: case AttributeList::AT_TypeNullable : case AttributeList::AT_TypeNullUnspecified: | |||
654 | // Nullability specifiers cannot go after the declarator-id. | |||
655 | ||||
656 | // Objective-C __kindof does not get distributed. | |||
657 | case AttributeList::AT_ObjCKindOf: | |||
658 | continue; | |||
659 | ||||
660 | default: | |||
661 | break; | |||
662 | } | |||
663 | } while ((attr = next)); | |||
664 | } | |||
665 | ||||
666 | /// Add a synthetic '()' to a block-literal declarator if it is | |||
667 | /// required, given the return type. | |||
668 | static void maybeSynthesizeBlockSignature(TypeProcessingState &state, | |||
669 | QualType declSpecType) { | |||
670 | Declarator &declarator = state.getDeclarator(); | |||
671 | ||||
672 | // First, check whether the declarator would produce a function, | |||
673 | // i.e. whether the innermost semantic chunk is a function. | |||
674 | if (declarator.isFunctionDeclarator()) { | |||
675 | // If so, make that declarator a prototyped declarator. | |||
676 | declarator.getFunctionTypeInfo().hasPrototype = true; | |||
677 | return; | |||
678 | } | |||
679 | ||||
680 | // If there are any type objects, the type as written won't name a | |||
681 | // function, regardless of the decl spec type. This is because a | |||
682 | // block signature declarator is always an abstract-declarator, and | |||
683 | // abstract-declarators can't just be parentheses chunks. Therefore | |||
684 | // we need to build a function chunk unless there are no type | |||
685 | // objects and the decl spec type is a function. | |||
686 | if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) | |||
687 | return; | |||
688 | ||||
689 | // Note that there *are* cases with invalid declarators where | |||
690 | // declarators consist solely of parentheses. In general, these | |||
691 | // occur only in failed efforts to make function declarators, so | |||
692 | // faking up the function chunk is still the right thing to do. | |||
693 | ||||
694 | // Otherwise, we need to fake up a function declarator. | |||
695 | SourceLocation loc = declarator.getLocStart(); | |||
696 | ||||
697 | // ...and *prepend* it to the declarator. | |||
698 | SourceLocation NoLoc; | |||
699 | declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( | |||
700 | /*HasProto=*/true, | |||
701 | /*IsAmbiguous=*/false, | |||
702 | /*LParenLoc=*/NoLoc, | |||
703 | /*ArgInfo=*/nullptr, | |||
704 | /*NumArgs=*/0, | |||
705 | /*EllipsisLoc=*/NoLoc, | |||
706 | /*RParenLoc=*/NoLoc, | |||
707 | /*TypeQuals=*/0, | |||
708 | /*RefQualifierIsLvalueRef=*/true, | |||
709 | /*RefQualifierLoc=*/NoLoc, | |||
710 | /*ConstQualifierLoc=*/NoLoc, | |||
711 | /*VolatileQualifierLoc=*/NoLoc, | |||
712 | /*RestrictQualifierLoc=*/NoLoc, | |||
713 | /*MutableLoc=*/NoLoc, EST_None, | |||
714 | /*ESpecRange=*/SourceRange(), | |||
715 | /*Exceptions=*/nullptr, | |||
716 | /*ExceptionRanges=*/nullptr, | |||
717 | /*NumExceptions=*/0, | |||
718 | /*NoexceptExpr=*/nullptr, | |||
719 | /*ExceptionSpecTokens=*/nullptr, | |||
720 | /*DeclsInPrototype=*/None, | |||
721 | loc, loc, declarator)); | |||
722 | ||||
723 | // For consistency, make sure the state still has us as processing | |||
724 | // the decl spec. | |||
725 | assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1)(static_cast <bool> (state.getCurrentChunkIndex() == declarator .getNumTypeObjects() - 1) ? void (0) : __assert_fail ("state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 725, __extension__ __PRETTY_FUNCTION__)); | |||
726 | state.setCurrentChunkIndex(declarator.getNumTypeObjects()); | |||
727 | } | |||
728 | ||||
729 | static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, | |||
730 | unsigned &TypeQuals, | |||
731 | QualType TypeSoFar, | |||
732 | unsigned RemoveTQs, | |||
733 | unsigned DiagID) { | |||
734 | // If this occurs outside a template instantiation, warn the user about | |||
735 | // it; they probably didn't mean to specify a redundant qualifier. | |||
736 | typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; | |||
737 | for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), | |||
738 | QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), | |||
739 | QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), | |||
740 | QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { | |||
741 | if (!(RemoveTQs & Qual.first)) | |||
742 | continue; | |||
743 | ||||
744 | if (!S.inTemplateInstantiation()) { | |||
745 | if (TypeQuals & Qual.first) | |||
746 | S.Diag(Qual.second, DiagID) | |||
747 | << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar | |||
748 | << FixItHint::CreateRemoval(Qual.second); | |||
749 | } | |||
750 | ||||
751 | TypeQuals &= ~Qual.first; | |||
752 | } | |||
753 | } | |||
754 | ||||
755 | /// Return true if this is omitted block return type. Also check type | |||
756 | /// attributes and type qualifiers when returning true. | |||
757 | static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, | |||
758 | QualType Result) { | |||
759 | if (!isOmittedBlockReturnType(declarator)) | |||
760 | return false; | |||
761 | ||||
762 | // Warn if we see type attributes for omitted return type on a block literal. | |||
763 | AttributeList *&attrs = | |||
764 | declarator.getMutableDeclSpec().getAttributes().getListRef(); | |||
765 | AttributeList *prev = nullptr; | |||
766 | for (AttributeList *cur = attrs; cur; cur = cur->getNext()) { | |||
767 | AttributeList &attr = *cur; | |||
768 | // Skip attributes that were marked to be invalid or non-type | |||
769 | // attributes. | |||
770 | if (attr.isInvalid() || !attr.isTypeAttr()) { | |||
771 | prev = cur; | |||
772 | continue; | |||
773 | } | |||
774 | S.Diag(attr.getLoc(), | |||
775 | diag::warn_block_literal_attributes_on_omitted_return_type) | |||
776 | << attr.getName(); | |||
777 | // Remove cur from the list. | |||
778 | if (prev) { | |||
779 | prev->setNext(cur->getNext()); | |||
780 | prev = cur; | |||
781 | } else { | |||
782 | attrs = cur->getNext(); | |||
783 | } | |||
784 | } | |||
785 | ||||
786 | // Warn if we see type qualifiers for omitted return type on a block literal. | |||
787 | const DeclSpec &DS = declarator.getDeclSpec(); | |||
788 | unsigned TypeQuals = DS.getTypeQualifiers(); | |||
789 | diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, | |||
790 | diag::warn_block_literal_qualifiers_on_omitted_return_type); | |||
791 | declarator.getMutableDeclSpec().ClearTypeQualifiers(); | |||
792 | ||||
793 | return true; | |||
794 | } | |||
795 | ||||
796 | /// Apply Objective-C type arguments to the given type. | |||
797 | static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, | |||
798 | ArrayRef<TypeSourceInfo *> typeArgs, | |||
799 | SourceRange typeArgsRange, | |||
800 | bool failOnError = false) { | |||
801 | // We can only apply type arguments to an Objective-C class type. | |||
802 | const auto *objcObjectType = type->getAs<ObjCObjectType>(); | |||
803 | if (!objcObjectType || !objcObjectType->getInterface()) { | |||
804 | S.Diag(loc, diag::err_objc_type_args_non_class) | |||
805 | << type | |||
806 | << typeArgsRange; | |||
807 | ||||
808 | if (failOnError) | |||
809 | return QualType(); | |||
810 | return type; | |||
811 | } | |||
812 | ||||
813 | // The class type must be parameterized. | |||
814 | ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); | |||
815 | ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); | |||
816 | if (!typeParams) { | |||
817 | S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) | |||
818 | << objcClass->getDeclName() | |||
819 | << FixItHint::CreateRemoval(typeArgsRange); | |||
820 | ||||
821 | if (failOnError) | |||
822 | return QualType(); | |||
823 | ||||
824 | return type; | |||
825 | } | |||
826 | ||||
827 | // The type must not already be specialized. | |||
828 | if (objcObjectType->isSpecialized()) { | |||
829 | S.Diag(loc, diag::err_objc_type_args_specialized_class) | |||
830 | << type | |||
831 | << FixItHint::CreateRemoval(typeArgsRange); | |||
832 | ||||
833 | if (failOnError) | |||
834 | return QualType(); | |||
835 | ||||
836 | return type; | |||
837 | } | |||
838 | ||||
839 | // Check the type arguments. | |||
840 | SmallVector<QualType, 4> finalTypeArgs; | |||
841 | unsigned numTypeParams = typeParams->size(); | |||
842 | bool anyPackExpansions = false; | |||
843 | for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { | |||
844 | TypeSourceInfo *typeArgInfo = typeArgs[i]; | |||
845 | QualType typeArg = typeArgInfo->getType(); | |||
846 | ||||
847 | // Type arguments cannot have explicit qualifiers or nullability. | |||
848 | // We ignore indirect sources of these, e.g. behind typedefs or | |||
849 | // template arguments. | |||
850 | if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { | |||
851 | bool diagnosed = false; | |||
852 | SourceRange rangeToRemove; | |||
853 | if (auto attr = qual.getAs<AttributedTypeLoc>()) { | |||
854 | rangeToRemove = attr.getLocalSourceRange(); | |||
855 | if (attr.getTypePtr()->getImmediateNullability()) { | |||
856 | typeArg = attr.getTypePtr()->getModifiedType(); | |||
857 | S.Diag(attr.getLocStart(), | |||
858 | diag::err_objc_type_arg_explicit_nullability) | |||
859 | << typeArg << FixItHint::CreateRemoval(rangeToRemove); | |||
860 | diagnosed = true; | |||
861 | } | |||
862 | } | |||
863 | ||||
864 | if (!diagnosed) { | |||
865 | S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified) | |||
866 | << typeArg << typeArg.getQualifiers().getAsString() | |||
867 | << FixItHint::CreateRemoval(rangeToRemove); | |||
868 | } | |||
869 | } | |||
870 | ||||
871 | // Remove qualifiers even if they're non-local. | |||
872 | typeArg = typeArg.getUnqualifiedType(); | |||
873 | ||||
874 | finalTypeArgs.push_back(typeArg); | |||
875 | ||||
876 | if (typeArg->getAs<PackExpansionType>()) | |||
877 | anyPackExpansions = true; | |||
878 | ||||
879 | // Find the corresponding type parameter, if there is one. | |||
880 | ObjCTypeParamDecl *typeParam = nullptr; | |||
881 | if (!anyPackExpansions) { | |||
882 | if (i < numTypeParams) { | |||
883 | typeParam = typeParams->begin()[i]; | |||
884 | } else { | |||
885 | // Too many arguments. | |||
886 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | |||
887 | << false | |||
888 | << objcClass->getDeclName() | |||
889 | << (unsigned)typeArgs.size() | |||
890 | << numTypeParams; | |||
891 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | |||
892 | << objcClass; | |||
893 | ||||
894 | if (failOnError) | |||
895 | return QualType(); | |||
896 | ||||
897 | return type; | |||
898 | } | |||
899 | } | |||
900 | ||||
901 | // Objective-C object pointer types must be substitutable for the bounds. | |||
902 | if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { | |||
903 | // If we don't have a type parameter to match against, assume | |||
904 | // everything is fine. There was a prior pack expansion that | |||
905 | // means we won't be able to match anything. | |||
906 | if (!typeParam) { | |||
907 | assert(anyPackExpansions && "Too many arguments?")(static_cast <bool> (anyPackExpansions && "Too many arguments?" ) ? void (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 907, __extension__ __PRETTY_FUNCTION__)); | |||
908 | continue; | |||
909 | } | |||
910 | ||||
911 | // Retrieve the bound. | |||
912 | QualType bound = typeParam->getUnderlyingType(); | |||
913 | const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); | |||
914 | ||||
915 | // Determine whether the type argument is substitutable for the bound. | |||
916 | if (typeArgObjC->isObjCIdType()) { | |||
917 | // When the type argument is 'id', the only acceptable type | |||
918 | // parameter bound is 'id'. | |||
919 | if (boundObjC->isObjCIdType()) | |||
920 | continue; | |||
921 | } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { | |||
922 | // Otherwise, we follow the assignability rules. | |||
923 | continue; | |||
924 | } | |||
925 | ||||
926 | // Diagnose the mismatch. | |||
927 | S.Diag(typeArgInfo->getTypeLoc().getLocStart(), | |||
928 | diag::err_objc_type_arg_does_not_match_bound) | |||
929 | << typeArg << bound << typeParam->getDeclName(); | |||
930 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | |||
931 | << typeParam->getDeclName(); | |||
932 | ||||
933 | if (failOnError) | |||
934 | return QualType(); | |||
935 | ||||
936 | return type; | |||
937 | } | |||
938 | ||||
939 | // Block pointer types are permitted for unqualified 'id' bounds. | |||
940 | if (typeArg->isBlockPointerType()) { | |||
941 | // If we don't have a type parameter to match against, assume | |||
942 | // everything is fine. There was a prior pack expansion that | |||
943 | // means we won't be able to match anything. | |||
944 | if (!typeParam) { | |||
945 | assert(anyPackExpansions && "Too many arguments?")(static_cast <bool> (anyPackExpansions && "Too many arguments?" ) ? void (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 945, __extension__ __PRETTY_FUNCTION__)); | |||
946 | continue; | |||
947 | } | |||
948 | ||||
949 | // Retrieve the bound. | |||
950 | QualType bound = typeParam->getUnderlyingType(); | |||
951 | if (bound->isBlockCompatibleObjCPointerType(S.Context)) | |||
952 | continue; | |||
953 | ||||
954 | // Diagnose the mismatch. | |||
955 | S.Diag(typeArgInfo->getTypeLoc().getLocStart(), | |||
956 | diag::err_objc_type_arg_does_not_match_bound) | |||
957 | << typeArg << bound << typeParam->getDeclName(); | |||
958 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | |||
959 | << typeParam->getDeclName(); | |||
960 | ||||
961 | if (failOnError) | |||
962 | return QualType(); | |||
963 | ||||
964 | return type; | |||
965 | } | |||
966 | ||||
967 | // Dependent types will be checked at instantiation time. | |||
968 | if (typeArg->isDependentType()) { | |||
969 | continue; | |||
970 | } | |||
971 | ||||
972 | // Diagnose non-id-compatible type arguments. | |||
973 | S.Diag(typeArgInfo->getTypeLoc().getLocStart(), | |||
974 | diag::err_objc_type_arg_not_id_compatible) | |||
975 | << typeArg | |||
976 | << typeArgInfo->getTypeLoc().getSourceRange(); | |||
977 | ||||
978 | if (failOnError) | |||
979 | return QualType(); | |||
980 | ||||
981 | return type; | |||
982 | } | |||
983 | ||||
984 | // Make sure we didn't have the wrong number of arguments. | |||
985 | if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { | |||
986 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | |||
987 | << (typeArgs.size() < typeParams->size()) | |||
988 | << objcClass->getDeclName() | |||
989 | << (unsigned)finalTypeArgs.size() | |||
990 | << (unsigned)numTypeParams; | |||
991 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | |||
992 | << objcClass; | |||
993 | ||||
994 | if (failOnError) | |||
995 | return QualType(); | |||
996 | ||||
997 | return type; | |||
998 | } | |||
999 | ||||
1000 | // Success. Form the specialized type. | |||
1001 | return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); | |||
1002 | } | |||
1003 | ||||
1004 | QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, | |||
1005 | SourceLocation ProtocolLAngleLoc, | |||
1006 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
1007 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1008 | SourceLocation ProtocolRAngleLoc, | |||
1009 | bool FailOnError) { | |||
1010 | QualType Result = QualType(Decl->getTypeForDecl(), 0); | |||
1011 | if (!Protocols.empty()) { | |||
1012 | bool HasError; | |||
1013 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | |||
1014 | HasError); | |||
1015 | if (HasError) { | |||
1016 | Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) | |||
1017 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | |||
1018 | if (FailOnError) Result = QualType(); | |||
1019 | } | |||
1020 | if (FailOnError && Result.isNull()) | |||
1021 | return QualType(); | |||
1022 | } | |||
1023 | ||||
1024 | return Result; | |||
1025 | } | |||
1026 | ||||
1027 | QualType Sema::BuildObjCObjectType(QualType BaseType, | |||
1028 | SourceLocation Loc, | |||
1029 | SourceLocation TypeArgsLAngleLoc, | |||
1030 | ArrayRef<TypeSourceInfo *> TypeArgs, | |||
1031 | SourceLocation TypeArgsRAngleLoc, | |||
1032 | SourceLocation ProtocolLAngleLoc, | |||
1033 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
1034 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1035 | SourceLocation ProtocolRAngleLoc, | |||
1036 | bool FailOnError) { | |||
1037 | QualType Result = BaseType; | |||
1038 | if (!TypeArgs.empty()) { | |||
1039 | Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, | |||
1040 | SourceRange(TypeArgsLAngleLoc, | |||
1041 | TypeArgsRAngleLoc), | |||
1042 | FailOnError); | |||
1043 | if (FailOnError && Result.isNull()) | |||
1044 | return QualType(); | |||
1045 | } | |||
1046 | ||||
1047 | if (!Protocols.empty()) { | |||
1048 | bool HasError; | |||
1049 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | |||
1050 | HasError); | |||
1051 | if (HasError) { | |||
1052 | Diag(Loc, diag::err_invalid_protocol_qualifiers) | |||
1053 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | |||
1054 | if (FailOnError) Result = QualType(); | |||
1055 | } | |||
1056 | if (FailOnError && Result.isNull()) | |||
1057 | return QualType(); | |||
1058 | } | |||
1059 | ||||
1060 | return Result; | |||
1061 | } | |||
1062 | ||||
1063 | TypeResult Sema::actOnObjCProtocolQualifierType( | |||
1064 | SourceLocation lAngleLoc, | |||
1065 | ArrayRef<Decl *> protocols, | |||
1066 | ArrayRef<SourceLocation> protocolLocs, | |||
1067 | SourceLocation rAngleLoc) { | |||
1068 | // Form id<protocol-list>. | |||
1069 | QualType Result = Context.getObjCObjectType( | |||
1070 | Context.ObjCBuiltinIdTy, { }, | |||
1071 | llvm::makeArrayRef( | |||
1072 | (ObjCProtocolDecl * const *)protocols.data(), | |||
1073 | protocols.size()), | |||
1074 | false); | |||
1075 | Result = Context.getObjCObjectPointerType(Result); | |||
1076 | ||||
1077 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | |||
1078 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | |||
1079 | ||||
1080 | auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); | |||
1081 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit | |||
1082 | ||||
1083 | auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() | |||
1084 | .castAs<ObjCObjectTypeLoc>(); | |||
1085 | ObjCObjectTL.setHasBaseTypeAsWritten(false); | |||
1086 | ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); | |||
1087 | ||||
1088 | // No type arguments. | |||
1089 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | |||
1090 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | |||
1091 | ||||
1092 | // Fill in protocol qualifiers. | |||
1093 | ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); | |||
1094 | ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); | |||
1095 | for (unsigned i = 0, n = protocols.size(); i != n; ++i) | |||
1096 | ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); | |||
1097 | ||||
1098 | // We're done. Return the completed type to the parser. | |||
1099 | return CreateParsedType(Result, ResultTInfo); | |||
1100 | } | |||
1101 | ||||
1102 | TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( | |||
1103 | Scope *S, | |||
1104 | SourceLocation Loc, | |||
1105 | ParsedType BaseType, | |||
1106 | SourceLocation TypeArgsLAngleLoc, | |||
1107 | ArrayRef<ParsedType> TypeArgs, | |||
1108 | SourceLocation TypeArgsRAngleLoc, | |||
1109 | SourceLocation ProtocolLAngleLoc, | |||
1110 | ArrayRef<Decl *> Protocols, | |||
1111 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1112 | SourceLocation ProtocolRAngleLoc) { | |||
1113 | TypeSourceInfo *BaseTypeInfo = nullptr; | |||
1114 | QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); | |||
1115 | if (T.isNull()) | |||
1116 | return true; | |||
1117 | ||||
1118 | // Handle missing type-source info. | |||
1119 | if (!BaseTypeInfo) | |||
1120 | BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
1121 | ||||
1122 | // Extract type arguments. | |||
1123 | SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; | |||
1124 | for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { | |||
1125 | TypeSourceInfo *TypeArgInfo = nullptr; | |||
1126 | QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); | |||
1127 | if (TypeArg.isNull()) { | |||
1128 | ActualTypeArgInfos.clear(); | |||
1129 | break; | |||
1130 | } | |||
1131 | ||||
1132 | assert(TypeArgInfo && "No type source info?")(static_cast <bool> (TypeArgInfo && "No type source info?" ) ? void (0) : __assert_fail ("TypeArgInfo && \"No type source info?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1132, __extension__ __PRETTY_FUNCTION__)); | |||
1133 | ActualTypeArgInfos.push_back(TypeArgInfo); | |||
1134 | } | |||
1135 | ||||
1136 | // Build the object type. | |||
1137 | QualType Result = BuildObjCObjectType( | |||
1138 | T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), | |||
1139 | TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, | |||
1140 | ProtocolLAngleLoc, | |||
1141 | llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), | |||
1142 | Protocols.size()), | |||
1143 | ProtocolLocs, ProtocolRAngleLoc, | |||
1144 | /*FailOnError=*/false); | |||
1145 | ||||
1146 | if (Result == T) | |||
1147 | return BaseType; | |||
1148 | ||||
1149 | // Create source information for this type. | |||
1150 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | |||
1151 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | |||
1152 | ||||
1153 | // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an | |||
1154 | // object pointer type. Fill in source information for it. | |||
1155 | if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { | |||
1156 | // The '*' is implicit. | |||
1157 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); | |||
1158 | ResultTL = ObjCObjectPointerTL.getPointeeLoc(); | |||
1159 | } | |||
1160 | ||||
1161 | if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) { | |||
1162 | // Protocol qualifier information. | |||
1163 | if (OTPTL.getNumProtocols() > 0) { | |||
1164 | assert(OTPTL.getNumProtocols() == Protocols.size())(static_cast <bool> (OTPTL.getNumProtocols() == Protocols .size()) ? void (0) : __assert_fail ("OTPTL.getNumProtocols() == Protocols.size()" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1164, __extension__ __PRETTY_FUNCTION__)); | |||
1165 | OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | |||
1166 | OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | |||
1167 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | |||
1168 | OTPTL.setProtocolLoc(i, ProtocolLocs[i]); | |||
1169 | } | |||
1170 | ||||
1171 | // We're done. Return the completed type to the parser. | |||
1172 | return CreateParsedType(Result, ResultTInfo); | |||
1173 | } | |||
1174 | ||||
1175 | auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); | |||
1176 | ||||
1177 | // Type argument information. | |||
1178 | if (ObjCObjectTL.getNumTypeArgs() > 0) { | |||
1179 | assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size())(static_cast <bool> (ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos .size()) ? void (0) : __assert_fail ("ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1179, __extension__ __PRETTY_FUNCTION__)); | |||
1180 | ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); | |||
1181 | ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); | |||
1182 | for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) | |||
1183 | ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); | |||
1184 | } else { | |||
1185 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | |||
1186 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | |||
1187 | } | |||
1188 | ||||
1189 | // Protocol qualifier information. | |||
1190 | if (ObjCObjectTL.getNumProtocols() > 0) { | |||
1191 | assert(ObjCObjectTL.getNumProtocols() == Protocols.size())(static_cast <bool> (ObjCObjectTL.getNumProtocols() == Protocols .size()) ? void (0) : __assert_fail ("ObjCObjectTL.getNumProtocols() == Protocols.size()" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1191, __extension__ __PRETTY_FUNCTION__)); | |||
1192 | ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | |||
1193 | ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | |||
1194 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | |||
1195 | ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); | |||
1196 | } else { | |||
1197 | ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); | |||
1198 | ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); | |||
1199 | } | |||
1200 | ||||
1201 | // Base type. | |||
1202 | ObjCObjectTL.setHasBaseTypeAsWritten(true); | |||
1203 | if (ObjCObjectTL.getType() == T) | |||
1204 | ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); | |||
1205 | else | |||
1206 | ObjCObjectTL.getBaseLoc().initialize(Context, Loc); | |||
1207 | ||||
1208 | // We're done. Return the completed type to the parser. | |||
1209 | return CreateParsedType(Result, ResultTInfo); | |||
1210 | } | |||
1211 | ||||
1212 | static OpenCLAccessAttr::Spelling getImageAccess(const AttributeList *Attrs) { | |||
1213 | if (Attrs) { | |||
1214 | const AttributeList *Next = Attrs; | |||
1215 | do { | |||
1216 | const AttributeList &Attr = *Next; | |||
1217 | Next = Attr.getNext(); | |||
1218 | if (Attr.getKind() == AttributeList::AT_OpenCLAccess) { | |||
1219 | return static_cast<OpenCLAccessAttr::Spelling>( | |||
1220 | Attr.getSemanticSpelling()); | |||
1221 | } | |||
1222 | } while (Next); | |||
1223 | } | |||
1224 | return OpenCLAccessAttr::Keyword_read_only; | |||
1225 | } | |||
1226 | ||||
1227 | /// \brief Convert the specified declspec to the appropriate type | |||
1228 | /// object. | |||
1229 | /// \param state Specifies the declarator containing the declaration specifier | |||
1230 | /// to be converted, along with other associated processing state. | |||
1231 | /// \returns The type described by the declaration specifiers. This function | |||
1232 | /// never returns null. | |||
1233 | static QualType ConvertDeclSpecToType(TypeProcessingState &state) { | |||
1234 | // FIXME: Should move the logic from DeclSpec::Finish to here for validity | |||
1235 | // checking. | |||
1236 | ||||
1237 | Sema &S = state.getSema(); | |||
1238 | Declarator &declarator = state.getDeclarator(); | |||
1239 | const DeclSpec &DS = declarator.getDeclSpec(); | |||
1240 | SourceLocation DeclLoc = declarator.getIdentifierLoc(); | |||
1241 | if (DeclLoc.isInvalid()) | |||
1242 | DeclLoc = DS.getLocStart(); | |||
1243 | ||||
1244 | ASTContext &Context = S.Context; | |||
1245 | ||||
1246 | QualType Result; | |||
1247 | switch (DS.getTypeSpecType()) { | |||
1248 | case DeclSpec::TST_void: | |||
1249 | Result = Context.VoidTy; | |||
1250 | break; | |||
1251 | case DeclSpec::TST_char: | |||
1252 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) | |||
1253 | Result = Context.CharTy; | |||
1254 | else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) | |||
1255 | Result = Context.SignedCharTy; | |||
1256 | else { | |||
1257 | assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec:: TSS_unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1258, __extension__ __PRETTY_FUNCTION__)) | |||
1258 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec:: TSS_unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1258, __extension__ __PRETTY_FUNCTION__)); | |||
1259 | Result = Context.UnsignedCharTy; | |||
1260 | } | |||
1261 | break; | |||
1262 | case DeclSpec::TST_wchar: | |||
1263 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) | |||
1264 | Result = Context.WCharTy; | |||
1265 | else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { | |||
1266 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) | |||
1267 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1268 | Context.getPrintingPolicy()); | |||
1269 | Result = Context.getSignedWCharType(); | |||
1270 | } else { | |||
1271 | assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec:: TSS_unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1272, __extension__ __PRETTY_FUNCTION__)) | |||
1272 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec:: TSS_unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1272, __extension__ __PRETTY_FUNCTION__)); | |||
1273 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) | |||
1274 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1275 | Context.getPrintingPolicy()); | |||
1276 | Result = Context.getUnsignedWCharType(); | |||
1277 | } | |||
1278 | break; | |||
1279 | case DeclSpec::TST_char16: | |||
1280 | assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec:: TSS_unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1281, __extension__ __PRETTY_FUNCTION__)) | |||
1281 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec:: TSS_unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1281, __extension__ __PRETTY_FUNCTION__)); | |||
1282 | Result = Context.Char16Ty; | |||
1283 | break; | |||
1284 | case DeclSpec::TST_char32: | |||
1285 | assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec:: TSS_unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1286, __extension__ __PRETTY_FUNCTION__)) | |||
1286 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec:: TSS_unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1286, __extension__ __PRETTY_FUNCTION__)); | |||
1287 | Result = Context.Char32Ty; | |||
1288 | break; | |||
1289 | case DeclSpec::TST_unspecified: | |||
1290 | // If this is a missing declspec in a block literal return context, then it | |||
1291 | // is inferred from the return statements inside the block. | |||
1292 | // The declspec is always missing in a lambda expr context; it is either | |||
1293 | // specified with a trailing return type or inferred. | |||
1294 | if (S.getLangOpts().CPlusPlus14 && | |||
1295 | declarator.getContext() == DeclaratorContext::LambdaExprContext) { | |||
1296 | // In C++1y, a lambda's implicit return type is 'auto'. | |||
1297 | Result = Context.getAutoDeductType(); | |||
1298 | break; | |||
1299 | } else if (declarator.getContext() == | |||
1300 | DeclaratorContext::LambdaExprContext || | |||
1301 | checkOmittedBlockReturnType(S, declarator, | |||
1302 | Context.DependentTy)) { | |||
1303 | Result = Context.DependentTy; | |||
1304 | break; | |||
1305 | } | |||
1306 | ||||
1307 | // Unspecified typespec defaults to int in C90. However, the C90 grammar | |||
1308 | // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, | |||
1309 | // type-qualifier, or storage-class-specifier. If not, emit an extwarn. | |||
1310 | // Note that the one exception to this is function definitions, which are | |||
1311 | // allowed to be completely missing a declspec. This is handled in the | |||
1312 | // parser already though by it pretending to have seen an 'int' in this | |||
1313 | // case. | |||
1314 | if (S.getLangOpts().ImplicitInt) { | |||
1315 | // In C89 mode, we only warn if there is a completely missing declspec | |||
1316 | // when one is not allowed. | |||
1317 | if (DS.isEmpty()) { | |||
1318 | S.Diag(DeclLoc, diag::ext_missing_declspec) | |||
1319 | << DS.getSourceRange() | |||
1320 | << FixItHint::CreateInsertion(DS.getLocStart(), "int"); | |||
1321 | } | |||
1322 | } else if (!DS.hasTypeSpecifier()) { | |||
1323 | // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: | |||
1324 | // "At least one type specifier shall be given in the declaration | |||
1325 | // specifiers in each declaration, and in the specifier-qualifier list in | |||
1326 | // each struct declaration and type name." | |||
1327 | if (S.getLangOpts().CPlusPlus) { | |||
1328 | S.Diag(DeclLoc, diag::err_missing_type_specifier) | |||
1329 | << DS.getSourceRange(); | |||
1330 | ||||
1331 | // When this occurs in C++ code, often something is very broken with the | |||
1332 | // value being declared, poison it as invalid so we don't get chains of | |||
1333 | // errors. | |||
1334 | declarator.setInvalidType(true); | |||
1335 | } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){ | |||
1336 | S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) | |||
1337 | << DS.getSourceRange(); | |||
1338 | declarator.setInvalidType(true); | |||
1339 | } else { | |||
1340 | S.Diag(DeclLoc, diag::ext_missing_type_specifier) | |||
1341 | << DS.getSourceRange(); | |||
1342 | } | |||
1343 | } | |||
1344 | ||||
1345 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
1346 | case DeclSpec::TST_int: { | |||
1347 | if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { | |||
1348 | switch (DS.getTypeSpecWidth()) { | |||
1349 | case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; | |||
1350 | case DeclSpec::TSW_short: Result = Context.ShortTy; break; | |||
1351 | case DeclSpec::TSW_long: Result = Context.LongTy; break; | |||
1352 | case DeclSpec::TSW_longlong: | |||
1353 | Result = Context.LongLongTy; | |||
1354 | ||||
1355 | // 'long long' is a C99 or C++11 feature. | |||
1356 | if (!S.getLangOpts().C99) { | |||
1357 | if (S.getLangOpts().CPlusPlus) | |||
1358 | S.Diag(DS.getTypeSpecWidthLoc(), | |||
1359 | S.getLangOpts().CPlusPlus11 ? | |||
1360 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
1361 | else | |||
1362 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | |||
1363 | } | |||
1364 | break; | |||
1365 | } | |||
1366 | } else { | |||
1367 | switch (DS.getTypeSpecWidth()) { | |||
1368 | case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; | |||
1369 | case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; | |||
1370 | case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; | |||
1371 | case DeclSpec::TSW_longlong: | |||
1372 | Result = Context.UnsignedLongLongTy; | |||
1373 | ||||
1374 | // 'long long' is a C99 or C++11 feature. | |||
1375 | if (!S.getLangOpts().C99) { | |||
1376 | if (S.getLangOpts().CPlusPlus) | |||
1377 | S.Diag(DS.getTypeSpecWidthLoc(), | |||
1378 | S.getLangOpts().CPlusPlus11 ? | |||
1379 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
1380 | else | |||
1381 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | |||
1382 | } | |||
1383 | break; | |||
1384 | } | |||
1385 | } | |||
1386 | break; | |||
1387 | } | |||
1388 | case DeclSpec::TST_int128: | |||
1389 | if (!S.Context.getTargetInfo().hasInt128Type()) | |||
1390 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1391 | << "__int128"; | |||
1392 | if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) | |||
1393 | Result = Context.UnsignedInt128Ty; | |||
1394 | else | |||
1395 | Result = Context.Int128Ty; | |||
1396 | break; | |||
1397 | case DeclSpec::TST_float16: Result = Context.Float16Ty; break; | |||
1398 | case DeclSpec::TST_half: Result = Context.HalfTy; break; | |||
1399 | case DeclSpec::TST_float: Result = Context.FloatTy; break; | |||
1400 | case DeclSpec::TST_double: | |||
1401 | if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) | |||
1402 | Result = Context.LongDoubleTy; | |||
1403 | else | |||
1404 | Result = Context.DoubleTy; | |||
1405 | break; | |||
1406 | case DeclSpec::TST_float128: | |||
1407 | if (!S.Context.getTargetInfo().hasFloat128Type()) | |||
1408 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1409 | << "__float128"; | |||
1410 | Result = Context.Float128Ty; | |||
1411 | break; | |||
1412 | case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool | |||
1413 | break; | |||
1414 | case DeclSpec::TST_decimal32: // _Decimal32 | |||
1415 | case DeclSpec::TST_decimal64: // _Decimal64 | |||
1416 | case DeclSpec::TST_decimal128: // _Decimal128 | |||
1417 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); | |||
1418 | Result = Context.IntTy; | |||
1419 | declarator.setInvalidType(true); | |||
1420 | break; | |||
1421 | case DeclSpec::TST_class: | |||
1422 | case DeclSpec::TST_enum: | |||
1423 | case DeclSpec::TST_union: | |||
1424 | case DeclSpec::TST_struct: | |||
1425 | case DeclSpec::TST_interface: { | |||
1426 | TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); | |||
1427 | if (!D) { | |||
1428 | // This can happen in C++ with ambiguous lookups. | |||
1429 | Result = Context.IntTy; | |||
1430 | declarator.setInvalidType(true); | |||
1431 | break; | |||
1432 | } | |||
1433 | ||||
1434 | // If the type is deprecated or unavailable, diagnose it. | |||
1435 | S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); | |||
1436 | ||||
1437 | assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"No qualifiers on tag names!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1438, __extension__ __PRETTY_FUNCTION__)) | |||
1438 | DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!")(static_cast <bool> (DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"No qualifiers on tag names!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1438, __extension__ __PRETTY_FUNCTION__)); | |||
1439 | ||||
1440 | // TypeQuals handled by caller. | |||
1441 | Result = Context.getTypeDeclType(D); | |||
1442 | ||||
1443 | // In both C and C++, make an ElaboratedType. | |||
1444 | ElaboratedTypeKeyword Keyword | |||
1445 | = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); | |||
1446 | Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); | |||
1447 | break; | |||
1448 | } | |||
1449 | case DeclSpec::TST_typename: { | |||
1450 | assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && "Can't handle qualifiers on typedef names yet!" ) ? 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-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1452, __extension__ __PRETTY_FUNCTION__)) | |||
1451 | DS.getTypeSpecSign() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && "Can't handle qualifiers on typedef names yet!" ) ? 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-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1452, __extension__ __PRETTY_FUNCTION__)) | |||
1452 | "Can't handle qualifiers on typedef names yet!")(static_cast <bool> (DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && "Can't handle qualifiers on typedef names yet!" ) ? 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-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1452, __extension__ __PRETTY_FUNCTION__)); | |||
1453 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1454 | if (Result.isNull()) { | |||
1455 | declarator.setInvalidType(true); | |||
1456 | } | |||
1457 | ||||
1458 | // TypeQuals handled by caller. | |||
1459 | break; | |||
1460 | } | |||
1461 | case DeclSpec::TST_typeofType: | |||
1462 | // FIXME: Preserve type source info. | |||
1463 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1464 | assert(!Result.isNull() && "Didn't get a type for typeof?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for typeof?" ) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for typeof?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1464, __extension__ __PRETTY_FUNCTION__)); | |||
1465 | if (!Result->isDependentType()) | |||
1466 | if (const TagType *TT = Result->getAs<TagType>()) | |||
1467 | S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); | |||
1468 | // TypeQuals handled by caller. | |||
1469 | Result = Context.getTypeOfType(Result); | |||
1470 | break; | |||
1471 | case DeclSpec::TST_typeofExpr: { | |||
1472 | Expr *E = DS.getRepAsExpr(); | |||
1473 | assert(E && "Didn't get an expression for typeof?")(static_cast <bool> (E && "Didn't get an expression for typeof?" ) ? void (0) : __assert_fail ("E && \"Didn't get an expression for typeof?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1473, __extension__ __PRETTY_FUNCTION__)); | |||
1474 | // TypeQuals handled by caller. | |||
1475 | Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); | |||
1476 | if (Result.isNull()) { | |||
1477 | Result = Context.IntTy; | |||
1478 | declarator.setInvalidType(true); | |||
1479 | } | |||
1480 | break; | |||
1481 | } | |||
1482 | case DeclSpec::TST_decltype: { | |||
1483 | Expr *E = DS.getRepAsExpr(); | |||
1484 | assert(E && "Didn't get an expression for decltype?")(static_cast <bool> (E && "Didn't get an expression for decltype?" ) ? void (0) : __assert_fail ("E && \"Didn't get an expression for decltype?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1484, __extension__ __PRETTY_FUNCTION__)); | |||
1485 | // TypeQuals handled by caller. | |||
1486 | Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); | |||
1487 | if (Result.isNull()) { | |||
1488 | Result = Context.IntTy; | |||
1489 | declarator.setInvalidType(true); | |||
1490 | } | |||
1491 | break; | |||
1492 | } | |||
1493 | case DeclSpec::TST_underlyingType: | |||
1494 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1495 | assert(!Result.isNull() && "Didn't get a type for __underlying_type?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for __underlying_type?" ) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for __underlying_type?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1495, __extension__ __PRETTY_FUNCTION__)); | |||
1496 | Result = S.BuildUnaryTransformType(Result, | |||
1497 | UnaryTransformType::EnumUnderlyingType, | |||
1498 | DS.getTypeSpecTypeLoc()); | |||
1499 | if (Result.isNull()) { | |||
1500 | Result = Context.IntTy; | |||
1501 | declarator.setInvalidType(true); | |||
1502 | } | |||
1503 | break; | |||
1504 | ||||
1505 | case DeclSpec::TST_auto: | |||
1506 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false); | |||
1507 | break; | |||
1508 | ||||
1509 | case DeclSpec::TST_auto_type: | |||
1510 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); | |||
1511 | break; | |||
1512 | ||||
1513 | case DeclSpec::TST_decltype_auto: | |||
1514 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto, | |||
1515 | /*IsDependent*/ false); | |||
1516 | break; | |||
1517 | ||||
1518 | case DeclSpec::TST_unknown_anytype: | |||
1519 | Result = Context.UnknownAnyTy; | |||
1520 | break; | |||
1521 | ||||
1522 | case DeclSpec::TST_atomic: | |||
1523 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1524 | assert(!Result.isNull() && "Didn't get a type for _Atomic?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for _Atomic?" ) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for _Atomic?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1524, __extension__ __PRETTY_FUNCTION__)); | |||
1525 | Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); | |||
1526 | if (Result.isNull()) { | |||
1527 | Result = Context.IntTy; | |||
1528 | declarator.setInvalidType(true); | |||
1529 | } | |||
1530 | break; | |||
1531 | ||||
1532 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ | |||
1533 | case DeclSpec::TST_##ImgType##_t: \ | |||
1534 | switch (getImageAccess(DS.getAttributes().getList())) { \ | |||
1535 | case OpenCLAccessAttr::Keyword_write_only: \ | |||
1536 | Result = Context.Id##WOTy; break; \ | |||
1537 | case OpenCLAccessAttr::Keyword_read_write: \ | |||
1538 | Result = Context.Id##RWTy; break; \ | |||
1539 | case OpenCLAccessAttr::Keyword_read_only: \ | |||
1540 | Result = Context.Id##ROTy; break; \ | |||
1541 | } \ | |||
1542 | break; | |||
1543 | #include "clang/Basic/OpenCLImageTypes.def" | |||
1544 | ||||
1545 | case DeclSpec::TST_error: | |||
1546 | Result = Context.IntTy; | |||
1547 | declarator.setInvalidType(true); | |||
1548 | break; | |||
1549 | } | |||
1550 | ||||
1551 | if (S.getLangOpts().OpenCL && | |||
1552 | S.checkOpenCLDisabledTypeDeclSpec(DS, Result)) | |||
1553 | declarator.setInvalidType(true); | |||
1554 | ||||
1555 | // Handle complex types. | |||
1556 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { | |||
1557 | if (S.getLangOpts().Freestanding) | |||
1558 | S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); | |||
1559 | Result = Context.getComplexType(Result); | |||
1560 | } else if (DS.isTypeAltiVecVector()) { | |||
1561 | unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); | |||
1562 | assert(typeSize > 0 && "type size for vector must be greater than 0 bits")(static_cast <bool> (typeSize > 0 && "type size for vector must be greater than 0 bits" ) ? void (0) : __assert_fail ("typeSize > 0 && \"type size for vector must be greater than 0 bits\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1562, __extension__ __PRETTY_FUNCTION__)); | |||
1563 | VectorType::VectorKind VecKind = VectorType::AltiVecVector; | |||
1564 | if (DS.isTypeAltiVecPixel()) | |||
1565 | VecKind = VectorType::AltiVecPixel; | |||
1566 | else if (DS.isTypeAltiVecBool()) | |||
1567 | VecKind = VectorType::AltiVecBool; | |||
1568 | Result = Context.getVectorType(Result, 128/typeSize, VecKind); | |||
1569 | } | |||
1570 | ||||
1571 | // FIXME: Imaginary. | |||
1572 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) | |||
1573 | S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); | |||
1574 | ||||
1575 | // Before we process any type attributes, synthesize a block literal | |||
1576 | // function declarator if necessary. | |||
1577 | if (declarator.getContext() == DeclaratorContext::BlockLiteralContext) | |||
1578 | maybeSynthesizeBlockSignature(state, Result); | |||
1579 | ||||
1580 | // Apply any type attributes from the decl spec. This may cause the | |||
1581 | // list of type attributes to be temporarily saved while the type | |||
1582 | // attributes are pushed around. | |||
1583 | // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) | |||
1584 | if (!DS.isTypeSpecPipe()) | |||
1585 | processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList()); | |||
1586 | ||||
1587 | // Apply const/volatile/restrict qualifiers to T. | |||
1588 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | |||
1589 | // Warn about CV qualifiers on function types. | |||
1590 | // C99 6.7.3p8: | |||
1591 | // If the specification of a function type includes any type qualifiers, | |||
1592 | // the behavior is undefined. | |||
1593 | // C++11 [dcl.fct]p7: | |||
1594 | // The effect of a cv-qualifier-seq in a function declarator is not the | |||
1595 | // same as adding cv-qualification on top of the function type. In the | |||
1596 | // latter case, the cv-qualifiers are ignored. | |||
1597 | if (TypeQuals && Result->isFunctionType()) { | |||
1598 | diagnoseAndRemoveTypeQualifiers( | |||
1599 | S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, | |||
1600 | S.getLangOpts().CPlusPlus | |||
1601 | ? diag::warn_typecheck_function_qualifiers_ignored | |||
1602 | : diag::warn_typecheck_function_qualifiers_unspecified); | |||
1603 | // No diagnostic for 'restrict' or '_Atomic' applied to a | |||
1604 | // function type; we'll diagnose those later, in BuildQualifiedType. | |||
1605 | } | |||
1606 | ||||
1607 | // C++11 [dcl.ref]p1: | |||
1608 | // Cv-qualified references are ill-formed except when the | |||
1609 | // cv-qualifiers are introduced through the use of a typedef-name | |||
1610 | // or decltype-specifier, in which case the cv-qualifiers are ignored. | |||
1611 | // | |||
1612 | // There don't appear to be any other contexts in which a cv-qualified | |||
1613 | // reference type could be formed, so the 'ill-formed' clause here appears | |||
1614 | // to never happen. | |||
1615 | if (TypeQuals && Result->isReferenceType()) { | |||
1616 | diagnoseAndRemoveTypeQualifiers( | |||
1617 | S, DS, TypeQuals, Result, | |||
1618 | DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, | |||
1619 | diag::warn_typecheck_reference_qualifiers); | |||
1620 | } | |||
1621 | ||||
1622 | // C90 6.5.3 constraints: "The same type qualifier shall not appear more | |||
1623 | // than once in the same specifier-list or qualifier-list, either directly | |||
1624 | // or via one or more typedefs." | |||
1625 | if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus | |||
1626 | && TypeQuals & Result.getCVRQualifiers()) { | |||
1627 | if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { | |||
1628 | S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) | |||
1629 | << "const"; | |||
1630 | } | |||
1631 | ||||
1632 | if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { | |||
1633 | S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) | |||
1634 | << "volatile"; | |||
1635 | } | |||
1636 | ||||
1637 | // C90 doesn't have restrict nor _Atomic, so it doesn't force us to | |||
1638 | // produce a warning in this case. | |||
1639 | } | |||
1640 | ||||
1641 | QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); | |||
1642 | ||||
1643 | // If adding qualifiers fails, just use the unqualified type. | |||
1644 | if (Qualified.isNull()) | |||
1645 | declarator.setInvalidType(true); | |||
1646 | else | |||
1647 | Result = Qualified; | |||
1648 | } | |||
1649 | ||||
1650 | assert(!Result.isNull() && "This function should not return a null type")(static_cast <bool> (!Result.isNull() && "This function should not return a null type" ) ? void (0) : __assert_fail ("!Result.isNull() && \"This function should not return a null type\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1650, __extension__ __PRETTY_FUNCTION__)); | |||
1651 | return Result; | |||
1652 | } | |||
1653 | ||||
1654 | static std::string getPrintableNameForEntity(DeclarationName Entity) { | |||
1655 | if (Entity) | |||
1656 | return Entity.getAsString(); | |||
1657 | ||||
1658 | return "type name"; | |||
1659 | } | |||
1660 | ||||
1661 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | |||
1662 | Qualifiers Qs, const DeclSpec *DS) { | |||
1663 | if (T.isNull()) | |||
1664 | return QualType(); | |||
1665 | ||||
1666 | // Ignore any attempt to form a cv-qualified reference. | |||
1667 | if (T->isReferenceType()) { | |||
1668 | Qs.removeConst(); | |||
1669 | Qs.removeVolatile(); | |||
1670 | } | |||
1671 | ||||
1672 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from | |||
1673 | // object or incomplete types shall not be restrict-qualified." | |||
1674 | if (Qs.hasRestrict()) { | |||
1675 | unsigned DiagID = 0; | |||
1676 | QualType ProblemTy; | |||
1677 | ||||
1678 | if (T->isAnyPointerType() || T->isReferenceType() || | |||
1679 | T->isMemberPointerType()) { | |||
1680 | QualType EltTy; | |||
1681 | if (T->isObjCObjectPointerType()) | |||
1682 | EltTy = T; | |||
1683 | else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) | |||
1684 | EltTy = PTy->getPointeeType(); | |||
1685 | else | |||
1686 | EltTy = T->getPointeeType(); | |||
1687 | ||||
1688 | // If we have a pointer or reference, the pointee must have an object | |||
1689 | // incomplete type. | |||
1690 | if (!EltTy->isIncompleteOrObjectType()) { | |||
1691 | DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; | |||
1692 | ProblemTy = EltTy; | |||
1693 | } | |||
1694 | } else if (!T->isDependentType()) { | |||
1695 | DiagID = diag::err_typecheck_invalid_restrict_not_pointer; | |||
1696 | ProblemTy = T; | |||
1697 | } | |||
1698 | ||||
1699 | if (DiagID) { | |||
1700 | Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; | |||
1701 | Qs.removeRestrict(); | |||
1702 | } | |||
1703 | } | |||
1704 | ||||
1705 | return Context.getQualifiedType(T, Qs); | |||
1706 | } | |||
1707 | ||||
1708 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | |||
1709 | unsigned CVRAU, const DeclSpec *DS) { | |||
1710 | if (T.isNull()) | |||
1711 | return QualType(); | |||
1712 | ||||
1713 | // Ignore any attempt to form a cv-qualified reference. | |||
1714 | if (T->isReferenceType()) | |||
1715 | CVRAU &= | |||
1716 | ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); | |||
1717 | ||||
1718 | // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and | |||
1719 | // TQ_unaligned; | |||
1720 | unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); | |||
1721 | ||||
1722 | // C11 6.7.3/5: | |||
1723 | // If the same qualifier appears more than once in the same | |||
1724 | // specifier-qualifier-list, either directly or via one or more typedefs, | |||
1725 | // the behavior is the same as if it appeared only once. | |||
1726 | // | |||
1727 | // It's not specified what happens when the _Atomic qualifier is applied to | |||
1728 | // a type specified with the _Atomic specifier, but we assume that this | |||
1729 | // should be treated as if the _Atomic qualifier appeared multiple times. | |||
1730 | if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { | |||
1731 | // C11 6.7.3/5: | |||
1732 | // If other qualifiers appear along with the _Atomic qualifier in a | |||
1733 | // specifier-qualifier-list, the resulting type is the so-qualified | |||
1734 | // atomic type. | |||
1735 | // | |||
1736 | // Don't need to worry about array types here, since _Atomic can't be | |||
1737 | // applied to such types. | |||
1738 | SplitQualType Split = T.getSplitUnqualifiedType(); | |||
1739 | T = BuildAtomicType(QualType(Split.Ty, 0), | |||
1740 | DS ? DS->getAtomicSpecLoc() : Loc); | |||
1741 | if (T.isNull()) | |||
1742 | return T; | |||
1743 | Split.Quals.addCVRQualifiers(CVR); | |||
1744 | return BuildQualifiedType(T, Loc, Split.Quals); | |||
1745 | } | |||
1746 | ||||
1747 | Qualifiers Q = Qualifiers::fromCVRMask(CVR); | |||
1748 | Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); | |||
1749 | return BuildQualifiedType(T, Loc, Q, DS); | |||
1750 | } | |||
1751 | ||||
1752 | /// \brief Build a paren type including \p T. | |||
1753 | QualType Sema::BuildParenType(QualType T) { | |||
1754 | return Context.getParenType(T); | |||
1755 | } | |||
1756 | ||||
1757 | /// Given that we're building a pointer or reference to the given | |||
1758 | static QualType inferARCLifetimeForPointee(Sema &S, QualType type, | |||
1759 | SourceLocation loc, | |||
1760 | bool isReference) { | |||
1761 | // Bail out if retention is unrequired or already specified. | |||
1762 | if (!type->isObjCLifetimeType() || | |||
1763 | type.getObjCLifetime() != Qualifiers::OCL_None) | |||
1764 | return type; | |||
1765 | ||||
1766 | Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; | |||
1767 | ||||
1768 | // If the object type is const-qualified, we can safely use | |||
1769 | // __unsafe_unretained. This is safe (because there are no read | |||
1770 | // barriers), and it'll be safe to coerce anything but __weak* to | |||
1771 | // the resulting type. | |||
1772 | if (type.isConstQualified()) { | |||
1773 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | |||
1774 | ||||
1775 | // Otherwise, check whether the static type does not require | |||
1776 | // retaining. This currently only triggers for Class (possibly | |||
1777 | // protocol-qualifed, and arrays thereof). | |||
1778 | } else if (type->isObjCARCImplicitlyUnretainedType()) { | |||
1779 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | |||
1780 | ||||
1781 | // If we are in an unevaluated context, like sizeof, skip adding a | |||
1782 | // qualification. | |||
1783 | } else if (S.isUnevaluatedContext()) { | |||
1784 | return type; | |||
1785 | ||||
1786 | // If that failed, give an error and recover using __strong. __strong | |||
1787 | // is the option most likely to prevent spurious second-order diagnostics, | |||
1788 | // like when binding a reference to a field. | |||
1789 | } else { | |||
1790 | // These types can show up in private ivars in system headers, so | |||
1791 | // we need this to not be an error in those cases. Instead we | |||
1792 | // want to delay. | |||
1793 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | |||
1794 | S.DelayedDiagnostics.add( | |||
1795 | sema::DelayedDiagnostic::makeForbiddenType(loc, | |||
1796 | diag::err_arc_indirect_no_ownership, type, isReference)); | |||
1797 | } else { | |||
1798 | S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; | |||
1799 | } | |||
1800 | implicitLifetime = Qualifiers::OCL_Strong; | |||
1801 | } | |||
1802 | assert(implicitLifetime && "didn't infer any lifetime!")(static_cast <bool> (implicitLifetime && "didn't infer any lifetime!" ) ? void (0) : __assert_fail ("implicitLifetime && \"didn't infer any lifetime!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1802, __extension__ __PRETTY_FUNCTION__)); | |||
1803 | ||||
1804 | Qualifiers qs; | |||
1805 | qs.addObjCLifetime(implicitLifetime); | |||
1806 | return S.Context.getQualifiedType(type, qs); | |||
1807 | } | |||
1808 | ||||
1809 | static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ | |||
1810 | std::string Quals = | |||
1811 | Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); | |||
1812 | ||||
1813 | switch (FnTy->getRefQualifier()) { | |||
1814 | case RQ_None: | |||
1815 | break; | |||
1816 | ||||
1817 | case RQ_LValue: | |||
1818 | if (!Quals.empty()) | |||
1819 | Quals += ' '; | |||
1820 | Quals += '&'; | |||
1821 | break; | |||
1822 | ||||
1823 | case RQ_RValue: | |||
1824 | if (!Quals.empty()) | |||
1825 | Quals += ' '; | |||
1826 | Quals += "&&"; | |||
1827 | break; | |||
1828 | } | |||
1829 | ||||
1830 | return Quals; | |||
1831 | } | |||
1832 | ||||
1833 | namespace { | |||
1834 | /// Kinds of declarator that cannot contain a qualified function type. | |||
1835 | /// | |||
1836 | /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: | |||
1837 | /// a function type with a cv-qualifier or a ref-qualifier can only appear | |||
1838 | /// at the topmost level of a type. | |||
1839 | /// | |||
1840 | /// Parens and member pointers are permitted. We don't diagnose array and | |||
1841 | /// function declarators, because they don't allow function types at all. | |||
1842 | /// | |||
1843 | /// The values of this enum are used in diagnostics. | |||
1844 | enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; | |||
1845 | } // end anonymous namespace | |||
1846 | ||||
1847 | /// Check whether the type T is a qualified function type, and if it is, | |||
1848 | /// diagnose that it cannot be contained within the given kind of declarator. | |||
1849 | static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, | |||
1850 | QualifiedFunctionKind QFK) { | |||
1851 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | |||
1852 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); | |||
1853 | if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None)) | |||
1854 | return false; | |||
1855 | ||||
1856 | S.Diag(Loc, diag::err_compound_qualified_function_type) | |||
1857 | << QFK << isa<FunctionType>(T.IgnoreParens()) << T | |||
1858 | << getFunctionQualifiersAsString(FPT); | |||
1859 | return true; | |||
1860 | } | |||
1861 | ||||
1862 | /// \brief Build a pointer type. | |||
1863 | /// | |||
1864 | /// \param T The type to which we'll be building a pointer. | |||
1865 | /// | |||
1866 | /// \param Loc The location of the entity whose type involves this | |||
1867 | /// pointer type or, if there is no such entity, the location of the | |||
1868 | /// type that will have pointer type. | |||
1869 | /// | |||
1870 | /// \param Entity The name of the entity that involves the pointer | |||
1871 | /// type, if known. | |||
1872 | /// | |||
1873 | /// \returns A suitable pointer type, if there are no | |||
1874 | /// errors. Otherwise, returns a NULL type. | |||
1875 | QualType Sema::BuildPointerType(QualType T, | |||
1876 | SourceLocation Loc, DeclarationName Entity) { | |||
1877 | if (T->isReferenceType()) { | |||
1878 | // C++ 8.3.2p4: There shall be no ... pointers to references ... | |||
1879 | Diag(Loc, diag::err_illegal_decl_pointer_to_reference) | |||
1880 | << getPrintableNameForEntity(Entity) << T; | |||
1881 | return QualType(); | |||
1882 | } | |||
1883 | ||||
1884 | if (T->isFunctionType() && getLangOpts().OpenCL) { | |||
1885 | Diag(Loc, diag::err_opencl_function_pointer); | |||
1886 | return QualType(); | |||
1887 | } | |||
1888 | ||||
1889 | if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) | |||
1890 | return QualType(); | |||
1891 | ||||
1892 | assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType")(static_cast <bool> (!T->isObjCObjectType() && "Should build ObjCObjectPointerType") ? void (0) : __assert_fail ("!T->isObjCObjectType() && \"Should build ObjCObjectPointerType\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1892, __extension__ __PRETTY_FUNCTION__)); | |||
1893 | ||||
1894 | // In ARC, it is forbidden to build pointers to unqualified pointers. | |||
1895 | if (getLangOpts().ObjCAutoRefCount) | |||
1896 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); | |||
1897 | ||||
1898 | // Build the pointer type. | |||
1899 | return Context.getPointerType(T); | |||
1900 | } | |||
1901 | ||||
1902 | /// \brief Build a reference type. | |||
1903 | /// | |||
1904 | /// \param T The type to which we'll be building a reference. | |||
1905 | /// | |||
1906 | /// \param Loc The location of the entity whose type involves this | |||
1907 | /// reference type or, if there is no such entity, the location of the | |||
1908 | /// type that will have reference type. | |||
1909 | /// | |||
1910 | /// \param Entity The name of the entity that involves the reference | |||
1911 | /// type, if known. | |||
1912 | /// | |||
1913 | /// \returns A suitable reference type, if there are no | |||
1914 | /// errors. Otherwise, returns a NULL type. | |||
1915 | QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, | |||
1916 | SourceLocation Loc, | |||
1917 | DeclarationName Entity) { | |||
1918 | assert(Context.getCanonicalType(T) != Context.OverloadTy &&(static_cast <bool> (Context.getCanonicalType(T) != Context .OverloadTy && "Unresolved overloaded function type") ? void (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1919, __extension__ __PRETTY_FUNCTION__)) | |||
1919 | "Unresolved overloaded function type")(static_cast <bool> (Context.getCanonicalType(T) != Context .OverloadTy && "Unresolved overloaded function type") ? void (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 1919, __extension__ __PRETTY_FUNCTION__)); | |||
1920 | ||||
1921 | // C++0x [dcl.ref]p6: | |||
1922 | // If a typedef (7.1.3), a type template-parameter (14.3.1), or a | |||
1923 | // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a | |||
1924 | // type T, an attempt to create the type "lvalue reference to cv TR" creates | |||
1925 | // the type "lvalue reference to T", while an attempt to create the type | |||
1926 | // "rvalue reference to cv TR" creates the type TR. | |||
1927 | bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); | |||
1928 | ||||
1929 | // C++ [dcl.ref]p4: There shall be no references to references. | |||
1930 | // | |||
1931 | // According to C++ DR 106, references to references are only | |||
1932 | // diagnosed when they are written directly (e.g., "int & &"), | |||
1933 | // but not when they happen via a typedef: | |||
1934 | // | |||
1935 | // typedef int& intref; | |||
1936 | // typedef intref& intref2; | |||
1937 | // | |||
1938 | // Parser::ParseDeclaratorInternal diagnoses the case where | |||
1939 | // references are written directly; here, we handle the | |||
1940 | // collapsing of references-to-references as described in C++0x. | |||
1941 | // DR 106 and 540 introduce reference-collapsing into C++98/03. | |||
1942 | ||||
1943 | // C++ [dcl.ref]p1: | |||
1944 | // A declarator that specifies the type "reference to cv void" | |||
1945 | // is ill-formed. | |||
1946 | if (T->isVoidType()) { | |||
1947 | Diag(Loc, diag::err_reference_to_void); | |||
1948 | return QualType(); | |||
1949 | } | |||
1950 | ||||
1951 | if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) | |||
1952 | return QualType(); | |||
1953 | ||||
1954 | // In ARC, it is forbidden to build references to unqualified pointers. | |||
1955 | if (getLangOpts().ObjCAutoRefCount) | |||
1956 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); | |||
1957 | ||||
1958 | // Handle restrict on references. | |||
1959 | if (LValueRef) | |||
1960 | return Context.getLValueReferenceType(T, SpelledAsLValue); | |||
1961 | return Context.getRValueReferenceType(T); | |||
1962 | } | |||
1963 | ||||
1964 | /// \brief Build a Read-only Pipe type. | |||
1965 | /// | |||
1966 | /// \param T The type to which we'll be building a Pipe. | |||
1967 | /// | |||
1968 | /// \param Loc We do not use it for now. | |||
1969 | /// | |||
1970 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | |||
1971 | /// NULL type. | |||
1972 | QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { | |||
1973 | return Context.getReadPipeType(T); | |||
1974 | } | |||
1975 | ||||
1976 | /// \brief Build a Write-only Pipe type. | |||
1977 | /// | |||
1978 | /// \param T The type to which we'll be building a Pipe. | |||
1979 | /// | |||
1980 | /// \param Loc We do not use it for now. | |||
1981 | /// | |||
1982 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | |||
1983 | /// NULL type. | |||
1984 | QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { | |||
1985 | return Context.getWritePipeType(T); | |||
1986 | } | |||
1987 | ||||
1988 | /// Check whether the specified array size makes the array type a VLA. If so, | |||
1989 | /// return true, if not, return the size of the array in SizeVal. | |||
1990 | static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { | |||
1991 | // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode | |||
1992 | // (like gnu99, but not c99) accept any evaluatable value as an extension. | |||
1993 | class VLADiagnoser : public Sema::VerifyICEDiagnoser { | |||
1994 | public: | |||
1995 | VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} | |||
1996 | ||||
1997 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { | |||
1998 | } | |||
1999 | ||||
2000 | void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override { | |||
2001 | S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; | |||
2002 | } | |||
2003 | } Diagnoser; | |||
2004 | ||||
2005 | return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, | |||
2006 | S.LangOpts.GNUMode || | |||
2007 | S.LangOpts.OpenCL).isInvalid(); | |||
2008 | } | |||
2009 | ||||
2010 | /// \brief Build an array type. | |||
2011 | /// | |||
2012 | /// \param T The type of each element in the array. | |||
2013 | /// | |||
2014 | /// \param ASM C99 array size modifier (e.g., '*', 'static'). | |||
2015 | /// | |||
2016 | /// \param ArraySize Expression describing the size of the array. | |||
2017 | /// | |||
2018 | /// \param Brackets The range from the opening '[' to the closing ']'. | |||
2019 | /// | |||
2020 | /// \param Entity The name of the entity that involves the array | |||
2021 | /// type, if known. | |||
2022 | /// | |||
2023 | /// \returns A suitable array type, if there are no errors. Otherwise, | |||
2024 | /// returns a NULL type. | |||
2025 | QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, | |||
2026 | Expr *ArraySize, unsigned Quals, | |||
2027 | SourceRange Brackets, DeclarationName Entity) { | |||
2028 | ||||
2029 | SourceLocation Loc = Brackets.getBegin(); | |||
2030 | if (getLangOpts().CPlusPlus) { | |||
| ||||
2031 | // C++ [dcl.array]p1: | |||
2032 | // T is called the array element type; this type shall not be a reference | |||
2033 | // type, the (possibly cv-qualified) type void, a function type or an | |||
2034 | // abstract class type. | |||
2035 | // | |||
2036 | // C++ [dcl.array]p3: | |||
2037 | // When several "array of" specifications are adjacent, [...] only the | |||
2038 | // first of the constant expressions that specify the bounds of the arrays | |||
2039 | // may be omitted. | |||
2040 | // | |||
2041 | // Note: function types are handled in the common path with C. | |||
2042 | if (T->isReferenceType()) { | |||
2043 | Diag(Loc, diag::err_illegal_decl_array_of_references) | |||
2044 | << getPrintableNameForEntity(Entity) << T; | |||
2045 | return QualType(); | |||
2046 | } | |||
2047 | ||||
2048 | if (T->isVoidType() || T->isIncompleteArrayType()) { | |||
2049 | Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; | |||
2050 | return QualType(); | |||
2051 | } | |||
2052 | ||||
2053 | if (RequireNonAbstractType(Brackets.getBegin(), T, | |||
2054 | diag::err_array_of_abstract_type)) | |||
2055 | return QualType(); | |||
2056 | ||||
2057 | // Mentioning a member pointer type for an array type causes us to lock in | |||
2058 | // an inheritance model, even if it's inside an unused typedef. | |||
2059 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
2060 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) | |||
2061 | if (!MPTy->getClass()->isDependentType()) | |||
2062 | (void)isCompleteType(Loc, T); | |||
2063 | ||||
2064 | } else { | |||
2065 | // C99 6.7.5.2p1: If the element type is an incomplete or function type, | |||
2066 | // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) | |||
2067 | if (RequireCompleteType(Loc, T, | |||
2068 | diag::err_illegal_decl_array_incomplete_type)) | |||
2069 | return QualType(); | |||
2070 | } | |||
2071 | ||||
2072 | if (T->isFunctionType()) { | |||
2073 | Diag(Loc, diag::err_illegal_decl_array_of_functions) | |||
2074 | << getPrintableNameForEntity(Entity) << T; | |||
2075 | return QualType(); | |||
2076 | } | |||
2077 | ||||
2078 | if (const RecordType *EltTy = T->getAs<RecordType>()) { | |||
2079 | // If the element type is a struct or union that contains a variadic | |||
2080 | // array, accept it as a GNU extension: C99 6.7.2.1p2. | |||
2081 | if (EltTy->getDecl()->hasFlexibleArrayMember()) | |||
2082 | Diag(Loc, diag::ext_flexible_array_in_array) << T; | |||
2083 | } else if (T->isObjCObjectType()) { | |||
2084 | Diag(Loc, diag::err_objc_array_of_interfaces) << T; | |||
2085 | return QualType(); | |||
2086 | } | |||
2087 | ||||
2088 | // Do placeholder conversions on the array size expression. | |||
2089 | if (ArraySize && ArraySize->hasPlaceholderType()) { | |||
2090 | ExprResult Result = CheckPlaceholderExpr(ArraySize); | |||
2091 | if (Result.isInvalid()) return QualType(); | |||
2092 | ArraySize = Result.get(); | |||
2093 | } | |||
2094 | ||||
2095 | // Do lvalue-to-rvalue conversions on the array size expression. | |||
2096 | if (ArraySize && !ArraySize->isRValue()) { | |||
2097 | ExprResult Result = DefaultLvalueConversion(ArraySize); | |||
2098 | if (Result.isInvalid()) | |||
2099 | return QualType(); | |||
2100 | ||||
2101 | ArraySize = Result.get(); | |||
2102 | } | |||
2103 | ||||
2104 | // C99 6.7.5.2p1: The size expression shall have integer type. | |||
2105 | // C++11 allows contextual conversions to such types. | |||
2106 | if (!getLangOpts().CPlusPlus11 && | |||
2107 | ArraySize && !ArraySize->isTypeDependent() && | |||
2108 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
2109 | Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) | |||
2110 | << ArraySize->getType() << ArraySize->getSourceRange(); | |||
2111 | return QualType(); | |||
2112 | } | |||
2113 | ||||
2114 | llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); | |||
2115 | if (!ArraySize) { | |||
2116 | if (ASM == ArrayType::Star) | |||
2117 | T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); | |||
2118 | else | |||
2119 | T = Context.getIncompleteArrayType(T, ASM, Quals); | |||
2120 | } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { | |||
2121 | T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2122 | } else if ((!T->isDependentType() && !T->isIncompleteType() && | |||
2123 | !T->isConstantSizeType()) || | |||
2124 | isArraySizeVLA(*this, ArraySize, ConstVal)) { | |||
2125 | // Even in C++11, don't allow contextual conversions in the array bound | |||
2126 | // of a VLA. | |||
2127 | if (getLangOpts().CPlusPlus11 && | |||
2128 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
2129 | Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) | |||
2130 | << ArraySize->getType() << ArraySize->getSourceRange(); | |||
2131 | return QualType(); | |||
2132 | } | |||
2133 | ||||
2134 | // C99: an array with an element type that has a non-constant-size is a VLA. | |||
2135 | // C99: an array with a non-ICE size is a VLA. We accept any expression | |||
2136 | // that we can fold to a non-zero positive value as an extension. | |||
2137 | T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2138 | } else { | |||
2139 | // C99 6.7.5.2p1: If the expression is a constant expression, it shall | |||
2140 | // have a value greater than zero. | |||
2141 | if (ConstVal.isSigned() && ConstVal.isNegative()) { | |||
2142 | if (Entity) | |||
2143 | Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) | |||
2144 | << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); | |||
2145 | else | |||
2146 | Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) | |||
2147 | << ArraySize->getSourceRange(); | |||
2148 | return QualType(); | |||
2149 | } | |||
2150 | if (ConstVal == 0) { | |||
2151 | // GCC accepts zero sized static arrays. We allow them when | |||
2152 | // we're not in a SFINAE context. | |||
2153 | Diag(ArraySize->getLocStart(), | |||
2154 | isSFINAEContext()? diag::err_typecheck_zero_array_size | |||
2155 | : diag::ext_typecheck_zero_array_size) | |||
2156 | << ArraySize->getSourceRange(); | |||
2157 | ||||
2158 | if (ASM == ArrayType::Static) { | |||
2159 | Diag(ArraySize->getLocStart(), | |||
2160 | diag::warn_typecheck_zero_static_array_size) | |||
2161 | << ArraySize->getSourceRange(); | |||
2162 | ASM = ArrayType::Normal; | |||
2163 | } | |||
2164 | } else if (!T->isDependentType() && !T->isVariablyModifiedType() && | |||
2165 | !T->isIncompleteType() && !T->isUndeducedType()) { | |||
2166 | // Is the array too large? | |||
2167 | unsigned ActiveSizeBits | |||
2168 | = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); | |||
2169 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | |||
2170 | Diag(ArraySize->getLocStart(), diag::err_array_too_large) | |||
2171 | << ConstVal.toString(10) | |||
2172 | << ArraySize->getSourceRange(); | |||
2173 | return QualType(); | |||
2174 | } | |||
2175 | } | |||
2176 | ||||
2177 | T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); | |||
2178 | } | |||
2179 | ||||
2180 | // OpenCL v1.2 s6.9.d: variable length arrays are not supported. | |||
2181 | if (getLangOpts().OpenCL && T->isVariableArrayType()) { | |||
2182 | Diag(Loc, diag::err_opencl_vla); | |||
2183 | return QualType(); | |||
2184 | } | |||
2185 | ||||
2186 | if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) { | |||
2187 | if (getLangOpts().CUDA) { | |||
2188 | // CUDA device code doesn't support VLAs. | |||
2189 | CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget(); | |||
2190 | } else if (!getLangOpts().OpenMP || | |||
2191 | shouldDiagnoseTargetSupportFromOpenMP()) { | |||
2192 | // Some targets don't support VLAs. | |||
2193 | Diag(Loc, diag::err_vla_unsupported); | |||
2194 | return QualType(); | |||
2195 | } | |||
2196 | } | |||
2197 | ||||
2198 | // If this is not C99, extwarn about VLA's and C99 array size modifiers. | |||
2199 | if (!getLangOpts().C99) { | |||
| ||||
2200 | if (T->isVariableArrayType()) { | |||
2201 | // Prohibit the use of VLAs during template argument deduction. | |||
2202 | if (isSFINAEContext()) { | |||
2203 | Diag(Loc, diag::err_vla_in_sfinae); | |||
2204 | return QualType(); | |||
2205 | } | |||
2206 | // Just extwarn about VLAs. | |||
2207 | else | |||
2208 | Diag(Loc, diag::ext_vla); | |||
2209 | } else if (ASM != ArrayType::Normal || Quals != 0) | |||
2210 | Diag(Loc, | |||
2211 | getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx | |||
2212 | : diag::ext_c99_array_usage) << ASM; | |||
2213 | } | |||
2214 | ||||
2215 | if (T->isVariableArrayType()) { | |||
2216 | // Warn about VLAs for -Wvla. | |||
2217 | Diag(Loc, diag::warn_vla_used); | |||
2218 | } | |||
2219 | ||||
2220 | // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. | |||
2221 | // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. | |||
2222 | // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. | |||
2223 | if (getLangOpts().OpenCL) { | |||
2224 | const QualType ArrType = Context.getBaseElementType(T); | |||
2225 | if (ArrType->isBlockPointerType() || ArrType->isPipeType() || | |||
2226 | ArrType->isSamplerT() || ArrType->isImageType()) { | |||
2227 | Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; | |||
2228 | return QualType(); | |||
2229 | } | |||
2230 | } | |||
2231 | ||||
2232 | return T; | |||
2233 | } | |||
2234 | ||||
2235 | /// \brief Build an ext-vector type. | |||
2236 | /// | |||
2237 | /// Run the required checks for the extended vector type. | |||
2238 | QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, | |||
2239 | SourceLocation AttrLoc) { | |||
2240 | // Unlike gcc's vector_size attribute, we do not allow vectors to be defined | |||
2241 | // in conjunction with complex types (pointers, arrays, functions, etc.). | |||
2242 | // | |||
2243 | // Additionally, OpenCL prohibits vectors of booleans (they're considered a | |||
2244 | // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects | |||
2245 | // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors | |||
2246 | // of bool aren't allowed. | |||
2247 | if ((!T->isDependentType() && !T->isIntegerType() && | |||
2248 | !T->isRealFloatingType()) || | |||
2249 | T->isBooleanType()) { | |||
2250 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; | |||
2251 | return QualType(); | |||
2252 | } | |||
2253 | ||||
2254 | if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { | |||
2255 | llvm::APSInt vecSize(32); | |||
2256 | if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { | |||
2257 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2258 | << "ext_vector_type" << AANT_ArgumentIntegerConstant | |||
2259 | << ArraySize->getSourceRange(); | |||
2260 | return QualType(); | |||
2261 | } | |||
2262 | ||||
2263 | // Unlike gcc's vector_size attribute, the size is specified as the | |||
2264 | // number of elements, not the number of bytes. | |||
2265 | unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); | |||
2266 | ||||
2267 | if (vectorSize == 0) { | |||
2268 | Diag(AttrLoc, diag::err_attribute_zero_size) | |||
2269 | << ArraySize->getSourceRange(); | |||
2270 | return QualType(); | |||
2271 | } | |||
2272 | ||||
2273 | if (VectorType::isVectorSizeTooLarge(vectorSize)) { | |||
2274 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2275 | << ArraySize->getSourceRange(); | |||
2276 | return QualType(); | |||
2277 | } | |||
2278 | ||||
2279 | return Context.getExtVectorType(T, vectorSize); | |||
2280 | } | |||
2281 | ||||
2282 | return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); | |||
2283 | } | |||
2284 | ||||
2285 | bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { | |||
2286 | if (T->isArrayType() || T->isFunctionType()) { | |||
2287 | Diag(Loc, diag::err_func_returning_array_function) | |||
2288 | << T->isFunctionType() << T; | |||
2289 | return true; | |||
2290 | } | |||
2291 | ||||
2292 | // Functions cannot return half FP. | |||
2293 | if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { | |||
2294 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << | |||
2295 | FixItHint::CreateInsertion(Loc, "*"); | |||
2296 | return true; | |||
2297 | } | |||
2298 | ||||
2299 | // Methods cannot return interface types. All ObjC objects are | |||
2300 | // passed by reference. | |||
2301 | if (T->isObjCObjectType()) { | |||
2302 | Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) | |||
2303 | << 0 << T << FixItHint::CreateInsertion(Loc, "*"); | |||
2304 | return true; | |||
2305 | } | |||
2306 | ||||
2307 | return false; | |||
2308 | } | |||
2309 | ||||
2310 | /// Check the extended parameter information. Most of the necessary | |||
2311 | /// checking should occur when applying the parameter attribute; the | |||
2312 | /// only other checks required are positional restrictions. | |||
2313 | static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, | |||
2314 | const FunctionProtoType::ExtProtoInfo &EPI, | |||
2315 | llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { | |||
2316 | assert(EPI.ExtParameterInfos && "shouldn't get here without param infos")(static_cast <bool> (EPI.ExtParameterInfos && "shouldn't get here without param infos" ) ? void (0) : __assert_fail ("EPI.ExtParameterInfos && \"shouldn't get here without param infos\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 2316, __extension__ __PRETTY_FUNCTION__)); | |||
2317 | ||||
2318 | bool hasCheckedSwiftCall = false; | |||
2319 | auto checkForSwiftCC = [&](unsigned paramIndex) { | |||
2320 | // Only do this once. | |||
2321 | if (hasCheckedSwiftCall) return; | |||
2322 | hasCheckedSwiftCall = true; | |||
2323 | if (EPI.ExtInfo.getCC() == CC_Swift) return; | |||
2324 | S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) | |||
2325 | << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()); | |||
2326 | }; | |||
2327 | ||||
2328 | for (size_t paramIndex = 0, numParams = paramTypes.size(); | |||
2329 | paramIndex != numParams; ++paramIndex) { | |||
2330 | switch (EPI.ExtParameterInfos[paramIndex].getABI()) { | |||
2331 | // Nothing interesting to check for orindary-ABI parameters. | |||
2332 | case ParameterABI::Ordinary: | |||
2333 | continue; | |||
2334 | ||||
2335 | // swift_indirect_result parameters must be a prefix of the function | |||
2336 | // arguments. | |||
2337 | case ParameterABI::SwiftIndirectResult: | |||
2338 | checkForSwiftCC(paramIndex); | |||
2339 | if (paramIndex != 0 && | |||
2340 | EPI.ExtParameterInfos[paramIndex - 1].getABI() | |||
2341 | != ParameterABI::SwiftIndirectResult) { | |||
2342 | S.Diag(getParamLoc(paramIndex), | |||
2343 | diag::err_swift_indirect_result_not_first); | |||
2344 | } | |||
2345 | continue; | |||
2346 | ||||
2347 | case ParameterABI::SwiftContext: | |||
2348 | checkForSwiftCC(paramIndex); | |||
2349 | continue; | |||
2350 | ||||
2351 | // swift_error parameters must be preceded by a swift_context parameter. | |||
2352 | case ParameterABI::SwiftErrorResult: | |||
2353 | checkForSwiftCC(paramIndex); | |||
2354 | if (paramIndex == 0 || | |||
2355 | EPI.ExtParameterInfos[paramIndex - 1].getABI() != | |||
2356 | ParameterABI::SwiftContext) { | |||
2357 | S.Diag(getParamLoc(paramIndex), | |||
2358 | diag::err_swift_error_result_not_after_swift_context); | |||
2359 | } | |||
2360 | continue; | |||
2361 | } | |||
2362 | llvm_unreachable("bad ABI kind")::llvm::llvm_unreachable_internal("bad ABI kind", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 2362); | |||
2363 | } | |||
2364 | } | |||
2365 | ||||
2366 | QualType Sema::BuildFunctionType(QualType T, | |||
2367 | MutableArrayRef<QualType> ParamTypes, | |||
2368 | SourceLocation Loc, DeclarationName Entity, | |||
2369 | const FunctionProtoType::ExtProtoInfo &EPI) { | |||
2370 | bool Invalid = false; | |||
2371 | ||||
2372 | Invalid |= CheckFunctionReturnType(T, Loc); | |||
2373 | ||||
2374 | for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { | |||
2375 | // FIXME: Loc is too inprecise here, should use proper locations for args. | |||
2376 | QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); | |||
2377 | if (ParamType->isVoidType()) { | |||
2378 | Diag(Loc, diag::err_param_with_void_type); | |||
2379 | Invalid = true; | |||
2380 | } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { | |||
2381 | // Disallow half FP arguments. | |||
2382 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << | |||
2383 | FixItHint::CreateInsertion(Loc, "*"); | |||
2384 | Invalid = true; | |||
2385 | } | |||
2386 | ||||
2387 | ParamTypes[Idx] = ParamType; | |||
2388 | } | |||
2389 | ||||
2390 | if (EPI.ExtParameterInfos) { | |||
2391 | checkExtParameterInfos(*this, ParamTypes, EPI, | |||
2392 | [=](unsigned i) { return Loc; }); | |||
2393 | } | |||
2394 | ||||
2395 | if (EPI.ExtInfo.getProducesResult()) { | |||
2396 | // This is just a warning, so we can't fail to build if we see it. | |||
2397 | checkNSReturnsRetainedReturnType(Loc, T); | |||
2398 | } | |||
2399 | ||||
2400 | if (Invalid) | |||
2401 | return QualType(); | |||
2402 | ||||
2403 | return Context.getFunctionType(T, ParamTypes, EPI); | |||
2404 | } | |||
2405 | ||||
2406 | /// \brief Build a member pointer type \c T Class::*. | |||
2407 | /// | |||
2408 | /// \param T the type to which the member pointer refers. | |||
2409 | /// \param Class the class type into which the member pointer points. | |||
2410 | /// \param Loc the location where this type begins | |||
2411 | /// \param Entity the name of the entity that will have this member pointer type | |||
2412 | /// | |||
2413 | /// \returns a member pointer type, if successful, or a NULL type if there was | |||
2414 | /// an error. | |||
2415 | QualType Sema::BuildMemberPointerType(QualType T, QualType Class, | |||
2416 | SourceLocation Loc, | |||
2417 | DeclarationName Entity) { | |||
2418 | // Verify that we're not building a pointer to pointer to function with | |||
2419 | // exception specification. | |||
2420 | if (CheckDistantExceptionSpec(T)) { | |||
2421 | Diag(Loc, diag::err_distant_exception_spec); | |||
2422 | return QualType(); | |||
2423 | } | |||
2424 | ||||
2425 | // C++ 8.3.3p3: A pointer to member shall not point to ... a member | |||
2426 | // with reference type, or "cv void." | |||
2427 | if (T->isReferenceType()) { | |||
2428 | Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) | |||
2429 | << getPrintableNameForEntity(Entity) << T; | |||
2430 | return QualType(); | |||
2431 | } | |||
2432 | ||||
2433 | if (T->isVoidType()) { | |||
2434 | Diag(Loc, diag::err_illegal_decl_mempointer_to_void) | |||
2435 | << getPrintableNameForEntity(Entity); | |||
2436 | return QualType(); | |||
2437 | } | |||
2438 | ||||
2439 | if (!Class->isDependentType() && !Class->isRecordType()) { | |||
2440 | Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; | |||
2441 | return QualType(); | |||
2442 | } | |||
2443 | ||||
2444 | // Adjust the default free function calling convention to the default method | |||
2445 | // calling convention. | |||
2446 | bool IsCtorOrDtor = | |||
2447 | (Entity.getNameKind() == DeclarationName::CXXConstructorName) || | |||
2448 | (Entity.getNameKind() == DeclarationName::CXXDestructorName); | |||
2449 | if (T->isFunctionType()) | |||
2450 | adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); | |||
2451 | ||||
2452 | return Context.getMemberPointerType(T, Class.getTypePtr()); | |||
2453 | } | |||
2454 | ||||
2455 | /// \brief Build a block pointer type. | |||
2456 | /// | |||
2457 | /// \param T The type to which we'll be building a block pointer. | |||
2458 | /// | |||
2459 | /// \param Loc The source location, used for diagnostics. | |||
2460 | /// | |||
2461 | /// \param Entity The name of the entity that involves the block pointer | |||
2462 | /// type, if known. | |||
2463 | /// | |||
2464 | /// \returns A suitable block pointer type, if there are no | |||
2465 | /// errors. Otherwise, returns a NULL type. | |||
2466 | QualType Sema::BuildBlockPointerType(QualType T, | |||
2467 | SourceLocation Loc, | |||
2468 | DeclarationName Entity) { | |||
2469 | if (!T->isFunctionType()) { | |||
2470 | Diag(Loc, diag::err_nonfunction_block_type); | |||
2471 | return QualType(); | |||
2472 | } | |||
2473 | ||||
2474 | if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) | |||
2475 | return QualType(); | |||
2476 | ||||
2477 | return Context.getBlockPointerType(T); | |||
2478 | } | |||
2479 | ||||
2480 | QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { | |||
2481 | QualType QT = Ty.get(); | |||
2482 | if (QT.isNull()) { | |||
2483 | if (TInfo) *TInfo = nullptr; | |||
2484 | return QualType(); | |||
2485 | } | |||
2486 | ||||
2487 | TypeSourceInfo *DI = nullptr; | |||
2488 | if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { | |||
2489 | QT = LIT->getType(); | |||
2490 | DI = LIT->getTypeSourceInfo(); | |||
2491 | } | |||
2492 | ||||
2493 | if (TInfo) *TInfo = DI; | |||
2494 | return QT; | |||
2495 | } | |||
2496 | ||||
2497 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | |||
2498 | Qualifiers::ObjCLifetime ownership, | |||
2499 | unsigned chunkIndex); | |||
2500 | ||||
2501 | /// Given that this is the declaration of a parameter under ARC, | |||
2502 | /// attempt to infer attributes and such for pointer-to-whatever | |||
2503 | /// types. | |||
2504 | static void inferARCWriteback(TypeProcessingState &state, | |||
2505 | QualType &declSpecType) { | |||
2506 | Sema &S = state.getSema(); | |||
2507 | Declarator &declarator = state.getDeclarator(); | |||
2508 | ||||
2509 | // TODO: should we care about decl qualifiers? | |||
2510 | ||||
2511 | // Check whether the declarator has the expected form. We walk | |||
2512 | // from the inside out in order to make the block logic work. | |||
2513 | unsigned outermostPointerIndex = 0; | |||
2514 | bool isBlockPointer = false; | |||
2515 | unsigned numPointers = 0; | |||
2516 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
2517 | unsigned chunkIndex = i; | |||
2518 | DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); | |||
2519 | switch (chunk.Kind) { | |||
2520 | case DeclaratorChunk::Paren: | |||
2521 | // Ignore parens. | |||
2522 | break; | |||
2523 | ||||
2524 | case DeclaratorChunk::Reference: | |||
2525 | case DeclaratorChunk::Pointer: | |||
2526 | // Count the number of pointers. Treat references | |||
2527 | // interchangeably as pointers; if they're mis-ordered, normal | |||
2528 | // type building will discover that. | |||
2529 | outermostPointerIndex = chunkIndex; | |||
2530 | numPointers++; | |||
2531 | break; | |||
2532 | ||||
2533 | case DeclaratorChunk::BlockPointer: | |||
2534 | // If we have a pointer to block pointer, that's an acceptable | |||
2535 | // indirect reference; anything else is not an application of | |||
2536 | // the rules. | |||
2537 | if (numPointers != 1) return; | |||
2538 | numPointers++; | |||
2539 | outermostPointerIndex = chunkIndex; | |||
2540 | isBlockPointer = true; | |||
2541 | ||||
2542 | // We don't care about pointer structure in return values here. | |||
2543 | goto done; | |||
2544 | ||||
2545 | case DeclaratorChunk::Array: // suppress if written (id[])? | |||
2546 | case DeclaratorChunk::Function: | |||
2547 | case DeclaratorChunk::MemberPointer: | |||
2548 | case DeclaratorChunk::Pipe: | |||
2549 | return; | |||
2550 | } | |||
2551 | } | |||
2552 | done: | |||
2553 | ||||
2554 | // If we have *one* pointer, then we want to throw the qualifier on | |||
2555 | // the declaration-specifiers, which means that it needs to be a | |||
2556 | // retainable object type. | |||
2557 | if (numPointers == 1) { | |||
2558 | // If it's not a retainable object type, the rule doesn't apply. | |||
2559 | if (!declSpecType->isObjCRetainableType()) return; | |||
2560 | ||||
2561 | // If it already has lifetime, don't do anything. | |||
2562 | if (declSpecType.getObjCLifetime()) return; | |||
2563 | ||||
2564 | // Otherwise, modify the type in-place. | |||
2565 | Qualifiers qs; | |||
2566 | ||||
2567 | if (declSpecType->isObjCARCImplicitlyUnretainedType()) | |||
2568 | qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); | |||
2569 | else | |||
2570 | qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); | |||
2571 | declSpecType = S.Context.getQualifiedType(declSpecType, qs); | |||
2572 | ||||
2573 | // If we have *two* pointers, then we want to throw the qualifier on | |||
2574 | // the outermost pointer. | |||
2575 | } else if (numPointers == 2) { | |||
2576 | // If we don't have a block pointer, we need to check whether the | |||
2577 | // declaration-specifiers gave us something that will turn into a | |||
2578 | // retainable object pointer after we slap the first pointer on it. | |||
2579 | if (!isBlockPointer && !declSpecType->isObjCObjectType()) | |||
2580 | return; | |||
2581 | ||||
2582 | // Look for an explicit lifetime attribute there. | |||
2583 | DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); | |||
2584 | if (chunk.Kind != DeclaratorChunk::Pointer && | |||
2585 | chunk.Kind != DeclaratorChunk::BlockPointer) | |||
2586 | return; | |||
2587 | for (const AttributeList *attr = chunk.getAttrs(); attr; | |||
2588 | attr = attr->getNext()) | |||
2589 | if (attr->getKind() == AttributeList::AT_ObjCOwnership) | |||
2590 | return; | |||
2591 | ||||
2592 | transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, | |||
2593 | outermostPointerIndex); | |||
2594 | ||||
2595 | // Any other number of pointers/references does not trigger the rule. | |||
2596 | } else return; | |||
2597 | ||||
2598 | // TODO: mark whether we did this inference? | |||
2599 | } | |||
2600 | ||||
2601 | void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, | |||
2602 | SourceLocation FallbackLoc, | |||
2603 | SourceLocation ConstQualLoc, | |||
2604 | SourceLocation VolatileQualLoc, | |||
2605 | SourceLocation RestrictQualLoc, | |||
2606 | SourceLocation AtomicQualLoc, | |||
2607 | SourceLocation UnalignedQualLoc) { | |||
2608 | if (!Quals) | |||
2609 | return; | |||
2610 | ||||
2611 | struct Qual { | |||
2612 | const char *Name; | |||
2613 | unsigned Mask; | |||
2614 | SourceLocation Loc; | |||
2615 | } const QualKinds[5] = { | |||
2616 | { "const", DeclSpec::TQ_const, ConstQualLoc }, | |||
2617 | { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, | |||
2618 | { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, | |||
2619 | { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc }, | |||
2620 | { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } | |||
2621 | }; | |||
2622 | ||||
2623 | SmallString<32> QualStr; | |||
2624 | unsigned NumQuals = 0; | |||
2625 | SourceLocation Loc; | |||
2626 | FixItHint FixIts[5]; | |||
2627 | ||||
2628 | // Build a string naming the redundant qualifiers. | |||
2629 | for (auto &E : QualKinds) { | |||
2630 | if (Quals & E.Mask) { | |||
2631 | if (!QualStr.empty()) QualStr += ' '; | |||
2632 | QualStr += E.Name; | |||
2633 | ||||
2634 | // If we have a location for the qualifier, offer a fixit. | |||
2635 | SourceLocation QualLoc = E.Loc; | |||
2636 | if (QualLoc.isValid()) { | |||
2637 | FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); | |||
2638 | if (Loc.isInvalid() || | |||
2639 | getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) | |||
2640 | Loc = QualLoc; | |||
2641 | } | |||
2642 | ||||
2643 | ++NumQuals; | |||
2644 | } | |||
2645 | } | |||
2646 | ||||
2647 | Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) | |||
2648 | << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; | |||
2649 | } | |||
2650 | ||||
2651 | // Diagnose pointless type qualifiers on the return type of a function. | |||
2652 | static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, | |||
2653 | Declarator &D, | |||
2654 | unsigned FunctionChunkIndex) { | |||
2655 | if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { | |||
2656 | // FIXME: TypeSourceInfo doesn't preserve location information for | |||
2657 | // qualifiers. | |||
2658 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
2659 | RetTy.getLocalCVRQualifiers(), | |||
2660 | D.getIdentifierLoc()); | |||
2661 | return; | |||
2662 | } | |||
2663 | ||||
2664 | for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, | |||
2665 | End = D.getNumTypeObjects(); | |||
2666 | OuterChunkIndex != End; ++OuterChunkIndex) { | |||
2667 | DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); | |||
2668 | switch (OuterChunk.Kind) { | |||
2669 | case DeclaratorChunk::Paren: | |||
2670 | continue; | |||
2671 | ||||
2672 | case DeclaratorChunk::Pointer: { | |||
2673 | DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; | |||
2674 | S.diagnoseIgnoredQualifiers( | |||
2675 | diag::warn_qual_return_type, | |||
2676 | PTI.TypeQuals, | |||
2677 | SourceLocation(), | |||
2678 | SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), | |||
2679 | SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), | |||
2680 | SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), | |||
2681 | SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc), | |||
2682 | SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc)); | |||
2683 | return; | |||
2684 | } | |||
2685 | ||||
2686 | case DeclaratorChunk::Function: | |||
2687 | case DeclaratorChunk::BlockPointer: | |||
2688 | case DeclaratorChunk::Reference: | |||
2689 | case DeclaratorChunk::Array: | |||
2690 | case DeclaratorChunk::MemberPointer: | |||
2691 | case DeclaratorChunk::Pipe: | |||
2692 | // FIXME: We can't currently provide an accurate source location and a | |||
2693 | // fix-it hint for these. | |||
2694 | unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; | |||
2695 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
2696 | RetTy.getCVRQualifiers() | AtomicQual, | |||
2697 | D.getIdentifierLoc()); | |||
2698 | return; | |||
2699 | } | |||
2700 | ||||
2701 | llvm_unreachable("unknown declarator chunk kind")::llvm::llvm_unreachable_internal("unknown declarator chunk kind" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 2701); | |||
2702 | } | |||
2703 | ||||
2704 | // If the qualifiers come from a conversion function type, don't diagnose | |||
2705 | // them -- they're not necessarily redundant, since such a conversion | |||
2706 | // operator can be explicitly called as "x.operator const int()". | |||
2707 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | |||
2708 | return; | |||
2709 | ||||
2710 | // Just parens all the way out to the decl specifiers. Diagnose any qualifiers | |||
2711 | // which are present there. | |||
2712 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
2713 | D.getDeclSpec().getTypeQualifiers(), | |||
2714 | D.getIdentifierLoc(), | |||
2715 | D.getDeclSpec().getConstSpecLoc(), | |||
2716 | D.getDeclSpec().getVolatileSpecLoc(), | |||
2717 | D.getDeclSpec().getRestrictSpecLoc(), | |||
2718 | D.getDeclSpec().getAtomicSpecLoc(), | |||
2719 | D.getDeclSpec().getUnalignedSpecLoc()); | |||
2720 | } | |||
2721 | ||||
2722 | static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, | |||
2723 | TypeSourceInfo *&ReturnTypeInfo) { | |||
2724 | Sema &SemaRef = state.getSema(); | |||
2725 | Declarator &D = state.getDeclarator(); | |||
2726 | QualType T; | |||
2727 | ReturnTypeInfo = nullptr; | |||
2728 | ||||
2729 | // The TagDecl owned by the DeclSpec. | |||
2730 | TagDecl *OwnedTagDecl = nullptr; | |||
2731 | ||||
2732 | switch (D.getName().getKind()) { | |||
2733 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
2734 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
2735 | case UnqualifiedIdKind::IK_Identifier: | |||
2736 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
2737 | case UnqualifiedIdKind::IK_TemplateId: | |||
2738 | T = ConvertDeclSpecToType(state); | |||
2739 | ||||
2740 | if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { | |||
2741 | OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
2742 | // Owned declaration is embedded in declarator. | |||
2743 | OwnedTagDecl->setEmbeddedInDeclarator(true); | |||
2744 | } | |||
2745 | break; | |||
2746 | ||||
2747 | case UnqualifiedIdKind::IK_ConstructorName: | |||
2748 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
2749 | case UnqualifiedIdKind::IK_DestructorName: | |||
2750 | // Constructors and destructors don't have return types. Use | |||
2751 | // "void" instead. | |||
2752 | T = SemaRef.Context.VoidTy; | |||
2753 | processTypeAttrs(state, T, TAL_DeclSpec, | |||
2754 | D.getDeclSpec().getAttributes().getList()); | |||
2755 | break; | |||
2756 | ||||
2757 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
2758 | // Deduction guides have a trailing return type and no type in their | |||
2759 | // decl-specifier sequence. Use a placeholder return type for now. | |||
2760 | T = SemaRef.Context.DependentTy; | |||
2761 | break; | |||
2762 | ||||
2763 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
2764 | // The result type of a conversion function is the type that it | |||
2765 | // converts to. | |||
2766 | T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, | |||
2767 | &ReturnTypeInfo); | |||
2768 | break; | |||
2769 | } | |||
2770 | ||||
2771 | if (D.getAttributes()) | |||
2772 | distributeTypeAttrsFromDeclarator(state, T); | |||
2773 | ||||
2774 | // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. | |||
2775 | if (DeducedType *Deduced = T->getContainedDeducedType()) { | |||
2776 | AutoType *Auto = dyn_cast<AutoType>(Deduced); | |||
2777 | int Error = -1; | |||
2778 | ||||
2779 | // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or | |||
2780 | // class template argument deduction)? | |||
2781 | bool IsCXXAutoType = | |||
2782 | (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); | |||
2783 | ||||
2784 | switch (D.getContext()) { | |||
2785 | case DeclaratorContext::LambdaExprContext: | |||
2786 | // Declared return type of a lambda-declarator is implicit and is always | |||
2787 | // 'auto'. | |||
2788 | break; | |||
2789 | case DeclaratorContext::ObjCParameterContext: | |||
2790 | case DeclaratorContext::ObjCResultContext: | |||
2791 | case DeclaratorContext::PrototypeContext: | |||
2792 | Error = 0; | |||
2793 | break; | |||
2794 | case DeclaratorContext::LambdaExprParameterContext: | |||
2795 | // In C++14, generic lambdas allow 'auto' in their parameters. | |||
2796 | if (!SemaRef.getLangOpts().CPlusPlus14 || | |||
2797 | !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) | |||
2798 | Error = 16; | |||
2799 | else { | |||
2800 | // If auto is mentioned in a lambda parameter context, convert it to a | |||
2801 | // template parameter type. | |||
2802 | sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda(); | |||
2803 | assert(LSI && "No LambdaScopeInfo on the stack!")(static_cast <bool> (LSI && "No LambdaScopeInfo on the stack!" ) ? void (0) : __assert_fail ("LSI && \"No LambdaScopeInfo on the stack!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 2803, __extension__ __PRETTY_FUNCTION__)); | |||
2804 | const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth; | |||
2805 | const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size(); | |||
2806 | const bool IsParameterPack = D.hasEllipsis(); | |||
2807 | ||||
2808 | // Create the TemplateTypeParmDecl here to retrieve the corresponding | |||
2809 | // template parameter type. Template parameters are temporarily added | |||
2810 | // to the TU until the associated TemplateDecl is created. | |||
2811 | TemplateTypeParmDecl *CorrespondingTemplateParam = | |||
2812 | TemplateTypeParmDecl::Create( | |||
2813 | SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(), | |||
2814 | /*KeyLoc*/SourceLocation(), /*NameLoc*/D.getLocStart(), | |||
2815 | TemplateParameterDepth, AutoParameterPosition, | |||
2816 | /*Identifier*/nullptr, false, IsParameterPack); | |||
2817 | LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam); | |||
2818 | // Replace the 'auto' in the function parameter with this invented | |||
2819 | // template type parameter. | |||
2820 | // FIXME: Retain some type sugar to indicate that this was written | |||
2821 | // as 'auto'. | |||
2822 | T = SemaRef.ReplaceAutoType( | |||
2823 | T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0)); | |||
2824 | } | |||
2825 | break; | |||
2826 | case DeclaratorContext::MemberContext: { | |||
2827 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || | |||
2828 | D.isFunctionDeclarator()) | |||
2829 | break; | |||
2830 | bool Cxx = SemaRef.getLangOpts().CPlusPlus; | |||
2831 | switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { | |||
2832 | case TTK_Enum: llvm_unreachable("unhandled tag kind")::llvm::llvm_unreachable_internal("unhandled tag kind", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 2832); | |||
2833 | case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; | |||
2834 | case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; | |||
2835 | case TTK_Class: Error = 5; /* Class member */ break; | |||
2836 | case TTK_Interface: Error = 6; /* Interface member */ break; | |||
2837 | } | |||
2838 | if (D.getDeclSpec().isFriendSpecified()) | |||
2839 | Error = 20; // Friend type | |||
2840 | break; | |||
2841 | } | |||
2842 | case DeclaratorContext::CXXCatchContext: | |||
2843 | case DeclaratorContext::ObjCCatchContext: | |||
2844 | Error = 7; // Exception declaration | |||
2845 | break; | |||
2846 | case DeclaratorContext::TemplateParamContext: | |||
2847 | if (isa<DeducedTemplateSpecializationType>(Deduced)) | |||
2848 | Error = 19; // Template parameter | |||
2849 | else if (!SemaRef.getLangOpts().CPlusPlus17) | |||
2850 | Error = 8; // Template parameter (until C++17) | |||
2851 | break; | |||
2852 | case DeclaratorContext::BlockLiteralContext: | |||
2853 | Error = 9; // Block literal | |||
2854 | break; | |||
2855 | case DeclaratorContext::TemplateArgContext: | |||
2856 | // Within a template argument list, a deduced template specialization | |||
2857 | // type will be reinterpreted as a template template argument. | |||
2858 | if (isa<DeducedTemplateSpecializationType>(Deduced) && | |||
2859 | !D.getNumTypeObjects() && | |||
2860 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) | |||
2861 | break; | |||
2862 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
2863 | case DeclaratorContext::TemplateTypeArgContext: | |||
2864 | Error = 10; // Template type argument | |||
2865 | break; | |||
2866 | case DeclaratorContext::AliasDeclContext: | |||
2867 | case DeclaratorContext::AliasTemplateContext: | |||
2868 | Error = 12; // Type alias | |||
2869 | break; | |||
2870 | case DeclaratorContext::TrailingReturnContext: | |||
2871 | case DeclaratorContext::TrailingReturnVarContext: | |||
2872 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | |||
2873 | Error = 13; // Function return type | |||
2874 | break; | |||
2875 | case DeclaratorContext::ConversionIdContext: | |||
2876 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | |||
2877 | Error = 14; // conversion-type-id | |||
2878 | break; | |||
2879 | case DeclaratorContext::FunctionalCastContext: | |||
2880 | if (isa<DeducedTemplateSpecializationType>(Deduced)) | |||
2881 | break; | |||
2882 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
2883 | case DeclaratorContext::TypeNameContext: | |||
2884 | Error = 15; // Generic | |||
2885 | break; | |||
2886 | case DeclaratorContext::FileContext: | |||
2887 | case DeclaratorContext::BlockContext: | |||
2888 | case DeclaratorContext::ForContext: | |||
2889 | case DeclaratorContext::InitStmtContext: | |||
2890 | case DeclaratorContext::ConditionContext: | |||
2891 | // FIXME: P0091R3 (erroneously) does not permit class template argument | |||
2892 | // deduction in conditions, for-init-statements, and other declarations | |||
2893 | // that are not simple-declarations. | |||
2894 | break; | |||
2895 | case DeclaratorContext::CXXNewContext: | |||
2896 | // FIXME: P0091R3 does not permit class template argument deduction here, | |||
2897 | // but we follow GCC and allow it anyway. | |||
2898 | if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) | |||
2899 | Error = 17; // 'new' type | |||
2900 | break; | |||
2901 | case DeclaratorContext::KNRTypeListContext: | |||
2902 | Error = 18; // K&R function parameter | |||
2903 | break; | |||
2904 | } | |||
2905 | ||||
2906 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
2907 | Error = 11; | |||
2908 | ||||
2909 | // In Objective-C it is an error to use 'auto' on a function declarator | |||
2910 | // (and everywhere for '__auto_type'). | |||
2911 | if (D.isFunctionDeclarator() && | |||
2912 | (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) | |||
2913 | Error = 13; | |||
2914 | ||||
2915 | bool HaveTrailing = false; | |||
2916 | ||||
2917 | // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator | |||
2918 | // contains a trailing return type. That is only legal at the outermost | |||
2919 | // level. Check all declarator chunks (outermost first) anyway, to give | |||
2920 | // better diagnostics. | |||
2921 | // We don't support '__auto_type' with trailing return types. | |||
2922 | // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'? | |||
2923 | if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType && | |||
2924 | D.hasTrailingReturnType()) { | |||
2925 | HaveTrailing = true; | |||
2926 | Error = -1; | |||
2927 | } | |||
2928 | ||||
2929 | SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); | |||
2930 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | |||
2931 | AutoRange = D.getName().getSourceRange(); | |||
2932 | ||||
2933 | if (Error != -1) { | |||
2934 | unsigned Kind; | |||
2935 | if (Auto) { | |||
2936 | switch (Auto->getKeyword()) { | |||
2937 | case AutoTypeKeyword::Auto: Kind = 0; break; | |||
2938 | case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; | |||
2939 | case AutoTypeKeyword::GNUAutoType: Kind = 2; break; | |||
2940 | } | |||
2941 | } else { | |||
2942 | assert(isa<DeducedTemplateSpecializationType>(Deduced) &&(static_cast <bool> (isa<DeducedTemplateSpecializationType >(Deduced) && "unknown auto type") ? void (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 2943, __extension__ __PRETTY_FUNCTION__)) | |||
2943 | "unknown auto type")(static_cast <bool> (isa<DeducedTemplateSpecializationType >(Deduced) && "unknown auto type") ? void (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 2943, __extension__ __PRETTY_FUNCTION__)); | |||
2944 | Kind = 3; | |||
2945 | } | |||
2946 | ||||
2947 | auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); | |||
2948 | TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); | |||
2949 | ||||
2950 | SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) | |||
2951 | << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) | |||
2952 | << QualType(Deduced, 0) << AutoRange; | |||
2953 | if (auto *TD = TN.getAsTemplateDecl()) | |||
2954 | SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here); | |||
2955 | ||||
2956 | T = SemaRef.Context.IntTy; | |||
2957 | D.setInvalidType(true); | |||
2958 | } else if (!HaveTrailing) { | |||
2959 | // If there was a trailing return type, we already got | |||
2960 | // warn_cxx98_compat_trailing_return_type in the parser. | |||
2961 | SemaRef.Diag(AutoRange.getBegin(), | |||
2962 | diag::warn_cxx98_compat_auto_type_specifier) | |||
2963 | << AutoRange; | |||
2964 | } | |||
2965 | } | |||
2966 | ||||
2967 | if (SemaRef.getLangOpts().CPlusPlus && | |||
2968 | OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { | |||
2969 | // Check the contexts where C++ forbids the declaration of a new class | |||
2970 | // or enumeration in a type-specifier-seq. | |||
2971 | unsigned DiagID = 0; | |||
2972 | switch (D.getContext()) { | |||
2973 | case DeclaratorContext::TrailingReturnContext: | |||
2974 | case DeclaratorContext::TrailingReturnVarContext: | |||
2975 | // Class and enumeration definitions are syntactically not allowed in | |||
2976 | // trailing return types. | |||
2977 | llvm_unreachable("parser should not have allowed this")::llvm::llvm_unreachable_internal("parser should not have allowed this" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 2977); | |||
2978 | break; | |||
2979 | case DeclaratorContext::FileContext: | |||
2980 | case DeclaratorContext::MemberContext: | |||
2981 | case DeclaratorContext::BlockContext: | |||
2982 | case DeclaratorContext::ForContext: | |||
2983 | case DeclaratorContext::InitStmtContext: | |||
2984 | case DeclaratorContext::BlockLiteralContext: | |||
2985 | case DeclaratorContext::LambdaExprContext: | |||
2986 | // C++11 [dcl.type]p3: | |||
2987 | // A type-specifier-seq shall not define a class or enumeration unless | |||
2988 | // it appears in the type-id of an alias-declaration (7.1.3) that is not | |||
2989 | // the declaration of a template-declaration. | |||
2990 | case DeclaratorContext::AliasDeclContext: | |||
2991 | break; | |||
2992 | case DeclaratorContext::AliasTemplateContext: | |||
2993 | DiagID = diag::err_type_defined_in_alias_template; | |||
2994 | break; | |||
2995 | case DeclaratorContext::TypeNameContext: | |||
2996 | case DeclaratorContext::FunctionalCastContext: | |||
2997 | case DeclaratorContext::ConversionIdContext: | |||
2998 | case DeclaratorContext::TemplateParamContext: | |||
2999 | case DeclaratorContext::CXXNewContext: | |||
3000 | case DeclaratorContext::CXXCatchContext: | |||
3001 | case DeclaratorContext::ObjCCatchContext: | |||
3002 | case DeclaratorContext::TemplateArgContext: | |||
3003 | case DeclaratorContext::TemplateTypeArgContext: | |||
3004 | DiagID = diag::err_type_defined_in_type_specifier; | |||
3005 | break; | |||
3006 | case DeclaratorContext::PrototypeContext: | |||
3007 | case DeclaratorContext::LambdaExprParameterContext: | |||
3008 | case DeclaratorContext::ObjCParameterContext: | |||
3009 | case DeclaratorContext::ObjCResultContext: | |||
3010 | case DeclaratorContext::KNRTypeListContext: | |||
3011 | // C++ [dcl.fct]p6: | |||
3012 | // Types shall not be defined in return or parameter types. | |||
3013 | DiagID = diag::err_type_defined_in_param_type; | |||
3014 | break; | |||
3015 | case DeclaratorContext::ConditionContext: | |||
3016 | // C++ 6.4p2: | |||
3017 | // The type-specifier-seq shall not contain typedef and shall not declare | |||
3018 | // a new class or enumeration. | |||
3019 | DiagID = diag::err_type_defined_in_condition; | |||
3020 | break; | |||
3021 | } | |||
3022 | ||||
3023 | if (DiagID != 0) { | |||
3024 | SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) | |||
3025 | << SemaRef.Context.getTypeDeclType(OwnedTagDecl); | |||
3026 | D.setInvalidType(true); | |||
3027 | } | |||
3028 | } | |||
3029 | ||||
3030 | assert(!T.isNull() && "This function should not return a null type")(static_cast <bool> (!T.isNull() && "This function should not return a null type" ) ? void (0) : __assert_fail ("!T.isNull() && \"This function should not return a null type\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 3030, __extension__ __PRETTY_FUNCTION__)); | |||
3031 | return T; | |||
3032 | } | |||
3033 | ||||
3034 | /// Produce an appropriate diagnostic for an ambiguity between a function | |||
3035 | /// declarator and a C++ direct-initializer. | |||
3036 | static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, | |||
3037 | DeclaratorChunk &DeclType, QualType RT) { | |||
3038 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
3039 | assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity")(static_cast <bool> (FTI.isAmbiguous && "no direct-initializer / function ambiguity" ) ? void (0) : __assert_fail ("FTI.isAmbiguous && \"no direct-initializer / function ambiguity\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 3039, __extension__ __PRETTY_FUNCTION__)); | |||
3040 | ||||
3041 | // If the return type is void there is no ambiguity. | |||
3042 | if (RT->isVoidType()) | |||
3043 | return; | |||
3044 | ||||
3045 | // An initializer for a non-class type can have at most one argument. | |||
3046 | if (!RT->isRecordType() && FTI.NumParams > 1) | |||
3047 | return; | |||
3048 | ||||
3049 | // An initializer for a reference must have exactly one argument. | |||
3050 | if (RT->isReferenceType() && FTI.NumParams != 1) | |||
3051 | return; | |||
3052 | ||||
3053 | // Only warn if this declarator is declaring a function at block scope, and | |||
3054 | // doesn't have a storage class (such as 'extern') specified. | |||
3055 | if (!D.isFunctionDeclarator() || | |||
3056 | D.getFunctionDefinitionKind() != FDK_Declaration || | |||
3057 | !S.CurContext->isFunctionOrMethod() || | |||
3058 | D.getDeclSpec().getStorageClassSpec() | |||
3059 | != DeclSpec::SCS_unspecified) | |||
3060 | return; | |||
3061 | ||||
3062 | // Inside a condition, a direct initializer is not permitted. We allow one to | |||
3063 | // be parsed in order to give better diagnostics in condition parsing. | |||
3064 | if (D.getContext() == DeclaratorContext::ConditionContext) | |||
3065 | return; | |||
3066 | ||||
3067 | SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); | |||
3068 | ||||
3069 | S.Diag(DeclType.Loc, | |||
3070 | FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration | |||
3071 | : diag::warn_empty_parens_are_function_decl) | |||
3072 | << ParenRange; | |||
3073 | ||||
3074 | // If the declaration looks like: | |||
3075 | // T var1, | |||
3076 | // f(); | |||
3077 | // and name lookup finds a function named 'f', then the ',' was | |||
3078 | // probably intended to be a ';'. | |||
3079 | if (!D.isFirstDeclarator() && D.getIdentifier()) { | |||
3080 | FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); | |||
3081 | FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); | |||
3082 | if (Comma.getFileID() != Name.getFileID() || | |||
3083 | Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { | |||
3084 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | |||
3085 | Sema::LookupOrdinaryName); | |||
3086 | if (S.LookupName(Result, S.getCurScope())) | |||
3087 | S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) | |||
3088 | << FixItHint::CreateReplacement(D.getCommaLoc(), ";") | |||
3089 | << D.getIdentifier(); | |||
3090 | Result.suppressDiagnostics(); | |||
3091 | } | |||
3092 | } | |||
3093 | ||||
3094 | if (FTI.NumParams > 0) { | |||
3095 | // For a declaration with parameters, eg. "T var(T());", suggest adding | |||
3096 | // parens around the first parameter to turn the declaration into a | |||
3097 | // variable declaration. | |||
3098 | SourceRange Range = FTI.Params[0].Param->getSourceRange(); | |||
3099 | SourceLocation B = Range.getBegin(); | |||
3100 | SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); | |||
3101 | // FIXME: Maybe we should suggest adding braces instead of parens | |||
3102 | // in C++11 for classes that don't have an initializer_list constructor. | |||
3103 | S.Diag(B, diag::note_additional_parens_for_variable_declaration) | |||
3104 | << FixItHint::CreateInsertion(B, "(") | |||
3105 | << FixItHint::CreateInsertion(E, ")"); | |||
3106 | } else { | |||
3107 | // For a declaration without parameters, eg. "T var();", suggest replacing | |||
3108 | // the parens with an initializer to turn the declaration into a variable | |||
3109 | // declaration. | |||
3110 | const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); | |||
3111 | ||||
3112 | // Empty parens mean value-initialization, and no parens mean | |||
3113 | // default initialization. These are equivalent if the default | |||
3114 | // constructor is user-provided or if zero-initialization is a | |||
3115 | // no-op. | |||
3116 | if (RD && RD->hasDefinition() && | |||
3117 | (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) | |||
3118 | S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) | |||
3119 | << FixItHint::CreateRemoval(ParenRange); | |||
3120 | else { | |||
3121 | std::string Init = | |||
3122 | S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); | |||
3123 | if (Init.empty() && S.LangOpts.CPlusPlus11) | |||
3124 | Init = "{}"; | |||
3125 | if (!Init.empty()) | |||
3126 | S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) | |||
3127 | << FixItHint::CreateReplacement(ParenRange, Init); | |||
3128 | } | |||
3129 | } | |||
3130 | } | |||
3131 | ||||
3132 | /// Produce an appropriate diagnostic for a declarator with top-level | |||
3133 | /// parentheses. | |||
3134 | static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { | |||
3135 | DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); | |||
3136 | assert(Paren.Kind == DeclaratorChunk::Paren &&(static_cast <bool> (Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses") ? void (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 3137, __extension__ __PRETTY_FUNCTION__)) | |||
3137 | "do not have redundant top-level parentheses")(static_cast <bool> (Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses") ? void (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 3137, __extension__ __PRETTY_FUNCTION__)); | |||
3138 | ||||
3139 | // This is a syntactic check; we're not interested in cases that arise | |||
3140 | // during template instantiation. | |||
3141 | if (S.inTemplateInstantiation()) | |||
3142 | return; | |||
3143 | ||||
3144 | // Check whether this could be intended to be a construction of a temporary | |||
3145 | // object in C++ via a function-style cast. | |||
3146 | bool CouldBeTemporaryObject = | |||
3147 | S.getLangOpts().CPlusPlus && D.isExpressionContext() && | |||
3148 | !D.isInvalidType() && D.getIdentifier() && | |||
3149 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && | |||
3150 | (T->isRecordType() || T->isDependentType()) && | |||
3151 | D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); | |||
3152 | ||||
3153 | bool StartsWithDeclaratorId = true; | |||
3154 | for (auto &C : D.type_objects()) { | |||
3155 | switch (C.Kind) { | |||
3156 | case DeclaratorChunk::Paren: | |||
3157 | if (&C == &Paren) | |||
3158 | continue; | |||
3159 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
3160 | case DeclaratorChunk::Pointer: | |||
3161 | StartsWithDeclaratorId = false; | |||
3162 | continue; | |||
3163 | ||||
3164 | case DeclaratorChunk::Array: | |||
3165 | if (!C.Arr.NumElts) | |||
3166 | CouldBeTemporaryObject = false; | |||
3167 | continue; | |||
3168 | ||||
3169 | case DeclaratorChunk::Reference: | |||
3170 | // FIXME: Suppress the warning here if there is no initializer; we're | |||
3171 | // going to give an error anyway. | |||
3172 | // We assume that something like 'T (&x) = y;' is highly likely to not | |||
3173 | // be intended to be a temporary object. | |||
3174 | CouldBeTemporaryObject = false; | |||
3175 | StartsWithDeclaratorId = false; | |||
3176 | continue; | |||
3177 | ||||
3178 | case DeclaratorChunk::Function: | |||
3179 | // In a new-type-id, function chunks require parentheses. | |||
3180 | if (D.getContext() == DeclaratorContext::CXXNewContext) | |||
3181 | return; | |||
3182 | // FIXME: "A(f())" deserves a vexing-parse warning, not just a | |||
3183 | // redundant-parens warning, but we don't know whether the function | |||
3184 | // chunk was syntactically valid as an expression here. | |||
3185 | CouldBeTemporaryObject = false; | |||
3186 | continue; | |||
3187 | ||||
3188 | case DeclaratorChunk::BlockPointer: | |||
3189 | case DeclaratorChunk::MemberPointer: | |||
3190 | case DeclaratorChunk::Pipe: | |||
3191 | // These cannot appear in expressions. | |||
3192 | CouldBeTemporaryObject = false; | |||
3193 | StartsWithDeclaratorId = false; | |||
3194 | continue; | |||
3195 | } | |||
3196 | } | |||
3197 | ||||
3198 | // FIXME: If there is an initializer, assume that this is not intended to be | |||
3199 | // a construction of a temporary object. | |||
3200 | ||||
3201 | // Check whether the name has already been declared; if not, this is not a | |||
3202 | // function-style cast. | |||
3203 | if (CouldBeTemporaryObject) { | |||
3204 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | |||
3205 | Sema::LookupOrdinaryName); | |||
3206 | if (!S.LookupName(Result, S.getCurScope())) | |||
3207 | CouldBeTemporaryObject = false; | |||
3208 | Result.suppressDiagnostics(); | |||
3209 | } | |||
3210 | ||||
3211 | SourceRange ParenRange(Paren.Loc, Paren.EndLoc); | |||
3212 | ||||
3213 | if (!CouldBeTemporaryObject) { | |||
3214 | // If we have A (::B), the parentheses affect the meaning of the program. | |||
3215 | // Suppress the warning in that case. Don't bother looking at the DeclSpec | |||
3216 | // here: even (e.g.) "int ::x" is visually ambiguous even though it's | |||
3217 | // formally unambiguous. | |||
3218 | if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { | |||
3219 | for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; | |||
3220 | NNS = NNS->getPrefix()) { | |||
3221 | if (NNS->getKind() == NestedNameSpecifier::Global) | |||
3222 | return; | |||
3223 | } | |||
3224 | } | |||
3225 | ||||
3226 | S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) | |||
3227 | << ParenRange << FixItHint::CreateRemoval(Paren.Loc) | |||
3228 | << FixItHint::CreateRemoval(Paren.EndLoc); | |||
3229 | return; | |||
3230 | } | |||
3231 | ||||
3232 | S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) | |||
3233 | << ParenRange << D.getIdentifier(); | |||
3234 | auto *RD = T->getAsCXXRecordDecl(); | |||
3235 | if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) | |||
3236 | S.Diag(Paren.Loc, diag::note_raii_guard_add_name) | |||
3237 | << FixItHint::CreateInsertion(Paren.Loc, " varname") << T | |||
3238 | << D.getIdentifier(); | |||
3239 | // FIXME: A cast to void is probably a better suggestion in cases where it's | |||
3240 | // valid (when there is no initializer and we're not in a condition). | |||
3241 | S.Diag(D.getLocStart(), diag::note_function_style_cast_add_parentheses) | |||
3242 | << FixItHint::CreateInsertion(D.getLocStart(), "(") | |||
3243 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getLocEnd()), ")"); | |||
3244 | S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) | |||
3245 | << FixItHint::CreateRemoval(Paren.Loc) | |||
3246 | << FixItHint::CreateRemoval(Paren.EndLoc); | |||
3247 | } | |||
3248 | ||||
3249 | /// Helper for figuring out the default CC for a function declarator type. If | |||
3250 | /// this is the outermost chunk, then we can determine the CC from the | |||
3251 | /// declarator context. If not, then this could be either a member function | |||
3252 | /// type or normal function type. | |||
3253 | static CallingConv | |||
3254 | getCCForDeclaratorChunk(Sema &S, Declarator &D, | |||
3255 | const DeclaratorChunk::FunctionTypeInfo &FTI, | |||
3256 | unsigned ChunkIndex) { | |||
3257 | assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function)(static_cast <bool> (D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function) ? void (0) : __assert_fail ("D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 3257, __extension__ __PRETTY_FUNCTION__)); | |||
3258 | ||||
3259 | // Check for an explicit CC attribute. | |||
3260 | for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) { | |||
3261 | switch (Attr->getKind()) { | |||
3262 | CALLING_CONV_ATTRS_CASELISTcase AttributeList::AT_CDecl: case AttributeList::AT_FastCall : case AttributeList::AT_StdCall: case AttributeList::AT_ThisCall : case AttributeList::AT_RegCall: case AttributeList::AT_Pascal : case AttributeList::AT_SwiftCall: case AttributeList::AT_VectorCall : case AttributeList::AT_MSABI: case AttributeList::AT_SysVABI : case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc : case AttributeList::AT_PreserveMost: case AttributeList::AT_PreserveAll: { | |||
3263 | // Ignore attributes that don't validate or can't apply to the | |||
3264 | // function type. We'll diagnose the failure to apply them in | |||
3265 | // handleFunctionTypeAttr. | |||
3266 | CallingConv CC; | |||
3267 | if (!S.CheckCallingConvAttr(*Attr, CC) && | |||
3268 | (!FTI.isVariadic || supportsVariadicCall(CC))) { | |||
3269 | return CC; | |||
3270 | } | |||
3271 | break; | |||
3272 | } | |||
3273 | ||||
3274 | default: | |||
3275 | break; | |||
3276 | } | |||
3277 | } | |||
3278 | ||||
3279 | bool IsCXXInstanceMethod = false; | |||
3280 | ||||
3281 | if (S.getLangOpts().CPlusPlus) { | |||
3282 | // Look inwards through parentheses to see if this chunk will form a | |||
3283 | // member pointer type or if we're the declarator. Any type attributes | |||
3284 | // between here and there will override the CC we choose here. | |||
3285 | unsigned I = ChunkIndex; | |||
3286 | bool FoundNonParen = false; | |||
3287 | while (I && !FoundNonParen) { | |||
3288 | --I; | |||
3289 | if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) | |||
3290 | FoundNonParen = true; | |||
3291 | } | |||
3292 | ||||
3293 | if (FoundNonParen) { | |||
3294 | // If we're not the declarator, we're a regular function type unless we're | |||
3295 | // in a member pointer. | |||
3296 | IsCXXInstanceMethod = | |||
3297 | D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; | |||
3298 | } else if (D.getContext() == DeclaratorContext::LambdaExprContext) { | |||
3299 | // This can only be a call operator for a lambda, which is an instance | |||
3300 | // method. | |||
3301 | IsCXXInstanceMethod = true; | |||
3302 | } else { | |||
3303 | // We're the innermost decl chunk, so must be a function declarator. | |||
3304 | assert(D.isFunctionDeclarator())(static_cast <bool> (D.isFunctionDeclarator()) ? void ( 0) : __assert_fail ("D.isFunctionDeclarator()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 3304, __extension__ __PRETTY_FUNCTION__)); | |||
3305 | ||||
3306 | // If we're inside a record, we're declaring a method, but it could be | |||
3307 | // explicitly or implicitly static. | |||
3308 | IsCXXInstanceMethod = | |||
3309 | D.isFirstDeclarationOfMember() && | |||
3310 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | |||
3311 | !D.isStaticMember(); | |||
3312 | } | |||
3313 | } | |||
3314 | ||||
3315 | CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, | |||
3316 | IsCXXInstanceMethod); | |||
3317 | ||||
3318 | // Attribute AT_OpenCLKernel affects the calling convention for SPIR | |||
3319 | // and AMDGPU targets, hence it cannot be treated as a calling | |||
3320 | // convention attribute. This is the simplest place to infer | |||
3321 | // calling convention for OpenCL kernels. | |||
3322 | if (S.getLangOpts().OpenCL) { | |||
3323 | for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList(); | |||
3324 | Attr; Attr = Attr->getNext()) { | |||
3325 | if (Attr->getKind() == AttributeList::AT_OpenCLKernel) { | |||
3326 | CC = CC_OpenCLKernel; | |||
3327 | break; | |||
3328 | } | |||
3329 | } | |||
3330 | } | |||
3331 | ||||
3332 | return CC; | |||
3333 | } | |||
3334 | ||||
3335 | namespace { | |||
3336 | /// A simple notion of pointer kinds, which matches up with the various | |||
3337 | /// pointer declarators. | |||
3338 | enum class SimplePointerKind { | |||
3339 | Pointer, | |||
3340 | BlockPointer, | |||
3341 | MemberPointer, | |||
3342 | Array, | |||
3343 | }; | |||
3344 | } // end anonymous namespace | |||
3345 | ||||
3346 | IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { | |||
3347 | switch (nullability) { | |||
3348 | case NullabilityKind::NonNull: | |||
3349 | if (!Ident__Nonnull) | |||
3350 | Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); | |||
3351 | return Ident__Nonnull; | |||
3352 | ||||
3353 | case NullabilityKind::Nullable: | |||
3354 | if (!Ident__Nullable) | |||
3355 | Ident__Nullable = PP.getIdentifierInfo("_Nullable"); | |||
3356 | return Ident__Nullable; | |||
3357 | ||||
3358 | case NullabilityKind::Unspecified: | |||
3359 | if (!Ident__Null_unspecified) | |||
3360 | Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); | |||
3361 | return Ident__Null_unspecified; | |||
3362 | } | |||
3363 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 3363); | |||
3364 | } | |||
3365 | ||||
3366 | /// Retrieve the identifier "NSError". | |||
3367 | IdentifierInfo *Sema::getNSErrorIdent() { | |||
3368 | if (!Ident_NSError) | |||
3369 | Ident_NSError = PP.getIdentifierInfo("NSError"); | |||
3370 | ||||
3371 | return Ident_NSError; | |||
3372 | } | |||
3373 | ||||
3374 | /// Check whether there is a nullability attribute of any kind in the given | |||
3375 | /// attribute list. | |||
3376 | static bool hasNullabilityAttr(const AttributeList *attrs) { | |||
3377 | for (const AttributeList *attr = attrs; attr; | |||
3378 | attr = attr->getNext()) { | |||
3379 | if (attr->getKind() == AttributeList::AT_TypeNonNull || | |||
3380 | attr->getKind() == AttributeList::AT_TypeNullable || | |||
3381 | attr->getKind() == AttributeList::AT_TypeNullUnspecified) | |||
3382 | return true; | |||
3383 | } | |||
3384 | ||||
3385 | return false; | |||
3386 | } | |||
3387 | ||||
3388 | namespace { | |||
3389 | /// Describes the kind of a pointer a declarator describes. | |||
3390 | enum class PointerDeclaratorKind { | |||
3391 | // Not a pointer. | |||
3392 | NonPointer, | |||
3393 | // Single-level pointer. | |||
3394 | SingleLevelPointer, | |||
3395 | // Multi-level pointer (of any pointer kind). | |||
3396 | MultiLevelPointer, | |||
3397 | // CFFooRef* | |||
3398 | MaybePointerToCFRef, | |||
3399 | // CFErrorRef* | |||
3400 | CFErrorRefPointer, | |||
3401 | // NSError** | |||
3402 | NSErrorPointerPointer, | |||
3403 | }; | |||
3404 | ||||
3405 | /// Describes a declarator chunk wrapping a pointer that marks inference as | |||
3406 | /// unexpected. | |||
3407 | // These values must be kept in sync with diagnostics. | |||
3408 | enum class PointerWrappingDeclaratorKind { | |||
3409 | /// Pointer is top-level. | |||
3410 | None = -1, | |||
3411 | /// Pointer is an array element. | |||
3412 | Array = 0, | |||
3413 | /// Pointer is the referent type of a C++ reference. | |||
3414 | Reference = 1 | |||
3415 | }; | |||
3416 | } // end anonymous namespace | |||
3417 | ||||
3418 | /// Classify the given declarator, whose type-specified is \c type, based on | |||
3419 | /// what kind of pointer it refers to. | |||
3420 | /// | |||
3421 | /// This is used to determine the default nullability. | |||
3422 | static PointerDeclaratorKind | |||
3423 | classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, | |||
3424 | PointerWrappingDeclaratorKind &wrappingKind) { | |||
3425 | unsigned numNormalPointers = 0; | |||
3426 | ||||
3427 | // For any dependent type, we consider it a non-pointer. | |||
3428 | if (type->isDependentType()) | |||
3429 | return PointerDeclaratorKind::NonPointer; | |||
3430 | ||||
3431 | // Look through the declarator chunks to identify pointers. | |||
3432 | for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { | |||
3433 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
3434 | switch (chunk.Kind) { | |||
3435 | case DeclaratorChunk::Array: | |||
3436 | if (numNormalPointers == 0) | |||
3437 | wrappingKind = PointerWrappingDeclaratorKind::Array; | |||
3438 | break; | |||
3439 | ||||
3440 | case DeclaratorChunk::Function: | |||
3441 | case DeclaratorChunk::Pipe: | |||
3442 | break; | |||
3443 | ||||
3444 | case DeclaratorChunk::BlockPointer: | |||
3445 | case DeclaratorChunk::MemberPointer: | |||
3446 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
3447 | : PointerDeclaratorKind::SingleLevelPointer; | |||
3448 | ||||
3449 | case DeclaratorChunk::Paren: | |||
3450 | break; | |||
3451 | ||||
3452 | case DeclaratorChunk::Reference: | |||
3453 | if (numNormalPointers == 0) | |||
3454 | wrappingKind = PointerWrappingDeclaratorKind::Reference; | |||
3455 | break; | |||
3456 | ||||
3457 | case DeclaratorChunk::Pointer: | |||
3458 | ++numNormalPointers; | |||
3459 | if (numNormalPointers > 2) | |||
3460 | return PointerDeclaratorKind::MultiLevelPointer; | |||
3461 | break; | |||
3462 | } | |||
3463 | } | |||
3464 | ||||
3465 | // Then, dig into the type specifier itself. | |||
3466 | unsigned numTypeSpecifierPointers = 0; | |||
3467 | do { | |||
3468 | // Decompose normal pointers. | |||
3469 | if (auto ptrType = type->getAs<PointerType>()) { | |||
3470 | ++numNormalPointers; | |||
3471 | ||||
3472 | if (numNormalPointers > 2) | |||
3473 | return PointerDeclaratorKind::MultiLevelPointer; | |||
3474 | ||||
3475 | type = ptrType->getPointeeType(); | |||
3476 | ++numTypeSpecifierPointers; | |||
3477 | continue; | |||
3478 | } | |||
3479 | ||||
3480 | // Decompose block pointers. | |||
3481 | if (type->getAs<BlockPointerType>()) { | |||
3482 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
3483 | : PointerDeclaratorKind::SingleLevelPointer; | |||
3484 | } | |||
3485 | ||||
3486 | // Decompose member pointers. | |||
3487 | if (type->getAs<MemberPointerType>()) { | |||
3488 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
3489 | : PointerDeclaratorKind::SingleLevelPointer; | |||
3490 | } | |||
3491 | ||||
3492 | // Look at Objective-C object pointers. | |||
3493 | if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { | |||
3494 | ++numNormalPointers; | |||
3495 | ++numTypeSpecifierPointers; | |||
3496 | ||||
3497 | // If this is NSError**, report that. | |||
3498 | if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { | |||
3499 | if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && | |||
3500 | numNormalPointers == 2 && numTypeSpecifierPointers < 2) { | |||
3501 | return PointerDeclaratorKind::NSErrorPointerPointer; | |||
3502 | } | |||
3503 | } | |||
3504 | ||||
3505 | break; | |||
3506 | } | |||
3507 | ||||
3508 | // Look at Objective-C class types. | |||
3509 | if (auto objcClass = type->getAs<ObjCInterfaceType>()) { | |||
3510 | if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { | |||
3511 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) | |||
3512 | return PointerDeclaratorKind::NSErrorPointerPointer; | |||
3513 | } | |||
3514 | ||||
3515 | break; | |||
3516 | } | |||
3517 | ||||
3518 | // If at this point we haven't seen a pointer, we won't see one. | |||
3519 | if (numNormalPointers == 0) | |||
3520 | return PointerDeclaratorKind::NonPointer; | |||
3521 | ||||
3522 | if (auto recordType = type->getAs<RecordType>()) { | |||
3523 | RecordDecl *recordDecl = recordType->getDecl(); | |||
3524 | ||||
3525 | bool isCFError = false; | |||
3526 | if (S.CFError) { | |||
3527 | // If we already know about CFError, test it directly. | |||
3528 | isCFError = (S.CFError == recordDecl); | |||
3529 | } else { | |||
3530 | // Check whether this is CFError, which we identify based on its bridge | |||
3531 | // to NSError. CFErrorRef used to be declared with "objc_bridge" but is | |||
3532 | // now declared with "objc_bridge_mutable", so look for either one of | |||
3533 | // the two attributes. | |||
3534 | if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) { | |||
3535 | IdentifierInfo *bridgedType = nullptr; | |||
3536 | if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) | |||
3537 | bridgedType = bridgeAttr->getBridgedType(); | |||
3538 | else if (auto bridgeAttr = | |||
3539 | recordDecl->getAttr<ObjCBridgeMutableAttr>()) | |||
3540 | bridgedType = bridgeAttr->getBridgedType(); | |||
3541 | ||||
3542 | if (bridgedType == S.getNSErrorIdent()) { | |||
3543 | S.CFError = recordDecl; | |||
3544 | isCFError = true; | |||
3545 | } | |||
3546 | } | |||
3547 | } | |||
3548 | ||||
3549 | // If this is CFErrorRef*, report it as such. | |||
3550 | if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) { | |||
3551 | return PointerDeclaratorKind::CFErrorRefPointer; | |||
3552 | } | |||
3553 | break; | |||
3554 | } | |||
3555 | ||||
3556 | break; | |||
3557 | } while (true); | |||
3558 | ||||
3559 | switch (numNormalPointers) { | |||
3560 | case 0: | |||
3561 | return PointerDeclaratorKind::NonPointer; | |||
3562 | ||||
3563 | case 1: | |||
3564 | return PointerDeclaratorKind::SingleLevelPointer; | |||
3565 | ||||
3566 | case 2: | |||
3567 | return PointerDeclaratorKind::MaybePointerToCFRef; | |||
3568 | ||||
3569 | default: | |||
3570 | return PointerDeclaratorKind::MultiLevelPointer; | |||
3571 | } | |||
3572 | } | |||
3573 | ||||
3574 | static FileID getNullabilityCompletenessCheckFileID(Sema &S, | |||
3575 | SourceLocation loc) { | |||
3576 | // If we're anywhere in a function, method, or closure context, don't perform | |||
3577 | // completeness checks. | |||
3578 | for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { | |||
3579 | if (ctx->isFunctionOrMethod()) | |||
3580 | return FileID(); | |||
3581 | ||||
3582 | if (ctx->isFileContext()) | |||
3583 | break; | |||
3584 | } | |||
3585 | ||||
3586 | // We only care about the expansion location. | |||
3587 | loc = S.SourceMgr.getExpansionLoc(loc); | |||
3588 | FileID file = S.SourceMgr.getFileID(loc); | |||
3589 | if (file.isInvalid()) | |||
3590 | return FileID(); | |||
3591 | ||||
3592 | // Retrieve file information. | |||
3593 | bool invalid = false; | |||
3594 | const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); | |||
3595 | if (invalid || !sloc.isFile()) | |||
3596 | return FileID(); | |||
3597 | ||||
3598 | // We don't want to perform completeness checks on the main file or in | |||
3599 | // system headers. | |||
3600 | const SrcMgr::FileInfo &fileInfo = sloc.getFile(); | |||
3601 | if (fileInfo.getIncludeLoc().isInvalid()) | |||
3602 | return FileID(); | |||
3603 | if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && | |||
3604 | S.Diags.getSuppressSystemWarnings()) { | |||
3605 | return FileID(); | |||
3606 | } | |||
3607 | ||||
3608 | return file; | |||
3609 | } | |||
3610 | ||||
3611 | /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, | |||
3612 | /// taking into account whitespace before and after. | |||
3613 | static void fixItNullability(Sema &S, DiagnosticBuilder &Diag, | |||
3614 | SourceLocation PointerLoc, | |||
3615 | NullabilityKind Nullability) { | |||
3616 | assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) : __assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 3616, __extension__ __PRETTY_FUNCTION__)); | |||
3617 | if (PointerLoc.isMacroID()) | |||
3618 | return; | |||
3619 | ||||
3620 | SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); | |||
3621 | if (!FixItLoc.isValid() || FixItLoc == PointerLoc) | |||
3622 | return; | |||
3623 | ||||
3624 | const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); | |||
3625 | if (!NextChar) | |||
3626 | return; | |||
3627 | ||||
3628 | SmallString<32> InsertionTextBuf{" "}; | |||
3629 | InsertionTextBuf += getNullabilitySpelling(Nullability); | |||
3630 | InsertionTextBuf += " "; | |||
3631 | StringRef InsertionText = InsertionTextBuf.str(); | |||
3632 | ||||
3633 | if (isWhitespace(*NextChar)) { | |||
3634 | InsertionText = InsertionText.drop_back(); | |||
3635 | } else if (NextChar[-1] == '[') { | |||
3636 | if (NextChar[0] == ']') | |||
3637 | InsertionText = InsertionText.drop_back().drop_front(); | |||
3638 | else | |||
3639 | InsertionText = InsertionText.drop_front(); | |||
3640 | } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) && | |||
3641 | !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) { | |||
3642 | InsertionText = InsertionText.drop_back().drop_front(); | |||
3643 | } | |||
3644 | ||||
3645 | Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); | |||
3646 | } | |||
3647 | ||||
3648 | static void emitNullabilityConsistencyWarning(Sema &S, | |||
3649 | SimplePointerKind PointerKind, | |||
3650 | SourceLocation PointerLoc, | |||
3651 | SourceLocation PointerEndLoc) { | |||
3652 | assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) : __assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 3652, __extension__ __PRETTY_FUNCTION__)); | |||
3653 | ||||
3654 | if (PointerKind == SimplePointerKind::Array) { | |||
3655 | S.Diag(PointerLoc, diag::warn_nullability_missing_array); | |||
3656 | } else { | |||
3657 | S.Diag(PointerLoc, diag::warn_nullability_missing) | |||
3658 | << static_cast<unsigned>(PointerKind); | |||
3659 | } | |||
3660 | ||||
3661 | auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; | |||
3662 | if (FixItLoc.isMacroID()) | |||
3663 | return; | |||
3664 | ||||
3665 | auto addFixIt = [&](NullabilityKind Nullability) { | |||
3666 | auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); | |||
3667 | Diag << static_cast<unsigned>(Nullability); | |||
3668 | Diag << static_cast<unsigned>(PointerKind); | |||
3669 | fixItNullability(S, Diag, FixItLoc, Nullability); | |||
3670 | }; | |||
3671 | addFixIt(NullabilityKind::Nullable); | |||
3672 | addFixIt(NullabilityKind::NonNull); | |||
3673 | } | |||
3674 | ||||
3675 | /// Complains about missing nullability if the file containing \p pointerLoc | |||
3676 | /// has other uses of nullability (either the keywords or the \c assume_nonnull | |||
3677 | /// pragma). | |||
3678 | /// | |||
3679 | /// If the file has \e not seen other uses of nullability, this particular | |||
3680 | /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). | |||
3681 | static void | |||
3682 | checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, | |||
3683 | SourceLocation pointerLoc, | |||
3684 | SourceLocation pointerEndLoc = SourceLocation()) { | |||
3685 | // Determine which file we're performing consistency checking for. | |||
3686 | FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); | |||
3687 | if (file.isInvalid()) | |||
3688 | return; | |||
3689 | ||||
3690 | // If we haven't seen any type nullability in this file, we won't warn now | |||
3691 | // about anything. | |||
3692 | FileNullability &fileNullability = S.NullabilityMap[file]; | |||
3693 | if (!fileNullability.SawTypeNullability) { | |||
3694 | // If this is the first pointer declarator in the file, and the appropriate | |||
3695 | // warning is on, record it in case we need to diagnose it retroactively. | |||
3696 | diag::kind diagKind; | |||
3697 | if (pointerKind == SimplePointerKind::Array) | |||
3698 | diagKind = diag::warn_nullability_missing_array; | |||
3699 | else | |||
3700 | diagKind = diag::warn_nullability_missing; | |||
3701 | ||||
3702 | if (fileNullability.PointerLoc.isInvalid() && | |||
3703 | !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { | |||
3704 | fileNullability.PointerLoc = pointerLoc; | |||
3705 | fileNullability.PointerEndLoc = pointerEndLoc; | |||
3706 | fileNullability.PointerKind = static_cast<unsigned>(pointerKind); | |||
3707 | } | |||
3708 | ||||
3709 | return; | |||
3710 | } | |||
3711 | ||||
3712 | // Complain about missing nullability. | |||
3713 | emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); | |||
3714 | } | |||
3715 | ||||
3716 | /// Marks that a nullability feature has been used in the file containing | |||
3717 | /// \p loc. | |||
3718 | /// | |||
3719 | /// If this file already had pointer types in it that were missing nullability, | |||
3720 | /// the first such instance is retroactively diagnosed. | |||
3721 | /// | |||
3722 | /// \sa checkNullabilityConsistency | |||
3723 | static void recordNullabilitySeen(Sema &S, SourceLocation loc) { | |||
3724 | FileID file = getNullabilityCompletenessCheckFileID(S, loc); | |||
3725 | if (file.isInvalid()) | |||
3726 | return; | |||
3727 | ||||
3728 | FileNullability &fileNullability = S.NullabilityMap[file]; | |||
3729 | if (fileNullability.SawTypeNullability) | |||
3730 | return; | |||
3731 | fileNullability.SawTypeNullability = true; | |||
3732 | ||||
3733 | // If we haven't seen any type nullability before, now we have. Retroactively | |||
3734 | // diagnose the first unannotated pointer, if there was one. | |||
3735 | if (fileNullability.PointerLoc.isInvalid()) | |||
3736 | return; | |||
3737 | ||||
3738 | auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); | |||
3739 | emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, | |||
3740 | fileNullability.PointerEndLoc); | |||
3741 | } | |||
3742 | ||||
3743 | /// Returns true if any of the declarator chunks before \p endIndex include a | |||
3744 | /// level of indirection: array, pointer, reference, or pointer-to-member. | |||
3745 | /// | |||
3746 | /// Because declarator chunks are stored in outer-to-inner order, testing | |||
3747 | /// every chunk before \p endIndex is testing all chunks that embed the current | |||
3748 | /// chunk as part of their type. | |||
3749 | /// | |||
3750 | /// It is legal to pass the result of Declarator::getNumTypeObjects() as the | |||
3751 | /// end index, in which case all chunks are tested. | |||
3752 | static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { | |||
3753 | unsigned i = endIndex; | |||
3754 | while (i != 0) { | |||
3755 | // Walk outwards along the declarator chunks. | |||
3756 | --i; | |||
3757 | const DeclaratorChunk &DC = D.getTypeObject(i); | |||
3758 | switch (DC.Kind) { | |||
3759 | case DeclaratorChunk::Paren: | |||
3760 | break; | |||
3761 | case DeclaratorChunk::Array: | |||
3762 | case DeclaratorChunk::Pointer: | |||
3763 | case DeclaratorChunk::Reference: | |||
3764 | case DeclaratorChunk::MemberPointer: | |||
3765 | return true; | |||
3766 | case DeclaratorChunk::Function: | |||
3767 | case DeclaratorChunk::BlockPointer: | |||
3768 | case DeclaratorChunk::Pipe: | |||
3769 | // These are invalid anyway, so just ignore. | |||
3770 | break; | |||
3771 | } | |||
3772 | } | |||
3773 | return false; | |||
3774 | } | |||
3775 | ||||
3776 | static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, | |||
3777 | QualType declSpecType, | |||
3778 | TypeSourceInfo *TInfo) { | |||
3779 | // The TypeSourceInfo that this function returns will not be a null type. | |||
3780 | // If there is an error, this function will fill in a dummy type as fallback. | |||
3781 | QualType T = declSpecType; | |||
3782 | Declarator &D = state.getDeclarator(); | |||
3783 | Sema &S = state.getSema(); | |||
3784 | ASTContext &Context = S.Context; | |||
3785 | const LangOptions &LangOpts = S.getLangOpts(); | |||
3786 | ||||
3787 | // The name we're declaring, if any. | |||
3788 | DeclarationName Name; | |||
3789 | if (D.getIdentifier()) | |||
3790 | Name = D.getIdentifier(); | |||
3791 | ||||
3792 | // Does this declaration declare a typedef-name? | |||
3793 | bool IsTypedefName = | |||
3794 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || | |||
3795 | D.getContext() == DeclaratorContext::AliasDeclContext || | |||
3796 | D.getContext() == DeclaratorContext::AliasTemplateContext; | |||
3797 | ||||
3798 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | |||
3799 | bool IsQualifiedFunction = T->isFunctionProtoType() && | |||
3800 | (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || | |||
3801 | T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); | |||
3802 | ||||
3803 | // If T is 'decltype(auto)', the only declarators we can have are parens | |||
3804 | // and at most one function declarator if this is a function declaration. | |||
3805 | // If T is a deduced class template specialization type, we can have no | |||
3806 | // declarator chunks at all. | |||
3807 | if (auto *DT = T->getAs<DeducedType>()) { | |||
3808 | const AutoType *AT = T->getAs<AutoType>(); | |||
3809 | bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); | |||
3810 | if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { | |||
3811 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | |||
3812 | unsigned Index = E - I - 1; | |||
3813 | DeclaratorChunk &DeclChunk = D.getTypeObject(Index); | |||
3814 | unsigned DiagId = IsClassTemplateDeduction | |||
3815 | ? diag::err_deduced_class_template_compound_type | |||
3816 | : diag::err_decltype_auto_compound_type; | |||
3817 | unsigned DiagKind = 0; | |||
3818 | switch (DeclChunk.Kind) { | |||
3819 | case DeclaratorChunk::Paren: | |||
3820 | // FIXME: Rejecting this is a little silly. | |||
3821 | if (IsClassTemplateDeduction) { | |||
3822 | DiagKind = 4; | |||
3823 | break; | |||
3824 | } | |||
3825 | continue; | |||
3826 | case DeclaratorChunk::Function: { | |||
3827 | if (IsClassTemplateDeduction) { | |||
3828 | DiagKind = 3; | |||
3829 | break; | |||
3830 | } | |||
3831 | unsigned FnIndex; | |||
3832 | if (D.isFunctionDeclarationContext() && | |||
3833 | D.isFunctionDeclarator(FnIndex) && FnIndex == Index) | |||
3834 | continue; | |||
3835 | DiagId = diag::err_decltype_auto_function_declarator_not_declaration; | |||
3836 | break; | |||
3837 | } | |||
3838 | case DeclaratorChunk::Pointer: | |||
3839 | case DeclaratorChunk::BlockPointer: | |||
3840 | case DeclaratorChunk::MemberPointer: | |||
3841 | DiagKind = 0; | |||
3842 | break; | |||
3843 | case DeclaratorChunk::Reference: | |||
3844 | DiagKind = 1; | |||
3845 | break; | |||
3846 | case DeclaratorChunk::Array: | |||
3847 | DiagKind = 2; | |||
3848 | break; | |||
3849 | case DeclaratorChunk::Pipe: | |||
3850 | break; | |||
3851 | } | |||
3852 | ||||
3853 | S.Diag(DeclChunk.Loc, DiagId) << DiagKind; | |||
3854 | D.setInvalidType(true); | |||
3855 | break; | |||
3856 | } | |||
3857 | } | |||
3858 | } | |||
3859 | ||||
3860 | // Determine whether we should infer _Nonnull on pointer types. | |||
3861 | Optional<NullabilityKind> inferNullability; | |||
3862 | bool inferNullabilityCS = false; | |||
3863 | bool inferNullabilityInnerOnly = false; | |||
3864 | bool inferNullabilityInnerOnlyComplete = false; | |||
3865 | ||||
3866 | // Are we in an assume-nonnull region? | |||
3867 | bool inAssumeNonNullRegion = false; | |||
3868 | SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); | |||
3869 | if (assumeNonNullLoc.isValid()) { | |||
3870 | inAssumeNonNullRegion = true; | |||
3871 | recordNullabilitySeen(S, assumeNonNullLoc); | |||
3872 | } | |||
3873 | ||||
3874 | // Whether to complain about missing nullability specifiers or not. | |||
3875 | enum { | |||
3876 | /// Never complain. | |||
3877 | CAMN_No, | |||
3878 | /// Complain on the inner pointers (but not the outermost | |||
3879 | /// pointer). | |||
3880 | CAMN_InnerPointers, | |||
3881 | /// Complain about any pointers that don't have nullability | |||
3882 | /// specified or inferred. | |||
3883 | CAMN_Yes | |||
3884 | } complainAboutMissingNullability = CAMN_No; | |||
3885 | unsigned NumPointersRemaining = 0; | |||
3886 | auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; | |||
3887 | ||||
3888 | if (IsTypedefName) { | |||
3889 | // For typedefs, we do not infer any nullability (the default), | |||
3890 | // and we only complain about missing nullability specifiers on | |||
3891 | // inner pointers. | |||
3892 | complainAboutMissingNullability = CAMN_InnerPointers; | |||
3893 | ||||
3894 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | |||
3895 | !T->getNullability(S.Context)) { | |||
3896 | // Note that we allow but don't require nullability on dependent types. | |||
3897 | ++NumPointersRemaining; | |||
3898 | } | |||
3899 | ||||
3900 | for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { | |||
3901 | DeclaratorChunk &chunk = D.getTypeObject(i); | |||
3902 | switch (chunk.Kind) { | |||
3903 | case DeclaratorChunk::Array: | |||
3904 | case DeclaratorChunk::Function: | |||
3905 | case DeclaratorChunk::Pipe: | |||
3906 | break; | |||
3907 | ||||
3908 | case DeclaratorChunk::BlockPointer: | |||
3909 | case DeclaratorChunk::MemberPointer: | |||
3910 | ++NumPointersRemaining; | |||
3911 | break; | |||
3912 | ||||
3913 | case DeclaratorChunk::Paren: | |||
3914 | case DeclaratorChunk::Reference: | |||
3915 | continue; | |||
3916 | ||||
3917 | case DeclaratorChunk::Pointer: | |||
3918 | ++NumPointersRemaining; | |||
3919 | continue; | |||
3920 | } | |||
3921 | } | |||
3922 | } else { | |||
3923 | bool isFunctionOrMethod = false; | |||
3924 | switch (auto context = state.getDeclarator().getContext()) { | |||
3925 | case DeclaratorContext::ObjCParameterContext: | |||
3926 | case DeclaratorContext::ObjCResultContext: | |||
3927 | case DeclaratorContext::PrototypeContext: | |||
3928 | case DeclaratorContext::TrailingReturnContext: | |||
3929 | case DeclaratorContext::TrailingReturnVarContext: | |||
3930 | isFunctionOrMethod = true; | |||
3931 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
3932 | ||||
3933 | case DeclaratorContext::MemberContext: | |||
3934 | if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { | |||
3935 | complainAboutMissingNullability = CAMN_No; | |||
3936 | break; | |||
3937 | } | |||
3938 | ||||
3939 | // Weak properties are inferred to be nullable. | |||
3940 | if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { | |||
3941 | inferNullability = NullabilityKind::Nullable; | |||
3942 | break; | |||
3943 | } | |||
3944 | ||||
3945 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
3946 | ||||
3947 | case DeclaratorContext::FileContext: | |||
3948 | case DeclaratorContext::KNRTypeListContext: { | |||
3949 | complainAboutMissingNullability = CAMN_Yes; | |||
3950 | ||||
3951 | // Nullability inference depends on the type and declarator. | |||
3952 | auto wrappingKind = PointerWrappingDeclaratorKind::None; | |||
3953 | switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { | |||
3954 | case PointerDeclaratorKind::NonPointer: | |||
3955 | case PointerDeclaratorKind::MultiLevelPointer: | |||
3956 | // Cannot infer nullability. | |||
3957 | break; | |||
3958 | ||||
3959 | case PointerDeclaratorKind::SingleLevelPointer: | |||
3960 | // Infer _Nonnull if we are in an assumes-nonnull region. | |||
3961 | if (inAssumeNonNullRegion) { | |||
3962 | complainAboutInferringWithinChunk = wrappingKind; | |||
3963 | inferNullability = NullabilityKind::NonNull; | |||
3964 | inferNullabilityCS = | |||
3965 | (context == DeclaratorContext::ObjCParameterContext || | |||
3966 | context == DeclaratorContext::ObjCResultContext); | |||
3967 | } | |||
3968 | break; | |||
3969 | ||||
3970 | case PointerDeclaratorKind::CFErrorRefPointer: | |||
3971 | case PointerDeclaratorKind::NSErrorPointerPointer: | |||
3972 | // Within a function or method signature, infer _Nullable at both | |||
3973 | // levels. | |||
3974 | if (isFunctionOrMethod && inAssumeNonNullRegion) | |||
3975 | inferNullability = NullabilityKind::Nullable; | |||
3976 | break; | |||
3977 | ||||
3978 | case PointerDeclaratorKind::MaybePointerToCFRef: | |||
3979 | if (isFunctionOrMethod) { | |||
3980 | // On pointer-to-pointer parameters marked cf_returns_retained or | |||
3981 | // cf_returns_not_retained, if the outer pointer is explicit then | |||
3982 | // infer the inner pointer as _Nullable. | |||
3983 | auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool { | |||
3984 | while (NextAttr) { | |||
3985 | if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained || | |||
3986 | NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained) | |||
3987 | return true; | |||
3988 | NextAttr = NextAttr->getNext(); | |||
3989 | } | |||
3990 | return false; | |||
3991 | }; | |||
3992 | if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { | |||
3993 | if (hasCFReturnsAttr(D.getAttributes()) || | |||
3994 | hasCFReturnsAttr(InnermostChunk->getAttrs()) || | |||
3995 | hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) { | |||
3996 | inferNullability = NullabilityKind::Nullable; | |||
3997 | inferNullabilityInnerOnly = true; | |||
3998 | } | |||
3999 | } | |||
4000 | } | |||
4001 | break; | |||
4002 | } | |||
4003 | break; | |||
4004 | } | |||
4005 | ||||
4006 | case DeclaratorContext::ConversionIdContext: | |||
4007 | complainAboutMissingNullability = CAMN_Yes; | |||
4008 | break; | |||
4009 | ||||
4010 | case DeclaratorContext::AliasDeclContext: | |||
4011 | case DeclaratorContext::AliasTemplateContext: | |||
4012 | case DeclaratorContext::BlockContext: | |||
4013 | case DeclaratorContext::BlockLiteralContext: | |||
4014 | case DeclaratorContext::ConditionContext: | |||
4015 | case DeclaratorContext::CXXCatchContext: | |||
4016 | case DeclaratorContext::CXXNewContext: | |||
4017 | case DeclaratorContext::ForContext: | |||
4018 | case DeclaratorContext::InitStmtContext: | |||
4019 | case DeclaratorContext::LambdaExprContext: | |||
4020 | case DeclaratorContext::LambdaExprParameterContext: | |||
4021 | case DeclaratorContext::ObjCCatchContext: | |||
4022 | case DeclaratorContext::TemplateParamContext: | |||
4023 | case DeclaratorContext::TemplateArgContext: | |||
4024 | case DeclaratorContext::TemplateTypeArgContext: | |||
4025 | case DeclaratorContext::TypeNameContext: | |||
4026 | case DeclaratorContext::FunctionalCastContext: | |||
4027 | // Don't infer in these contexts. | |||
4028 | break; | |||
4029 | } | |||
4030 | } | |||
4031 | ||||
4032 | // Local function that returns true if its argument looks like a va_list. | |||
4033 | auto isVaList = [&S](QualType T) -> bool { | |||
4034 | auto *typedefTy = T->getAs<TypedefType>(); | |||
4035 | if (!typedefTy) | |||
4036 | return false; | |||
4037 | TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); | |||
4038 | do { | |||
4039 | if (typedefTy->getDecl() == vaListTypedef) | |||
4040 | return true; | |||
4041 | if (auto *name = typedefTy->getDecl()->getIdentifier()) | |||
4042 | if (name->isStr("va_list")) | |||
4043 | return true; | |||
4044 | typedefTy = typedefTy->desugar()->getAs<TypedefType>(); | |||
4045 | } while (typedefTy); | |||
4046 | return false; | |||
4047 | }; | |||
4048 | ||||
4049 | // Local function that checks the nullability for a given pointer declarator. | |||
4050 | // Returns true if _Nonnull was inferred. | |||
4051 | auto inferPointerNullability = [&](SimplePointerKind pointerKind, | |||
4052 | SourceLocation pointerLoc, | |||
4053 | SourceLocation pointerEndLoc, | |||
4054 | AttributeList *&attrs) -> AttributeList * { | |||
4055 | // We've seen a pointer. | |||
4056 | if (NumPointersRemaining > 0) | |||
4057 | --NumPointersRemaining; | |||
4058 | ||||
4059 | // If a nullability attribute is present, there's nothing to do. | |||
4060 | if (hasNullabilityAttr(attrs)) | |||
4061 | return nullptr; | |||
4062 | ||||
4063 | // If we're supposed to infer nullability, do so now. | |||
4064 | if (inferNullability && !inferNullabilityInnerOnlyComplete) { | |||
4065 | AttributeList::Syntax syntax | |||
4066 | = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword | |||
4067 | : AttributeList::AS_Keyword; | |||
4068 | AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool() | |||
4069 | .create( | |||
4070 | S.getNullabilityKeyword( | |||
4071 | *inferNullability), | |||
4072 | SourceRange(pointerLoc), | |||
4073 | nullptr, SourceLocation(), | |||
4074 | nullptr, 0, syntax); | |||
4075 | ||||
4076 | spliceAttrIntoList(*nullabilityAttr, attrs); | |||
4077 | ||||
4078 | if (inferNullabilityCS) { | |||
4079 | state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() | |||
4080 | ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); | |||
4081 | } | |||
4082 | ||||
4083 | if (pointerLoc.isValid() && | |||
4084 | complainAboutInferringWithinChunk != | |||
4085 | PointerWrappingDeclaratorKind::None) { | |||
4086 | auto Diag = | |||
4087 | S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); | |||
4088 | Diag << static_cast<int>(complainAboutInferringWithinChunk); | |||
4089 | fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); | |||
4090 | } | |||
4091 | ||||
4092 | if (inferNullabilityInnerOnly) | |||
4093 | inferNullabilityInnerOnlyComplete = true; | |||
4094 | return nullabilityAttr; | |||
4095 | } | |||
4096 | ||||
4097 | // If we're supposed to complain about missing nullability, do so | |||
4098 | // now if it's truly missing. | |||
4099 | switch (complainAboutMissingNullability) { | |||
4100 | case CAMN_No: | |||
4101 | break; | |||
4102 | ||||
4103 | case CAMN_InnerPointers: | |||
4104 | if (NumPointersRemaining == 0) | |||
4105 | break; | |||
4106 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
4107 | ||||
4108 | case CAMN_Yes: | |||
4109 | checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); | |||
4110 | } | |||
4111 | return nullptr; | |||
4112 | }; | |||
4113 | ||||
4114 | // If the type itself could have nullability but does not, infer pointer | |||
4115 | // nullability and perform consistency checking. | |||
4116 | if (S.CodeSynthesisContexts.empty()) { | |||
4117 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | |||
4118 | !T->getNullability(S.Context)) { | |||
4119 | if (isVaList(T)) { | |||
4120 | // Record that we've seen a pointer, but do nothing else. | |||
4121 | if (NumPointersRemaining > 0) | |||
4122 | --NumPointersRemaining; | |||
4123 | } else { | |||
4124 | SimplePointerKind pointerKind = SimplePointerKind::Pointer; | |||
4125 | if (T->isBlockPointerType()) | |||
4126 | pointerKind = SimplePointerKind::BlockPointer; | |||
4127 | else if (T->isMemberPointerType()) | |||
4128 | pointerKind = SimplePointerKind::MemberPointer; | |||
4129 | ||||
4130 | if (auto *attr = inferPointerNullability( | |||
4131 | pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), | |||
4132 | D.getDeclSpec().getLocEnd(), | |||
4133 | D.getMutableDeclSpec().getAttributes().getListRef())) { | |||
4134 | T = Context.getAttributedType( | |||
4135 | AttributedType::getNullabilityAttrKind(*inferNullability),T,T); | |||
4136 | attr->setUsedAsTypeAttr(); | |||
4137 | } | |||
4138 | } | |||
4139 | } | |||
4140 | ||||
4141 | if (complainAboutMissingNullability == CAMN_Yes && | |||
4142 | T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && | |||
4143 | D.isPrototypeContext() && | |||
4144 | !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { | |||
4145 | checkNullabilityConsistency(S, SimplePointerKind::Array, | |||
4146 | D.getDeclSpec().getTypeSpecTypeLoc()); | |||
4147 | } | |||
4148 | } | |||
4149 | ||||
4150 | // Walk the DeclTypeInfo, building the recursive type as we go. | |||
4151 | // DeclTypeInfos are ordered from the identifier out, which is | |||
4152 | // opposite of what we want :). | |||
4153 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
4154 | unsigned chunkIndex = e - i - 1; | |||
4155 | state.setCurrentChunkIndex(chunkIndex); | |||
4156 | DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); | |||
4157 | IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; | |||
4158 | switch (DeclType.Kind) { | |||
4159 | case DeclaratorChunk::Paren: | |||
4160 | if (i == 0) | |||
4161 | warnAboutRedundantParens(S, D, T); | |||
4162 | T = S.BuildParenType(T); | |||
4163 | break; | |||
4164 | case DeclaratorChunk::BlockPointer: | |||
4165 | // If blocks are disabled, emit an error. | |||
4166 | if (!LangOpts.Blocks) | |||
4167 | S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; | |||
4168 | ||||
4169 | // Handle pointer nullability. | |||
4170 | inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, | |||
4171 | DeclType.EndLoc, DeclType.getAttrListRef()); | |||
4172 | ||||
4173 | T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); | |||
4174 | if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { | |||
4175 | // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly | |||
4176 | // qualified with const. | |||
4177 | if (LangOpts.OpenCL) | |||
4178 | DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; | |||
4179 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); | |||
4180 | } | |||
4181 | break; | |||
4182 | case DeclaratorChunk::Pointer: | |||
4183 | // Verify that we're not building a pointer to pointer to function with | |||
4184 | // exception specification. | |||
4185 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4186 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4187 | D.setInvalidType(true); | |||
4188 | // Build the type anyway. | |||
4189 | } | |||
4190 | ||||
4191 | // Handle pointer nullability | |||
4192 | inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, | |||
4193 | DeclType.EndLoc, DeclType.getAttrListRef()); | |||
4194 | ||||
4195 | if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { | |||
4196 | T = Context.getObjCObjectPointerType(T); | |||
4197 | if (DeclType.Ptr.TypeQuals) | |||
4198 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | |||
4199 | break; | |||
4200 | } | |||
4201 | ||||
4202 | // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. | |||
4203 | // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. | |||
4204 | // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. | |||
4205 | if (LangOpts.OpenCL) { | |||
4206 | if (T->isImageType() || T->isSamplerT() || T->isPipeType() || | |||
4207 | T->isBlockPointerType()) { | |||
4208 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; | |||
4209 | D.setInvalidType(true); | |||
4210 | } | |||
4211 | } | |||
4212 | ||||
4213 | T = S.BuildPointerType(T, DeclType.Loc, Name); | |||
4214 | if (DeclType.Ptr.TypeQuals) | |||
4215 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | |||
4216 | break; | |||
4217 | case DeclaratorChunk::Reference: { | |||
4218 | // Verify that we're not building a reference to pointer to function with | |||
4219 | // exception specification. | |||
4220 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4221 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4222 | D.setInvalidType(true); | |||
4223 | // Build the type anyway. | |||
4224 | } | |||
4225 | T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); | |||
4226 | ||||
4227 | if (DeclType.Ref.HasRestrict) | |||
4228 | T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); | |||
4229 | break; | |||
4230 | } | |||
4231 | case DeclaratorChunk::Array: { | |||
4232 | // Verify that we're not building an array of pointers to function with | |||
4233 | // exception specification. | |||
4234 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4235 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4236 | D.setInvalidType(true); | |||
4237 | // Build the type anyway. | |||
4238 | } | |||
4239 | DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; | |||
4240 | Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); | |||
4241 | ArrayType::ArraySizeModifier ASM; | |||
4242 | if (ATI.isStar) | |||
4243 | ASM = ArrayType::Star; | |||
4244 | else if (ATI.hasStatic) | |||
4245 | ASM = ArrayType::Static; | |||
4246 | else | |||
4247 | ASM = ArrayType::Normal; | |||
4248 | if (ASM == ArrayType::Star && !D.isPrototypeContext()) { | |||
4249 | // FIXME: This check isn't quite right: it allows star in prototypes | |||
4250 | // for function definitions, and disallows some edge cases detailed | |||
4251 | // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html | |||
4252 | S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); | |||
4253 | ASM = ArrayType::Normal; | |||
4254 | D.setInvalidType(true); | |||
4255 | } | |||
4256 | ||||
4257 | // C99 6.7.5.2p1: The optional type qualifiers and the keyword static | |||
4258 | // shall appear only in a declaration of a function parameter with an | |||
4259 | // array type, ... | |||
4260 | if (ASM == ArrayType::Static || ATI.TypeQuals) { | |||
4261 | if (!(D.isPrototypeContext() || | |||
4262 | D.getContext() == DeclaratorContext::KNRTypeListContext)) { | |||
4263 | S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << | |||
4264 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | |||
4265 | // Remove the 'static' and the type qualifiers. | |||
4266 | if (ASM == ArrayType::Static) | |||
4267 | ASM = ArrayType::Normal; | |||
4268 | ATI.TypeQuals = 0; | |||
4269 | D.setInvalidType(true); | |||
4270 | } | |||
4271 | ||||
4272 | // C99 6.7.5.2p1: ... and then only in the outermost array type | |||
4273 | // derivation. | |||
4274 | if (hasOuterPointerLikeChunk(D, chunkIndex)) { | |||
4275 | S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << | |||
4276 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | |||
4277 | if (ASM == ArrayType::Static) | |||
4278 | ASM = ArrayType::Normal; | |||
4279 | ATI.TypeQuals = 0; | |||
4280 | D.setInvalidType(true); | |||
4281 | } | |||
4282 | } | |||
4283 | const AutoType *AT = T->getContainedAutoType(); | |||
4284 | // Allow arrays of auto if we are a generic lambda parameter. | |||
4285 | // i.e. [](auto (&array)[5]) { return array[0]; }; OK | |||
4286 | if (AT && | |||
4287 | D.getContext() != DeclaratorContext::LambdaExprParameterContext) { | |||
4288 | // We've already diagnosed this for decltype(auto). | |||
4289 | if (!AT->isDecltypeAuto()) | |||
4290 | S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) | |||
4291 | << getPrintableNameForEntity(Name) << T; | |||
4292 | T = QualType(); | |||
4293 | break; | |||
4294 | } | |||
4295 | ||||
4296 | // Array parameters can be marked nullable as well, although it's not | |||
4297 | // necessary if they're marked 'static'. | |||
4298 | if (complainAboutMissingNullability == CAMN_Yes && | |||
4299 | !hasNullabilityAttr(DeclType.getAttrs()) && | |||
4300 | ASM != ArrayType::Static && | |||
4301 | D.isPrototypeContext() && | |||
4302 | !hasOuterPointerLikeChunk(D, chunkIndex)) { | |||
4303 | checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); | |||
4304 | } | |||
4305 | ||||
4306 | T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, | |||
4307 | SourceRange(DeclType.Loc, DeclType.EndLoc), Name); | |||
4308 | break; | |||
4309 | } | |||
4310 | case DeclaratorChunk::Function: { | |||
4311 | // If the function declarator has a prototype (i.e. it is not () and | |||
4312 | // does not have a K&R-style identifier list), then the arguments are part | |||
4313 | // of the type, otherwise the argument list is (). | |||
4314 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
4315 | IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); | |||
4316 | ||||
4317 | // Check for auto functions and trailing return type and adjust the | |||
4318 | // return type accordingly. | |||
4319 | if (!D.isInvalidType()) { | |||
4320 | // trailing-return-type is only required if we're declaring a function, | |||
4321 | // and not, for instance, a pointer to a function. | |||
4322 | if (D.getDeclSpec().hasAutoTypeSpec() && | |||
4323 | !FTI.hasTrailingReturnType() && chunkIndex == 0 && | |||
4324 | !S.getLangOpts().CPlusPlus14) { | |||
4325 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
4326 | D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto | |||
4327 | ? diag::err_auto_missing_trailing_return | |||
4328 | : diag::err_deduced_return_type); | |||
4329 | T = Context.IntTy; | |||
4330 | D.setInvalidType(true); | |||
4331 | } else if (FTI.hasTrailingReturnType()) { | |||
4332 | // T must be exactly 'auto' at this point. See CWG issue 681. | |||
4333 | if (isa<ParenType>(T)) { | |||
4334 | S.Diag(D.getLocStart(), | |||
4335 | diag::err_trailing_return_in_parens) | |||
4336 | << T << D.getSourceRange(); | |||
4337 | D.setInvalidType(true); | |||
4338 | } else if (D.getName().getKind() == | |||
4339 | UnqualifiedIdKind::IK_DeductionGuideName) { | |||
4340 | if (T != Context.DependentTy) { | |||
4341 | S.Diag(D.getDeclSpec().getLocStart(), | |||
4342 | diag::err_deduction_guide_with_complex_decl) | |||
4343 | << D.getSourceRange(); | |||
4344 | D.setInvalidType(true); | |||
4345 | } | |||
4346 | } else if (D.getContext() != DeclaratorContext::LambdaExprContext && | |||
4347 | (T.hasQualifiers() || !isa<AutoType>(T) || | |||
4348 | cast<AutoType>(T)->getKeyword() != | |||
4349 | AutoTypeKeyword::Auto)) { | |||
4350 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
4351 | diag::err_trailing_return_without_auto) | |||
4352 | << T << D.getDeclSpec().getSourceRange(); | |||
4353 | D.setInvalidType(true); | |||
4354 | } | |||
4355 | T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); | |||
4356 | if (T.isNull()) { | |||
4357 | // An error occurred parsing the trailing return type. | |||
4358 | T = Context.IntTy; | |||
4359 | D.setInvalidType(true); | |||
4360 | } | |||
4361 | } | |||
4362 | } | |||
4363 | ||||
4364 | // C99 6.7.5.3p1: The return type may not be a function or array type. | |||
4365 | // For conversion functions, we'll diagnose this particular error later. | |||
4366 | if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && | |||
4367 | (D.getName().getKind() != | |||
4368 | UnqualifiedIdKind::IK_ConversionFunctionId)) { | |||
4369 | unsigned diagID = diag::err_func_returning_array_function; | |||
4370 | // Last processing chunk in block context means this function chunk | |||
4371 | // represents the block. | |||
4372 | if (chunkIndex == 0 && | |||
4373 | D.getContext() == DeclaratorContext::BlockLiteralContext) | |||
4374 | diagID = diag::err_block_returning_array_function; | |||
4375 | S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; | |||
4376 | T = Context.IntTy; | |||
4377 | D.setInvalidType(true); | |||
4378 | } | |||
4379 | ||||
4380 | // Do not allow returning half FP value. | |||
4381 | // FIXME: This really should be in BuildFunctionType. | |||
4382 | if (T->isHalfType()) { | |||
4383 | if (S.getLangOpts().OpenCL) { | |||
4384 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { | |||
4385 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | |||
4386 | << T << 0 /*pointer hint*/; | |||
4387 | D.setInvalidType(true); | |||
4388 | } | |||
4389 | } else if (!S.getLangOpts().HalfArgsAndReturns) { | |||
4390 | S.Diag(D.getIdentifierLoc(), | |||
4391 | diag::err_parameters_retval_cannot_have_fp16_type) << 1; | |||
4392 | D.setInvalidType(true); | |||
4393 | } | |||
4394 | } | |||
4395 | ||||
4396 | if (LangOpts.OpenCL) { | |||
4397 | // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a | |||
4398 | // function. | |||
4399 | if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || | |||
4400 | T->isPipeType()) { | |||
4401 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | |||
4402 | << T << 1 /*hint off*/; | |||
4403 | D.setInvalidType(true); | |||
4404 | } | |||
4405 | // OpenCL doesn't support variadic functions and blocks | |||
4406 | // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. | |||
4407 | // We also allow here any toolchain reserved identifiers. | |||
4408 | if (FTI.isVariadic && | |||
4409 | !(D.getIdentifier() && | |||
4410 | ((D.getIdentifier()->getName() == "printf" && | |||
4411 | LangOpts.OpenCLVersion >= 120) || | |||
4412 | D.getIdentifier()->getName().startswith("__")))) { | |||
4413 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); | |||
4414 | D.setInvalidType(true); | |||
4415 | } | |||
4416 | } | |||
4417 | ||||
4418 | // Methods cannot return interface types. All ObjC objects are | |||
4419 | // passed by reference. | |||
4420 | if (T->isObjCObjectType()) { | |||
4421 | SourceLocation DiagLoc, FixitLoc; | |||
4422 | if (TInfo) { | |||
4423 | DiagLoc = TInfo->getTypeLoc().getLocStart(); | |||
4424 | FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd()); | |||
4425 | } else { | |||
4426 | DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); | |||
4427 | FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd()); | |||
4428 | } | |||
4429 | S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) | |||
4430 | << 0 << T | |||
4431 | << FixItHint::CreateInsertion(FixitLoc, "*"); | |||
4432 | ||||
4433 | T = Context.getObjCObjectPointerType(T); | |||
4434 | if (TInfo) { | |||
4435 | TypeLocBuilder TLB; | |||
4436 | TLB.pushFullCopy(TInfo->getTypeLoc()); | |||
4437 | ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); | |||
4438 | TLoc.setStarLoc(FixitLoc); | |||
4439 | TInfo = TLB.getTypeSourceInfo(Context, T); | |||
4440 | } | |||
4441 | ||||
4442 | D.setInvalidType(true); | |||
4443 | } | |||
4444 | ||||
4445 | // cv-qualifiers on return types are pointless except when the type is a | |||
4446 | // class type in C++. | |||
4447 | if ((T.getCVRQualifiers() || T->isAtomicType()) && | |||
4448 | !(S.getLangOpts().CPlusPlus && | |||
4449 | (T->isDependentType() || T->isRecordType()))) { | |||
4450 | if (T->isVoidType() && !S.getLangOpts().CPlusPlus && | |||
4451 | D.getFunctionDefinitionKind() == FDK_Definition) { | |||
4452 | // [6.9.1/3] qualified void return is invalid on a C | |||
4453 | // function definition. Apparently ok on declarations and | |||
4454 | // in C++ though (!) | |||
4455 | S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; | |||
4456 | } else | |||
4457 | diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); | |||
4458 | } | |||
4459 | ||||
4460 | // Objective-C ARC ownership qualifiers are ignored on the function | |||
4461 | // return type (by type canonicalization). Complain if this attribute | |||
4462 | // was written here. | |||
4463 | if (T.getQualifiers().hasObjCLifetime()) { | |||
4464 | SourceLocation AttrLoc; | |||
4465 | if (chunkIndex + 1 < D.getNumTypeObjects()) { | |||
4466 | DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); | |||
4467 | for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); | |||
4468 | Attr; Attr = Attr->getNext()) { | |||
4469 | if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { | |||
4470 | AttrLoc = Attr->getLoc(); | |||
4471 | break; | |||
4472 | } | |||
4473 | } | |||
4474 | } | |||
4475 | if (AttrLoc.isInvalid()) { | |||
4476 | for (const AttributeList *Attr | |||
4477 | = D.getDeclSpec().getAttributes().getList(); | |||
4478 | Attr; Attr = Attr->getNext()) { | |||
4479 | if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { | |||
4480 | AttrLoc = Attr->getLoc(); | |||
4481 | break; | |||
4482 | } | |||
4483 | } | |||
4484 | } | |||
4485 | ||||
4486 | if (AttrLoc.isValid()) { | |||
4487 | // The ownership attributes are almost always written via | |||
4488 | // the predefined | |||
4489 | // __strong/__weak/__autoreleasing/__unsafe_unretained. | |||
4490 | if (AttrLoc.isMacroID()) | |||
4491 | AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; | |||
4492 | ||||
4493 | S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) | |||
4494 | << T.getQualifiers().getObjCLifetime(); | |||
4495 | } | |||
4496 | } | |||
4497 | ||||
4498 | if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { | |||
4499 | // C++ [dcl.fct]p6: | |||
4500 | // Types shall not be defined in return or parameter types. | |||
4501 | TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
4502 | S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) | |||
4503 | << Context.getTypeDeclType(Tag); | |||
4504 | } | |||
4505 | ||||
4506 | // Exception specs are not allowed in typedefs. Complain, but add it | |||
4507 | // anyway. | |||
4508 | if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) | |||
4509 | S.Diag(FTI.getExceptionSpecLocBeg(), | |||
4510 | diag::err_exception_spec_in_typedef) | |||
4511 | << (D.getContext() == DeclaratorContext::AliasDeclContext || | |||
4512 | D.getContext() == DeclaratorContext::AliasTemplateContext); | |||
4513 | ||||
4514 | // If we see "T var();" or "T var(T());" at block scope, it is probably | |||
4515 | // an attempt to initialize a variable, not a function declaration. | |||
4516 | if (FTI.isAmbiguous) | |||
4517 | warnAboutAmbiguousFunction(S, D, DeclType, T); | |||
4518 | ||||
4519 | FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex)); | |||
4520 | ||||
4521 | if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus | |||
4522 | && !LangOpts.OpenCL) { | |||
4523 | // Simple void foo(), where the incoming T is the result type. | |||
4524 | T = Context.getFunctionNoProtoType(T, EI); | |||
4525 | } else { | |||
4526 | // We allow a zero-parameter variadic function in C if the | |||
4527 | // function is marked with the "overloadable" attribute. Scan | |||
4528 | // for this attribute now. | |||
4529 | if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { | |||
4530 | bool Overloadable = false; | |||
4531 | for (const AttributeList *Attrs = D.getAttributes(); | |||
4532 | Attrs; Attrs = Attrs->getNext()) { | |||
4533 | if (Attrs->getKind() == AttributeList::AT_Overloadable) { | |||
4534 | Overloadable = true; | |||
4535 | break; | |||
4536 | } | |||
4537 | } | |||
4538 | ||||
4539 | if (!Overloadable) | |||
4540 | S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); | |||
4541 | } | |||
4542 | ||||
4543 | if (FTI.NumParams && FTI.Params[0].Param == nullptr) { | |||
4544 | // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function | |||
4545 | // definition. | |||
4546 | S.Diag(FTI.Params[0].IdentLoc, | |||
4547 | diag::err_ident_list_in_fn_declaration); | |||
4548 | D.setInvalidType(true); | |||
4549 | // Recover by creating a K&R-style function type. | |||
4550 | T = Context.getFunctionNoProtoType(T, EI); | |||
4551 | break; | |||
4552 | } | |||
4553 | ||||
4554 | FunctionProtoType::ExtProtoInfo EPI; | |||
4555 | EPI.ExtInfo = EI; | |||
4556 | EPI.Variadic = FTI.isVariadic; | |||
4557 | EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); | |||
4558 | EPI.TypeQuals = FTI.TypeQuals; | |||
4559 | EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None | |||
4560 | : FTI.RefQualifierIsLValueRef? RQ_LValue | |||
4561 | : RQ_RValue; | |||
4562 | ||||
4563 | // Otherwise, we have a function with a parameter list that is | |||
4564 | // potentially variadic. | |||
4565 | SmallVector<QualType, 16> ParamTys; | |||
4566 | ParamTys.reserve(FTI.NumParams); | |||
4567 | ||||
4568 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> | |||
4569 | ExtParameterInfos(FTI.NumParams); | |||
4570 | bool HasAnyInterestingExtParameterInfos = false; | |||
4571 | ||||
4572 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | |||
4573 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
4574 | QualType ParamTy = Param->getType(); | |||
4575 | assert(!ParamTy.isNull() && "Couldn't parse type?")(static_cast <bool> (!ParamTy.isNull() && "Couldn't parse type?" ) ? void (0) : __assert_fail ("!ParamTy.isNull() && \"Couldn't parse type?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 4575, __extension__ __PRETTY_FUNCTION__)); | |||
4576 | ||||
4577 | // Look for 'void'. void is allowed only as a single parameter to a | |||
4578 | // function with no other parameters (C99 6.7.5.3p10). We record | |||
4579 | // int(void) as a FunctionProtoType with an empty parameter list. | |||
4580 | if (ParamTy->isVoidType()) { | |||
4581 | // If this is something like 'float(int, void)', reject it. 'void' | |||
4582 | // is an incomplete type (C99 6.2.5p19) and function decls cannot | |||
4583 | // have parameters of incomplete type. | |||
4584 | if (FTI.NumParams != 1 || FTI.isVariadic) { | |||
4585 | S.Diag(DeclType.Loc, diag::err_void_only_param); | |||
4586 | ParamTy = Context.IntTy; | |||
4587 | Param->setType(ParamTy); | |||
4588 | } else if (FTI.Params[i].Ident) { | |||
4589 | // Reject, but continue to parse 'int(void abc)'. | |||
4590 | S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); | |||
4591 | ParamTy = Context.IntTy; | |||
4592 | Param->setType(ParamTy); | |||
4593 | } else { | |||
4594 | // Reject, but continue to parse 'float(const void)'. | |||
4595 | if (ParamTy.hasQualifiers()) | |||
4596 | S.Diag(DeclType.Loc, diag::err_void_param_qualified); | |||
4597 | ||||
4598 | // Do not add 'void' to the list. | |||
4599 | break; | |||
4600 | } | |||
4601 | } else if (ParamTy->isHalfType()) { | |||
4602 | // Disallow half FP parameters. | |||
4603 | // FIXME: This really should be in BuildFunctionType. | |||
4604 | if (S.getLangOpts().OpenCL) { | |||
4605 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { | |||
4606 | S.Diag(Param->getLocation(), | |||
4607 | diag::err_opencl_half_param) << ParamTy; | |||
4608 | D.setInvalidType(); | |||
4609 | Param->setInvalidDecl(); | |||
4610 | } | |||
4611 | } else if (!S.getLangOpts().HalfArgsAndReturns) { | |||
4612 | S.Diag(Param->getLocation(), | |||
4613 | diag::err_parameters_retval_cannot_have_fp16_type) << 0; | |||
4614 | D.setInvalidType(); | |||
4615 | } | |||
4616 | } else if (!FTI.hasPrototype) { | |||
4617 | if (ParamTy->isPromotableIntegerType()) { | |||
4618 | ParamTy = Context.getPromotedIntegerType(ParamTy); | |||
4619 | Param->setKNRPromoted(true); | |||
4620 | } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { | |||
4621 | if (BTy->getKind() == BuiltinType::Float) { | |||
4622 | ParamTy = Context.DoubleTy; | |||
4623 | Param->setKNRPromoted(true); | |||
4624 | } | |||
4625 | } | |||
4626 | } | |||
4627 | ||||
4628 | if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { | |||
4629 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); | |||
4630 | HasAnyInterestingExtParameterInfos = true; | |||
4631 | } | |||
4632 | ||||
4633 | if (auto attr = Param->getAttr<ParameterABIAttr>()) { | |||
4634 | ExtParameterInfos[i] = | |||
4635 | ExtParameterInfos[i].withABI(attr->getABI()); | |||
4636 | HasAnyInterestingExtParameterInfos = true; | |||
4637 | } | |||
4638 | ||||
4639 | if (Param->hasAttr<PassObjectSizeAttr>()) { | |||
4640 | ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); | |||
4641 | HasAnyInterestingExtParameterInfos = true; | |||
4642 | } | |||
4643 | ||||
4644 | if (Param->hasAttr<NoEscapeAttr>()) { | |||
4645 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); | |||
4646 | HasAnyInterestingExtParameterInfos = true; | |||
4647 | } | |||
4648 | ||||
4649 | ParamTys.push_back(ParamTy); | |||
4650 | } | |||
4651 | ||||
4652 | if (HasAnyInterestingExtParameterInfos) { | |||
4653 | EPI.ExtParameterInfos = ExtParameterInfos.data(); | |||
4654 | checkExtParameterInfos(S, ParamTys, EPI, | |||
4655 | [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); | |||
4656 | } | |||
4657 | ||||
4658 | SmallVector<QualType, 4> Exceptions; | |||
4659 | SmallVector<ParsedType, 2> DynamicExceptions; | |||
4660 | SmallVector<SourceRange, 2> DynamicExceptionRanges; | |||
4661 | Expr *NoexceptExpr = nullptr; | |||
4662 | ||||
4663 | if (FTI.getExceptionSpecType() == EST_Dynamic) { | |||
4664 | // FIXME: It's rather inefficient to have to split into two vectors | |||
4665 | // here. | |||
4666 | unsigned N = FTI.getNumExceptions(); | |||
4667 | DynamicExceptions.reserve(N); | |||
4668 | DynamicExceptionRanges.reserve(N); | |||
4669 | for (unsigned I = 0; I != N; ++I) { | |||
4670 | DynamicExceptions.push_back(FTI.Exceptions[I].Ty); | |||
4671 | DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); | |||
4672 | } | |||
4673 | } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { | |||
4674 | NoexceptExpr = FTI.NoexceptExpr; | |||
4675 | } | |||
4676 | ||||
4677 | S.checkExceptionSpecification(D.isFunctionDeclarationContext(), | |||
4678 | FTI.getExceptionSpecType(), | |||
4679 | DynamicExceptions, | |||
4680 | DynamicExceptionRanges, | |||
4681 | NoexceptExpr, | |||
4682 | Exceptions, | |||
4683 | EPI.ExceptionSpec); | |||
4684 | ||||
4685 | T = Context.getFunctionType(T, ParamTys, EPI); | |||
4686 | } | |||
4687 | break; | |||
4688 | } | |||
4689 | case DeclaratorChunk::MemberPointer: { | |||
4690 | // The scope spec must refer to a class, or be dependent. | |||
4691 | CXXScopeSpec &SS = DeclType.Mem.Scope(); | |||
4692 | QualType ClsType; | |||
4693 | ||||
4694 | // Handle pointer nullability. | |||
4695 | inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, | |||
4696 | DeclType.EndLoc, DeclType.getAttrListRef()); | |||
4697 | ||||
4698 | if (SS.isInvalid()) { | |||
4699 | // Avoid emitting extra errors if we already errored on the scope. | |||
4700 | D.setInvalidType(true); | |||
4701 | } else if (S.isDependentScopeSpecifier(SS) || | |||
4702 | dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { | |||
4703 | NestedNameSpecifier *NNS = SS.getScopeRep(); | |||
4704 | NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); | |||
4705 | switch (NNS->getKind()) { | |||
4706 | case NestedNameSpecifier::Identifier: | |||
4707 | ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, | |||
4708 | NNS->getAsIdentifier()); | |||
4709 | break; | |||
4710 | ||||
4711 | case NestedNameSpecifier::Namespace: | |||
4712 | case NestedNameSpecifier::NamespaceAlias: | |||
4713 | case NestedNameSpecifier::Global: | |||
4714 | case NestedNameSpecifier::Super: | |||
4715 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 4715); | |||
4716 | ||||
4717 | case NestedNameSpecifier::TypeSpec: | |||
4718 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
4719 | ClsType = QualType(NNS->getAsType(), 0); | |||
4720 | // Note: if the NNS has a prefix and ClsType is a nondependent | |||
4721 | // TemplateSpecializationType, then the NNS prefix is NOT included | |||
4722 | // in ClsType; hence we wrap ClsType into an ElaboratedType. | |||
4723 | // NOTE: in particular, no wrap occurs if ClsType already is an | |||
4724 | // Elaborated, DependentName, or DependentTemplateSpecialization. | |||
4725 | if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) | |||
4726 | ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); | |||
4727 | break; | |||
4728 | } | |||
4729 | } else { | |||
4730 | S.Diag(DeclType.Mem.Scope().getBeginLoc(), | |||
4731 | diag::err_illegal_decl_mempointer_in_nonclass) | |||
4732 | << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") | |||
4733 | << DeclType.Mem.Scope().getRange(); | |||
4734 | D.setInvalidType(true); | |||
4735 | } | |||
4736 | ||||
4737 | if (!ClsType.isNull()) | |||
4738 | T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, | |||
4739 | D.getIdentifier()); | |||
4740 | if (T.isNull()) { | |||
4741 | T = Context.IntTy; | |||
4742 | D.setInvalidType(true); | |||
4743 | } else if (DeclType.Mem.TypeQuals) { | |||
4744 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); | |||
4745 | } | |||
4746 | break; | |||
4747 | } | |||
4748 | ||||
4749 | case DeclaratorChunk::Pipe: { | |||
4750 | T = S.BuildReadPipeType(T, DeclType.Loc); | |||
4751 | processTypeAttrs(state, T, TAL_DeclSpec, | |||
4752 | D.getDeclSpec().getAttributes().getList()); | |||
4753 | break; | |||
4754 | } | |||
4755 | } | |||
4756 | ||||
4757 | if (T.isNull()) { | |||
4758 | D.setInvalidType(true); | |||
4759 | T = Context.IntTy; | |||
4760 | } | |||
4761 | ||||
4762 | // See if there are any attributes on this declarator chunk. | |||
4763 | processTypeAttrs(state, T, TAL_DeclChunk, | |||
4764 | const_cast<AttributeList *>(DeclType.getAttrs())); | |||
4765 | } | |||
4766 | ||||
4767 | // GNU warning -Wstrict-prototypes | |||
4768 | // Warn if a function declaration is without a prototype. | |||
4769 | // This warning is issued for all kinds of unprototyped function | |||
4770 | // declarations (i.e. function type typedef, function pointer etc.) | |||
4771 | // C99 6.7.5.3p14: | |||
4772 | // The empty list in a function declarator that is not part of a definition | |||
4773 | // of that function specifies that no information about the number or types | |||
4774 | // of the parameters is supplied. | |||
4775 | if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) { | |||
4776 | bool IsBlock = false; | |||
4777 | for (const DeclaratorChunk &DeclType : D.type_objects()) { | |||
4778 | switch (DeclType.Kind) { | |||
4779 | case DeclaratorChunk::BlockPointer: | |||
4780 | IsBlock = true; | |||
4781 | break; | |||
4782 | case DeclaratorChunk::Function: { | |||
4783 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
4784 | if (FTI.NumParams == 0 && !FTI.isVariadic) | |||
4785 | S.Diag(DeclType.Loc, diag::warn_strict_prototypes) | |||
4786 | << IsBlock | |||
4787 | << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); | |||
4788 | IsBlock = false; | |||
4789 | break; | |||
4790 | } | |||
4791 | default: | |||
4792 | break; | |||
4793 | } | |||
4794 | } | |||
4795 | } | |||
4796 | ||||
4797 | assert(!T.isNull() && "T must not be null after this point")(static_cast <bool> (!T.isNull() && "T must not be null after this point" ) ? void (0) : __assert_fail ("!T.isNull() && \"T must not be null after this point\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 4797, __extension__ __PRETTY_FUNCTION__)); | |||
4798 | ||||
4799 | if (LangOpts.CPlusPlus && T->isFunctionType()) { | |||
4800 | const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); | |||
4801 | assert(FnTy && "Why oh why is there not a FunctionProtoType here?")(static_cast <bool> (FnTy && "Why oh why is there not a FunctionProtoType here?" ) ? void (0) : __assert_fail ("FnTy && \"Why oh why is there not a FunctionProtoType here?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 4801, __extension__ __PRETTY_FUNCTION__)); | |||
4802 | ||||
4803 | // C++ 8.3.5p4: | |||
4804 | // A cv-qualifier-seq shall only be part of the function type | |||
4805 | // for a nonstatic member function, the function type to which a pointer | |||
4806 | // to member refers, or the top-level function type of a function typedef | |||
4807 | // declaration. | |||
4808 | // | |||
4809 | // Core issue 547 also allows cv-qualifiers on function types that are | |||
4810 | // top-level template type arguments. | |||
4811 | enum { NonMember, Member, DeductionGuide } Kind = NonMember; | |||
4812 | if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) | |||
4813 | Kind = DeductionGuide; | |||
4814 | else if (!D.getCXXScopeSpec().isSet()) { | |||
4815 | if ((D.getContext() == DeclaratorContext::MemberContext || | |||
4816 | D.getContext() == DeclaratorContext::LambdaExprContext) && | |||
4817 | !D.getDeclSpec().isFriendSpecified()) | |||
4818 | Kind = Member; | |||
4819 | } else { | |||
4820 | DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); | |||
4821 | if (!DC || DC->isRecord()) | |||
4822 | Kind = Member; | |||
4823 | } | |||
4824 | ||||
4825 | // C++11 [dcl.fct]p6 (w/DR1417): | |||
4826 | // An attempt to specify a function type with a cv-qualifier-seq or a | |||
4827 | // ref-qualifier (including by typedef-name) is ill-formed unless it is: | |||
4828 | // - the function type for a non-static member function, | |||
4829 | // - the function type to which a pointer to member refers, | |||
4830 | // - the top-level function type of a function typedef declaration or | |||
4831 | // alias-declaration, | |||
4832 | // - the type-id in the default argument of a type-parameter, or | |||
4833 | // - the type-id of a template-argument for a type-parameter | |||
4834 | // | |||
4835 | // FIXME: Checking this here is insufficient. We accept-invalid on: | |||
4836 | // | |||
4837 | // template<typename T> struct S { void f(T); }; | |||
4838 | // S<int() const> s; | |||
4839 | // | |||
4840 | // ... for instance. | |||
4841 | if (IsQualifiedFunction && | |||
4842 | !(Kind == Member && | |||
4843 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && | |||
4844 | !IsTypedefName && | |||
4845 | D.getContext() != DeclaratorContext::TemplateArgContext && | |||
4846 | D.getContext() != DeclaratorContext::TemplateTypeArgContext) { | |||
4847 | SourceLocation Loc = D.getLocStart(); | |||
4848 | SourceRange RemovalRange; | |||
4849 | unsigned I; | |||
4850 | if (D.isFunctionDeclarator(I)) { | |||
4851 | SmallVector<SourceLocation, 4> RemovalLocs; | |||
4852 | const DeclaratorChunk &Chunk = D.getTypeObject(I); | |||
4853 | assert(Chunk.Kind == DeclaratorChunk::Function)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Function ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 4853, __extension__ __PRETTY_FUNCTION__)); | |||
4854 | if (Chunk.Fun.hasRefQualifier()) | |||
4855 | RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); | |||
4856 | if (Chunk.Fun.TypeQuals & Qualifiers::Const) | |||
4857 | RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); | |||
4858 | if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) | |||
4859 | RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); | |||
4860 | if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) | |||
4861 | RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); | |||
4862 | if (!RemovalLocs.empty()) { | |||
4863 | std::sort(RemovalLocs.begin(), RemovalLocs.end(), | |||
4864 | BeforeThanCompare<SourceLocation>(S.getSourceManager())); | |||
4865 | RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); | |||
4866 | Loc = RemovalLocs.front(); | |||
4867 | } | |||
4868 | } | |||
4869 | ||||
4870 | S.Diag(Loc, diag::err_invalid_qualified_function_type) | |||
4871 | << Kind << D.isFunctionDeclarator() << T | |||
4872 | << getFunctionQualifiersAsString(FnTy) | |||
4873 | << FixItHint::CreateRemoval(RemovalRange); | |||
4874 | ||||
4875 | // Strip the cv-qualifiers and ref-qualifiers from the type. | |||
4876 | FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); | |||
4877 | EPI.TypeQuals = 0; | |||
4878 | EPI.RefQualifier = RQ_None; | |||
4879 | ||||
4880 | T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), | |||
4881 | EPI); | |||
4882 | // Rebuild any parens around the identifier in the function type. | |||
4883 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
4884 | if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) | |||
4885 | break; | |||
4886 | T = S.BuildParenType(T); | |||
4887 | } | |||
4888 | } | |||
4889 | } | |||
4890 | ||||
4891 | // Apply any undistributed attributes from the declarator. | |||
4892 | processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); | |||
4893 | ||||
4894 | // Diagnose any ignored type attributes. | |||
4895 | state.diagnoseIgnoredTypeAttrs(T); | |||
4896 | ||||
4897 | // C++0x [dcl.constexpr]p9: | |||
4898 | // A constexpr specifier used in an object declaration declares the object | |||
4899 | // as const. | |||
4900 | if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { | |||
4901 | T.addConst(); | |||
4902 | } | |||
4903 | ||||
4904 | // If there was an ellipsis in the declarator, the declaration declares a | |||
4905 | // parameter pack whose type may be a pack expansion type. | |||
4906 | if (D.hasEllipsis()) { | |||
4907 | // C++0x [dcl.fct]p13: | |||
4908 | // A declarator-id or abstract-declarator containing an ellipsis shall | |||
4909 | // only be used in a parameter-declaration. Such a parameter-declaration | |||
4910 | // is a parameter pack (14.5.3). [...] | |||
4911 | switch (D.getContext()) { | |||
4912 | case DeclaratorContext::PrototypeContext: | |||
4913 | case DeclaratorContext::LambdaExprParameterContext: | |||
4914 | // C++0x [dcl.fct]p13: | |||
4915 | // [...] When it is part of a parameter-declaration-clause, the | |||
4916 | // parameter pack is a function parameter pack (14.5.3). The type T | |||
4917 | // of the declarator-id of the function parameter pack shall contain | |||
4918 | // a template parameter pack; each template parameter pack in T is | |||
4919 | // expanded by the function parameter pack. | |||
4920 | // | |||
4921 | // We represent function parameter packs as function parameters whose | |||
4922 | // type is a pack expansion. | |||
4923 | if (!T->containsUnexpandedParameterPack()) { | |||
4924 | S.Diag(D.getEllipsisLoc(), | |||
4925 | diag::err_function_parameter_pack_without_parameter_packs) | |||
4926 | << T << D.getSourceRange(); | |||
4927 | D.setEllipsisLoc(SourceLocation()); | |||
4928 | } else { | |||
4929 | T = Context.getPackExpansionType(T, None); | |||
4930 | } | |||
4931 | break; | |||
4932 | case DeclaratorContext::TemplateParamContext: | |||
4933 | // C++0x [temp.param]p15: | |||
4934 | // If a template-parameter is a [...] is a parameter-declaration that | |||
4935 | // declares a parameter pack (8.3.5), then the template-parameter is a | |||
4936 | // template parameter pack (14.5.3). | |||
4937 | // | |||
4938 | // Note: core issue 778 clarifies that, if there are any unexpanded | |||
4939 | // parameter packs in the type of the non-type template parameter, then | |||
4940 | // it expands those parameter packs. | |||
4941 | if (T->containsUnexpandedParameterPack()) | |||
4942 | T = Context.getPackExpansionType(T, None); | |||
4943 | else | |||
4944 | S.Diag(D.getEllipsisLoc(), | |||
4945 | LangOpts.CPlusPlus11 | |||
4946 | ? diag::warn_cxx98_compat_variadic_templates | |||
4947 | : diag::ext_variadic_templates); | |||
4948 | break; | |||
4949 | ||||
4950 | case DeclaratorContext::FileContext: | |||
4951 | case DeclaratorContext::KNRTypeListContext: | |||
4952 | case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic | |||
4953 | // here? | |||
4954 | case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic | |||
4955 | // here? | |||
4956 | case DeclaratorContext::TypeNameContext: | |||
4957 | case DeclaratorContext::FunctionalCastContext: | |||
4958 | case DeclaratorContext::CXXNewContext: | |||
4959 | case DeclaratorContext::AliasDeclContext: | |||
4960 | case DeclaratorContext::AliasTemplateContext: | |||
4961 | case DeclaratorContext::MemberContext: | |||
4962 | case DeclaratorContext::BlockContext: | |||
4963 | case DeclaratorContext::ForContext: | |||
4964 | case DeclaratorContext::InitStmtContext: | |||
4965 | case DeclaratorContext::ConditionContext: | |||
4966 | case DeclaratorContext::CXXCatchContext: | |||
4967 | case DeclaratorContext::ObjCCatchContext: | |||
4968 | case DeclaratorContext::BlockLiteralContext: | |||
4969 | case DeclaratorContext::LambdaExprContext: | |||
4970 | case DeclaratorContext::ConversionIdContext: | |||
4971 | case DeclaratorContext::TrailingReturnContext: | |||
4972 | case DeclaratorContext::TrailingReturnVarContext: | |||
4973 | case DeclaratorContext::TemplateArgContext: | |||
4974 | case DeclaratorContext::TemplateTypeArgContext: | |||
4975 | // FIXME: We may want to allow parameter packs in block-literal contexts | |||
4976 | // in the future. | |||
4977 | S.Diag(D.getEllipsisLoc(), | |||
4978 | diag::err_ellipsis_in_declarator_not_parameter); | |||
4979 | D.setEllipsisLoc(SourceLocation()); | |||
4980 | break; | |||
4981 | } | |||
4982 | } | |||
4983 | ||||
4984 | assert(!T.isNull() && "T must not be null at the end of this function")(static_cast <bool> (!T.isNull() && "T must not be null at the end of this function" ) ? void (0) : __assert_fail ("!T.isNull() && \"T must not be null at the end of this function\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 4984, __extension__ __PRETTY_FUNCTION__)); | |||
4985 | if (D.isInvalidType()) | |||
4986 | return Context.getTrivialTypeSourceInfo(T); | |||
4987 | ||||
4988 | return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); | |||
4989 | } | |||
4990 | ||||
4991 | /// GetTypeForDeclarator - Convert the type for the specified | |||
4992 | /// declarator to Type instances. | |||
4993 | /// | |||
4994 | /// The result of this call will never be null, but the associated | |||
4995 | /// type may be a null type if there's an unrecoverable error. | |||
4996 | TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { | |||
4997 | // Determine the type of the declarator. Not all forms of declarator | |||
4998 | // have a type. | |||
4999 | ||||
5000 | TypeProcessingState state(*this, D); | |||
5001 | ||||
5002 | TypeSourceInfo *ReturnTypeInfo = nullptr; | |||
5003 | QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | |||
5004 | if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) | |||
5005 | inferARCWriteback(state, T); | |||
5006 | ||||
5007 | return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); | |||
5008 | } | |||
5009 | ||||
5010 | static void transferARCOwnershipToDeclSpec(Sema &S, | |||
5011 | QualType &declSpecTy, | |||
5012 | Qualifiers::ObjCLifetime ownership) { | |||
5013 | if (declSpecTy->isObjCRetainableType() && | |||
5014 | declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { | |||
5015 | Qualifiers qs; | |||
5016 | qs.addObjCLifetime(ownership); | |||
5017 | declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); | |||
5018 | } | |||
5019 | } | |||
5020 | ||||
5021 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | |||
5022 | Qualifiers::ObjCLifetime ownership, | |||
5023 | unsigned chunkIndex) { | |||
5024 | Sema &S = state.getSema(); | |||
5025 | Declarator &D = state.getDeclarator(); | |||
5026 | ||||
5027 | // Look for an explicit lifetime attribute. | |||
5028 | DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); | |||
5029 | for (const AttributeList *attr = chunk.getAttrs(); attr; | |||
5030 | attr = attr->getNext()) | |||
5031 | if (attr->getKind() == AttributeList::AT_ObjCOwnership) | |||
5032 | return; | |||
5033 | ||||
5034 | const char *attrStr = nullptr; | |||
5035 | switch (ownership) { | |||
5036 | case Qualifiers::OCL_None: llvm_unreachable("no ownership!")::llvm::llvm_unreachable_internal("no ownership!", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5036); | |||
5037 | case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; | |||
5038 | case Qualifiers::OCL_Strong: attrStr = "strong"; break; | |||
5039 | case Qualifiers::OCL_Weak: attrStr = "weak"; break; | |||
5040 | case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; | |||
5041 | } | |||
5042 | ||||
5043 | IdentifierLoc *Arg = new (S.Context) IdentifierLoc; | |||
5044 | Arg->Ident = &S.Context.Idents.get(attrStr); | |||
5045 | Arg->Loc = SourceLocation(); | |||
5046 | ||||
5047 | ArgsUnion Args(Arg); | |||
5048 | ||||
5049 | // If there wasn't one, add one (with an invalid source location | |||
5050 | // so that we don't make an AttributedType for it). | |||
5051 | AttributeList *attr = D.getAttributePool() | |||
5052 | .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), | |||
5053 | /*scope*/ nullptr, SourceLocation(), | |||
5054 | /*args*/ &Args, 1, AttributeList::AS_GNU); | |||
5055 | spliceAttrIntoList(*attr, chunk.getAttrListRef()); | |||
5056 | ||||
5057 | // TODO: mark whether we did this inference? | |||
5058 | } | |||
5059 | ||||
5060 | /// \brief Used for transferring ownership in casts resulting in l-values. | |||
5061 | static void transferARCOwnership(TypeProcessingState &state, | |||
5062 | QualType &declSpecTy, | |||
5063 | Qualifiers::ObjCLifetime ownership) { | |||
5064 | Sema &S = state.getSema(); | |||
5065 | Declarator &D = state.getDeclarator(); | |||
5066 | ||||
5067 | int inner = -1; | |||
5068 | bool hasIndirection = false; | |||
5069 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
5070 | DeclaratorChunk &chunk = D.getTypeObject(i); | |||
5071 | switch (chunk.Kind) { | |||
5072 | case DeclaratorChunk::Paren: | |||
5073 | // Ignore parens. | |||
5074 | break; | |||
5075 | ||||
5076 | case DeclaratorChunk::Array: | |||
5077 | case DeclaratorChunk::Reference: | |||
5078 | case DeclaratorChunk::Pointer: | |||
5079 | if (inner != -1) | |||
5080 | hasIndirection = true; | |||
5081 | inner = i; | |||
5082 | break; | |||
5083 | ||||
5084 | case DeclaratorChunk::BlockPointer: | |||
5085 | if (inner != -1) | |||
5086 | transferARCOwnershipToDeclaratorChunk(state, ownership, i); | |||
5087 | return; | |||
5088 | ||||
5089 | case DeclaratorChunk::Function: | |||
5090 | case DeclaratorChunk::MemberPointer: | |||
5091 | case DeclaratorChunk::Pipe: | |||
5092 | return; | |||
5093 | } | |||
5094 | } | |||
5095 | ||||
5096 | if (inner == -1) | |||
5097 | return; | |||
5098 | ||||
5099 | DeclaratorChunk &chunk = D.getTypeObject(inner); | |||
5100 | if (chunk.Kind == DeclaratorChunk::Pointer) { | |||
5101 | if (declSpecTy->isObjCRetainableType()) | |||
5102 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | |||
5103 | if (declSpecTy->isObjCObjectType() && hasIndirection) | |||
5104 | return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); | |||
5105 | } else { | |||
5106 | assert(chunk.Kind == DeclaratorChunk::Array ||(static_cast <bool> (chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference) ? void (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5107, __extension__ __PRETTY_FUNCTION__)) | |||
5107 | chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference) ? void (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5107, __extension__ __PRETTY_FUNCTION__)); | |||
5108 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | |||
5109 | } | |||
5110 | } | |||
5111 | ||||
5112 | TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { | |||
5113 | TypeProcessingState state(*this, D); | |||
5114 | ||||
5115 | TypeSourceInfo *ReturnTypeInfo = nullptr; | |||
5116 | QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | |||
5117 | ||||
5118 | if (getLangOpts().ObjC1) { | |||
5119 | Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); | |||
5120 | if (ownership != Qualifiers::OCL_None) | |||
5121 | transferARCOwnership(state, declSpecTy, ownership); | |||
5122 | } | |||
5123 | ||||
5124 | return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); | |||
5125 | } | |||
5126 | ||||
5127 | /// Map an AttributedType::Kind to an AttributeList::Kind. | |||
5128 | static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { | |||
5129 | switch (kind) { | |||
5130 | case AttributedType::attr_address_space: | |||
5131 | return AttributeList::AT_AddressSpace; | |||
5132 | case AttributedType::attr_regparm: | |||
5133 | return AttributeList::AT_Regparm; | |||
5134 | case AttributedType::attr_vector_size: | |||
5135 | return AttributeList::AT_VectorSize; | |||
5136 | case AttributedType::attr_neon_vector_type: | |||
5137 | return AttributeList::AT_NeonVectorType; | |||
5138 | case AttributedType::attr_neon_polyvector_type: | |||
5139 | return AttributeList::AT_NeonPolyVectorType; | |||
5140 | case AttributedType::attr_objc_gc: | |||
5141 | return AttributeList::AT_ObjCGC; | |||
5142 | case AttributedType::attr_objc_ownership: | |||
5143 | case AttributedType::attr_objc_inert_unsafe_unretained: | |||
5144 | return AttributeList::AT_ObjCOwnership; | |||
5145 | case AttributedType::attr_noreturn: | |||
5146 | return AttributeList::AT_NoReturn; | |||
5147 | case AttributedType::attr_cdecl: | |||
5148 | return AttributeList::AT_CDecl; | |||
5149 | case AttributedType::attr_fastcall: | |||
5150 | return AttributeList::AT_FastCall; | |||
5151 | case AttributedType::attr_stdcall: | |||
5152 | return AttributeList::AT_StdCall; | |||
5153 | case AttributedType::attr_thiscall: | |||
5154 | return AttributeList::AT_ThisCall; | |||
5155 | case AttributedType::attr_regcall: | |||
5156 | return AttributeList::AT_RegCall; | |||
5157 | case AttributedType::attr_pascal: | |||
5158 | return AttributeList::AT_Pascal; | |||
5159 | case AttributedType::attr_swiftcall: | |||
5160 | return AttributeList::AT_SwiftCall; | |||
5161 | case AttributedType::attr_vectorcall: | |||
5162 | return AttributeList::AT_VectorCall; | |||
5163 | case AttributedType::attr_pcs: | |||
5164 | case AttributedType::attr_pcs_vfp: | |||
5165 | return AttributeList::AT_Pcs; | |||
5166 | case AttributedType::attr_inteloclbicc: | |||
5167 | return AttributeList::AT_IntelOclBicc; | |||
5168 | case AttributedType::attr_ms_abi: | |||
5169 | return AttributeList::AT_MSABI; | |||
5170 | case AttributedType::attr_sysv_abi: | |||
5171 | return AttributeList::AT_SysVABI; | |||
5172 | case AttributedType::attr_preserve_most: | |||
5173 | return AttributeList::AT_PreserveMost; | |||
5174 | case AttributedType::attr_preserve_all: | |||
5175 | return AttributeList::AT_PreserveAll; | |||
5176 | case AttributedType::attr_ptr32: | |||
5177 | return AttributeList::AT_Ptr32; | |||
5178 | case AttributedType::attr_ptr64: | |||
5179 | return AttributeList::AT_Ptr64; | |||
5180 | case AttributedType::attr_sptr: | |||
5181 | return AttributeList::AT_SPtr; | |||
5182 | case AttributedType::attr_uptr: | |||
5183 | return AttributeList::AT_UPtr; | |||
5184 | case AttributedType::attr_nonnull: | |||
5185 | return AttributeList::AT_TypeNonNull; | |||
5186 | case AttributedType::attr_nullable: | |||
5187 | return AttributeList::AT_TypeNullable; | |||
5188 | case AttributedType::attr_null_unspecified: | |||
5189 | return AttributeList::AT_TypeNullUnspecified; | |||
5190 | case AttributedType::attr_objc_kindof: | |||
5191 | return AttributeList::AT_ObjCKindOf; | |||
5192 | case AttributedType::attr_ns_returns_retained: | |||
5193 | return AttributeList::AT_NSReturnsRetained; | |||
5194 | } | |||
5195 | llvm_unreachable("unexpected attribute kind!")::llvm::llvm_unreachable_internal("unexpected attribute kind!" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5195); | |||
5196 | } | |||
5197 | ||||
5198 | static void fillAttributedTypeLoc(AttributedTypeLoc TL, | |||
5199 | const AttributeList *attrs, | |||
5200 | const AttributeList *DeclAttrs = nullptr) { | |||
5201 | // DeclAttrs and attrs cannot be both empty. | |||
5202 | assert((attrs || DeclAttrs) &&(static_cast <bool> ((attrs || DeclAttrs) && "no type attributes in the expected location!" ) ? void (0) : __assert_fail ("(attrs || DeclAttrs) && \"no type attributes in the expected location!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5203, __extension__ __PRETTY_FUNCTION__)) | |||
5203 | "no type attributes in the expected location!")(static_cast <bool> ((attrs || DeclAttrs) && "no type attributes in the expected location!" ) ? void (0) : __assert_fail ("(attrs || DeclAttrs) && \"no type attributes in the expected location!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5203, __extension__ __PRETTY_FUNCTION__)); | |||
5204 | ||||
5205 | AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind()); | |||
5206 | // Try to search for an attribute of matching kind in attrs list. | |||
5207 | while (attrs && attrs->getKind() != parsedKind) | |||
5208 | attrs = attrs->getNext(); | |||
5209 | if (!attrs) { | |||
5210 | // No matching type attribute in attrs list found. | |||
5211 | // Try searching through C++11 attributes in the declarator attribute list. | |||
5212 | while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() || | |||
5213 | DeclAttrs->getKind() != parsedKind)) | |||
5214 | DeclAttrs = DeclAttrs->getNext(); | |||
5215 | attrs = DeclAttrs; | |||
5216 | } | |||
5217 | ||||
5218 | assert(attrs && "no matching type attribute in expected location!")(static_cast <bool> (attrs && "no matching type attribute in expected location!" ) ? void (0) : __assert_fail ("attrs && \"no matching type attribute in expected location!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5218, __extension__ __PRETTY_FUNCTION__)); | |||
5219 | ||||
5220 | TL.setAttrNameLoc(attrs->getLoc()); | |||
5221 | if (TL.hasAttrExprOperand()) { | |||
5222 | assert(attrs->isArgExpr(0) && "mismatched attribute operand kind")(static_cast <bool> (attrs->isArgExpr(0) && "mismatched attribute operand kind" ) ? void (0) : __assert_fail ("attrs->isArgExpr(0) && \"mismatched attribute operand kind\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5222, __extension__ __PRETTY_FUNCTION__)); | |||
5223 | TL.setAttrExprOperand(attrs->getArgAsExpr(0)); | |||
5224 | } else if (TL.hasAttrEnumOperand()) { | |||
5225 | assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&(static_cast <bool> ((attrs->isArgIdent(0) || attrs-> isArgExpr(0)) && "unexpected attribute operand kind") ? void (0) : __assert_fail ("(attrs->isArgIdent(0) || attrs->isArgExpr(0)) && \"unexpected attribute operand kind\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5226, __extension__ __PRETTY_FUNCTION__)) | |||
5226 | "unexpected attribute operand kind")(static_cast <bool> ((attrs->isArgIdent(0) || attrs-> isArgExpr(0)) && "unexpected attribute operand kind") ? void (0) : __assert_fail ("(attrs->isArgIdent(0) || attrs->isArgExpr(0)) && \"unexpected attribute operand kind\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5226, __extension__ __PRETTY_FUNCTION__)); | |||
5227 | if (attrs->isArgIdent(0)) | |||
5228 | TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc); | |||
5229 | else | |||
5230 | TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc()); | |||
5231 | } | |||
5232 | ||||
5233 | // FIXME: preserve this information to here. | |||
5234 | if (TL.hasAttrOperand()) | |||
5235 | TL.setAttrOperandParensRange(SourceRange()); | |||
5236 | } | |||
5237 | ||||
5238 | namespace { | |||
5239 | class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { | |||
5240 | ASTContext &Context; | |||
5241 | const DeclSpec &DS; | |||
5242 | ||||
5243 | public: | |||
5244 | TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) | |||
5245 | : Context(Context), DS(DS) {} | |||
5246 | ||||
5247 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | |||
5248 | fillAttributedTypeLoc(TL, DS.getAttributes().getList()); | |||
5249 | Visit(TL.getModifiedLoc()); | |||
5250 | } | |||
5251 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | |||
5252 | Visit(TL.getUnqualifiedLoc()); | |||
5253 | } | |||
5254 | void VisitTypedefTypeLoc(TypedefTypeLoc TL) { | |||
5255 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
5256 | } | |||
5257 | void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { | |||
5258 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
5259 | // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires | |||
5260 | // addition field. What we have is good enough for dispay of location | |||
5261 | // of 'fixit' on interface name. | |||
5262 | TL.setNameEndLoc(DS.getLocEnd()); | |||
5263 | } | |||
5264 | void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { | |||
5265 | TypeSourceInfo *RepTInfo = nullptr; | |||
5266 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | |||
5267 | TL.copy(RepTInfo->getTypeLoc()); | |||
5268 | } | |||
5269 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | |||
5270 | TypeSourceInfo *RepTInfo = nullptr; | |||
5271 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | |||
5272 | TL.copy(RepTInfo->getTypeLoc()); | |||
5273 | } | |||
5274 | void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { | |||
5275 | TypeSourceInfo *TInfo = nullptr; | |||
5276 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5277 | ||||
5278 | // If we got no declarator info from previous Sema routines, | |||
5279 | // just fill with the typespec loc. | |||
5280 | if (!TInfo) { | |||
5281 | TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); | |||
5282 | return; | |||
5283 | } | |||
5284 | ||||
5285 | TypeLoc OldTL = TInfo->getTypeLoc(); | |||
5286 | if (TInfo->getType()->getAs<ElaboratedType>()) { | |||
5287 | ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); | |||
5288 | TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() | |||
5289 | .castAs<TemplateSpecializationTypeLoc>(); | |||
5290 | TL.copy(NamedTL); | |||
5291 | } else { | |||
5292 | TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); | |||
5293 | assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc())(static_cast <bool> (TL.getRAngleLoc() == OldTL.castAs< TemplateSpecializationTypeLoc>().getRAngleLoc()) ? void (0 ) : __assert_fail ("TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5293, __extension__ __PRETTY_FUNCTION__)); | |||
5294 | } | |||
5295 | ||||
5296 | } | |||
5297 | void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { | |||
5298 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_typeofExpr) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofExpr" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5298, __extension__ __PRETTY_FUNCTION__)); | |||
5299 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | |||
5300 | TL.setParensRange(DS.getTypeofParensRange()); | |||
5301 | } | |||
5302 | void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { | |||
5303 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_typeofType) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofType" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5303, __extension__ __PRETTY_FUNCTION__)); | |||
5304 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | |||
5305 | TL.setParensRange(DS.getTypeofParensRange()); | |||
5306 | assert(DS.getRepAsType())(static_cast <bool> (DS.getRepAsType()) ? void (0) : __assert_fail ("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5306, __extension__ __PRETTY_FUNCTION__)); | |||
5307 | TypeSourceInfo *TInfo = nullptr; | |||
5308 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5309 | TL.setUnderlyingTInfo(TInfo); | |||
5310 | } | |||
5311 | void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { | |||
5312 | // FIXME: This holds only because we only have one unary transform. | |||
5313 | assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_underlyingType) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_underlyingType" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5313, __extension__ __PRETTY_FUNCTION__)); | |||
5314 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
5315 | TL.setParensRange(DS.getTypeofParensRange()); | |||
5316 | assert(DS.getRepAsType())(static_cast <bool> (DS.getRepAsType()) ? void (0) : __assert_fail ("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5316, __extension__ __PRETTY_FUNCTION__)); | |||
5317 | TypeSourceInfo *TInfo = nullptr; | |||
5318 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5319 | TL.setUnderlyingTInfo(TInfo); | |||
5320 | } | |||
5321 | void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { | |||
5322 | // By default, use the source location of the type specifier. | |||
5323 | TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); | |||
5324 | if (TL.needsExtraLocalData()) { | |||
5325 | // Set info for the written builtin specifiers. | |||
5326 | TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); | |||
5327 | // Try to have a meaningful source location. | |||
5328 | if (TL.getWrittenSignSpec() != TSS_unspecified) | |||
5329 | TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); | |||
5330 | if (TL.getWrittenWidthSpec() != TSW_unspecified) | |||
5331 | TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); | |||
5332 | } | |||
5333 | } | |||
5334 | void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { | |||
5335 | ElaboratedTypeKeyword Keyword | |||
5336 | = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); | |||
5337 | if (DS.getTypeSpecType() == TST_typename) { | |||
5338 | TypeSourceInfo *TInfo = nullptr; | |||
5339 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5340 | if (TInfo) { | |||
5341 | TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); | |||
5342 | return; | |||
5343 | } | |||
5344 | } | |||
5345 | TL.setElaboratedKeywordLoc(Keyword != ETK_None | |||
5346 | ? DS.getTypeSpecTypeLoc() | |||
5347 | : SourceLocation()); | |||
5348 | const CXXScopeSpec& SS = DS.getTypeSpecScope(); | |||
5349 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
5350 | Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); | |||
5351 | } | |||
5352 | void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { | |||
5353 | assert(DS.getTypeSpecType() == TST_typename)(static_cast <bool> (DS.getTypeSpecType() == TST_typename ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5353, __extension__ __PRETTY_FUNCTION__)); | |||
5354 | TypeSourceInfo *TInfo = nullptr; | |||
5355 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5356 | assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail ( "TInfo", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5356, __extension__ __PRETTY_FUNCTION__)); | |||
5357 | TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); | |||
5358 | } | |||
5359 | void VisitDependentTemplateSpecializationTypeLoc( | |||
5360 | DependentTemplateSpecializationTypeLoc TL) { | |||
5361 | assert(DS.getTypeSpecType() == TST_typename)(static_cast <bool> (DS.getTypeSpecType() == TST_typename ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5361, __extension__ __PRETTY_FUNCTION__)); | |||
5362 | TypeSourceInfo *TInfo = nullptr; | |||
5363 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5364 | assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail ( "TInfo", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5364, __extension__ __PRETTY_FUNCTION__)); | |||
5365 | TL.copy( | |||
5366 | TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); | |||
5367 | } | |||
5368 | void VisitTagTypeLoc(TagTypeLoc TL) { | |||
5369 | TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); | |||
5370 | } | |||
5371 | void VisitAtomicTypeLoc(AtomicTypeLoc TL) { | |||
5372 | // An AtomicTypeLoc can come from either an _Atomic(...) type specifier | |||
5373 | // or an _Atomic qualifier. | |||
5374 | if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { | |||
5375 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
5376 | TL.setParensRange(DS.getTypeofParensRange()); | |||
5377 | ||||
5378 | TypeSourceInfo *TInfo = nullptr; | |||
5379 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5380 | assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail ( "TInfo", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5380, __extension__ __PRETTY_FUNCTION__)); | |||
5381 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | |||
5382 | } else { | |||
5383 | TL.setKWLoc(DS.getAtomicSpecLoc()); | |||
5384 | // No parens, to indicate this was spelled as an _Atomic qualifier. | |||
5385 | TL.setParensRange(SourceRange()); | |||
5386 | Visit(TL.getValueLoc()); | |||
5387 | } | |||
5388 | } | |||
5389 | ||||
5390 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | |||
5391 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
5392 | ||||
5393 | TypeSourceInfo *TInfo = nullptr; | |||
5394 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5395 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | |||
5396 | } | |||
5397 | ||||
5398 | void VisitTypeLoc(TypeLoc TL) { | |||
5399 | // FIXME: add other typespec types and change this to an assert. | |||
5400 | TL.initialize(Context, DS.getTypeSpecTypeLoc()); | |||
5401 | } | |||
5402 | }; | |||
5403 | ||||
5404 | class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { | |||
5405 | ASTContext &Context; | |||
5406 | const DeclaratorChunk &Chunk; | |||
5407 | ||||
5408 | public: | |||
5409 | DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) | |||
5410 | : Context(Context), Chunk(Chunk) {} | |||
5411 | ||||
5412 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | |||
5413 | llvm_unreachable("qualified type locs not expected here!")::llvm::llvm_unreachable_internal("qualified type locs not expected here!" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5413); | |||
5414 | } | |||
5415 | void VisitDecayedTypeLoc(DecayedTypeLoc TL) { | |||
5416 | llvm_unreachable("decayed type locs not expected here!")::llvm::llvm_unreachable_internal("decayed type locs not expected here!" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5416); | |||
5417 | } | |||
5418 | ||||
5419 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | |||
5420 | fillAttributedTypeLoc(TL, Chunk.getAttrs()); | |||
5421 | } | |||
5422 | void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { | |||
5423 | // nothing | |||
5424 | } | |||
5425 | void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { | |||
5426 | assert(Chunk.Kind == DeclaratorChunk::BlockPointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::BlockPointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::BlockPointer" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5426, __extension__ __PRETTY_FUNCTION__)); | |||
5427 | TL.setCaretLoc(Chunk.Loc); | |||
5428 | } | |||
5429 | void VisitPointerTypeLoc(PointerTypeLoc TL) { | |||
5430 | assert(Chunk.Kind == DeclaratorChunk::Pointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5430, __extension__ __PRETTY_FUNCTION__)); | |||
5431 | TL.setStarLoc(Chunk.Loc); | |||
5432 | } | |||
5433 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | |||
5434 | assert(Chunk.Kind == DeclaratorChunk::Pointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5434, __extension__ __PRETTY_FUNCTION__)); | |||
5435 | TL.setStarLoc(Chunk.Loc); | |||
5436 | } | |||
5437 | void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { | |||
5438 | assert(Chunk.Kind == DeclaratorChunk::MemberPointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::MemberPointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::MemberPointer" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5438, __extension__ __PRETTY_FUNCTION__)); | |||
5439 | const CXXScopeSpec& SS = Chunk.Mem.Scope(); | |||
5440 | NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); | |||
5441 | ||||
5442 | const Type* ClsTy = TL.getClass(); | |||
5443 | QualType ClsQT = QualType(ClsTy, 0); | |||
5444 | TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); | |||
5445 | // Now copy source location info into the type loc component. | |||
5446 | TypeLoc ClsTL = ClsTInfo->getTypeLoc(); | |||
5447 | switch (NNSLoc.getNestedNameSpecifier()->getKind()) { | |||
5448 | case NestedNameSpecifier::Identifier: | |||
5449 | assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc")(static_cast <bool> (isa<DependentNameType>(ClsTy ) && "Unexpected TypeLoc") ? void (0) : __assert_fail ("isa<DependentNameType>(ClsTy) && \"Unexpected TypeLoc\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5449, __extension__ __PRETTY_FUNCTION__)); | |||
5450 | { | |||
5451 | DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); | |||
5452 | DNTLoc.setElaboratedKeywordLoc(SourceLocation()); | |||
5453 | DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); | |||
5454 | DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); | |||
5455 | } | |||
5456 | break; | |||
5457 | ||||
5458 | case NestedNameSpecifier::TypeSpec: | |||
5459 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
5460 | if (isa<ElaboratedType>(ClsTy)) { | |||
5461 | ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); | |||
5462 | ETLoc.setElaboratedKeywordLoc(SourceLocation()); | |||
5463 | ETLoc.setQualifierLoc(NNSLoc.getPrefix()); | |||
5464 | TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); | |||
5465 | NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); | |||
5466 | } else { | |||
5467 | ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); | |||
5468 | } | |||
5469 | break; | |||
5470 | ||||
5471 | case NestedNameSpecifier::Namespace: | |||
5472 | case NestedNameSpecifier::NamespaceAlias: | |||
5473 | case NestedNameSpecifier::Global: | |||
5474 | case NestedNameSpecifier::Super: | |||
5475 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5475); | |||
5476 | } | |||
5477 | ||||
5478 | // Finally fill in MemberPointerLocInfo fields. | |||
5479 | TL.setStarLoc(Chunk.Loc); | |||
5480 | TL.setClassTInfo(ClsTInfo); | |||
5481 | } | |||
5482 | void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { | |||
5483 | assert(Chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Reference ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5483, __extension__ __PRETTY_FUNCTION__)); | |||
5484 | // 'Amp' is misleading: this might have been originally | |||
5485 | /// spelled with AmpAmp. | |||
5486 | TL.setAmpLoc(Chunk.Loc); | |||
5487 | } | |||
5488 | void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { | |||
5489 | assert(Chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Reference ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5489, __extension__ __PRETTY_FUNCTION__)); | |||
5490 | assert(!Chunk.Ref.LValueRef)(static_cast <bool> (!Chunk.Ref.LValueRef) ? void (0) : __assert_fail ("!Chunk.Ref.LValueRef", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5490, __extension__ __PRETTY_FUNCTION__)); | |||
5491 | TL.setAmpAmpLoc(Chunk.Loc); | |||
5492 | } | |||
5493 | void VisitArrayTypeLoc(ArrayTypeLoc TL) { | |||
5494 | assert(Chunk.Kind == DeclaratorChunk::Array)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Array ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Array" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5494, __extension__ __PRETTY_FUNCTION__)); | |||
5495 | TL.setLBracketLoc(Chunk.Loc); | |||
5496 | TL.setRBracketLoc(Chunk.EndLoc); | |||
5497 | TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); | |||
5498 | } | |||
5499 | void VisitFunctionTypeLoc(FunctionTypeLoc TL) { | |||
5500 | assert(Chunk.Kind == DeclaratorChunk::Function)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Function ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5500, __extension__ __PRETTY_FUNCTION__)); | |||
5501 | TL.setLocalRangeBegin(Chunk.Loc); | |||
5502 | TL.setLocalRangeEnd(Chunk.EndLoc); | |||
5503 | ||||
5504 | const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; | |||
5505 | TL.setLParenLoc(FTI.getLParenLoc()); | |||
5506 | TL.setRParenLoc(FTI.getRParenLoc()); | |||
5507 | for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { | |||
5508 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
5509 | TL.setParam(tpi++, Param); | |||
5510 | } | |||
5511 | TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); | |||
5512 | } | |||
5513 | void VisitParenTypeLoc(ParenTypeLoc TL) { | |||
5514 | assert(Chunk.Kind == DeclaratorChunk::Paren)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Paren ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Paren" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5514, __extension__ __PRETTY_FUNCTION__)); | |||
5515 | TL.setLParenLoc(Chunk.Loc); | |||
5516 | TL.setRParenLoc(Chunk.EndLoc); | |||
5517 | } | |||
5518 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | |||
5519 | assert(Chunk.Kind == DeclaratorChunk::Pipe)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pipe ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pipe" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5519, __extension__ __PRETTY_FUNCTION__)); | |||
5520 | TL.setKWLoc(Chunk.Loc); | |||
5521 | } | |||
5522 | ||||
5523 | void VisitTypeLoc(TypeLoc TL) { | |||
5524 | llvm_unreachable("unsupported TypeLoc kind in declarator!")::llvm::llvm_unreachable_internal("unsupported TypeLoc kind in declarator!" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5524); | |||
5525 | } | |||
5526 | }; | |||
5527 | } // end anonymous namespace | |||
5528 | ||||
5529 | static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { | |||
5530 | SourceLocation Loc; | |||
5531 | switch (Chunk.Kind) { | |||
5532 | case DeclaratorChunk::Function: | |||
5533 | case DeclaratorChunk::Array: | |||
5534 | case DeclaratorChunk::Paren: | |||
5535 | case DeclaratorChunk::Pipe: | |||
5536 | llvm_unreachable("cannot be _Atomic qualified")::llvm::llvm_unreachable_internal("cannot be _Atomic qualified" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5536); | |||
5537 | ||||
5538 | case DeclaratorChunk::Pointer: | |||
5539 | Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); | |||
5540 | break; | |||
5541 | ||||
5542 | case DeclaratorChunk::BlockPointer: | |||
5543 | case DeclaratorChunk::Reference: | |||
5544 | case DeclaratorChunk::MemberPointer: | |||
5545 | // FIXME: Provide a source location for the _Atomic keyword. | |||
5546 | break; | |||
5547 | } | |||
5548 | ||||
5549 | ATL.setKWLoc(Loc); | |||
5550 | ATL.setParensRange(SourceRange()); | |||
5551 | } | |||
5552 | ||||
5553 | static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, | |||
5554 | const AttributeList *Attrs) { | |||
5555 | while (Attrs && Attrs->getKind() != AttributeList::AT_AddressSpace) | |||
5556 | Attrs = Attrs->getNext(); | |||
5557 | ||||
5558 | assert(Attrs && "no address_space attribute found at the expected location!")(static_cast <bool> (Attrs && "no address_space attribute found at the expected location!" ) ? void (0) : __assert_fail ("Attrs && \"no address_space attribute found at the expected location!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5558, __extension__ __PRETTY_FUNCTION__)); | |||
5559 | ||||
5560 | DASTL.setAttrNameLoc(Attrs->getLoc()); | |||
5561 | DASTL.setAttrExprOperand(Attrs->getArgAsExpr(0)); | |||
5562 | DASTL.setAttrOperandParensRange(SourceRange()); | |||
5563 | } | |||
5564 | ||||
5565 | /// \brief Create and instantiate a TypeSourceInfo with type source information. | |||
5566 | /// | |||
5567 | /// \param T QualType referring to the type as written in source code. | |||
5568 | /// | |||
5569 | /// \param ReturnTypeInfo For declarators whose return type does not show | |||
5570 | /// up in the normal place in the declaration specifiers (such as a C++ | |||
5571 | /// conversion function), this pointer will refer to a type source information | |||
5572 | /// for that return type. | |||
5573 | TypeSourceInfo * | |||
5574 | Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, | |||
5575 | TypeSourceInfo *ReturnTypeInfo) { | |||
5576 | TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); | |||
5577 | UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); | |||
5578 | const AttributeList *DeclAttrs = D.getAttributes(); | |||
5579 | ||||
5580 | // Handle parameter packs whose type is a pack expansion. | |||
5581 | if (isa<PackExpansionType>(T)) { | |||
5582 | CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); | |||
5583 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | |||
5584 | } | |||
5585 | ||||
5586 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
5587 | ||||
5588 | if (DependentAddressSpaceTypeLoc DASTL = | |||
5589 | CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { | |||
5590 | fillDependentAddressSpaceTypeLoc(DASTL, D.getTypeObject(i).getAttrs()); | |||
5591 | CurrTL = DASTL.getPointeeTypeLoc().getUnqualifiedLoc(); | |||
5592 | } | |||
5593 | ||||
5594 | // An AtomicTypeLoc might be produced by an atomic qualifier in this | |||
5595 | // declarator chunk. | |||
5596 | if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { | |||
5597 | fillAtomicQualLoc(ATL, D.getTypeObject(i)); | |||
5598 | CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); | |||
5599 | } | |||
5600 | ||||
5601 | while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { | |||
5602 | fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs); | |||
5603 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
5604 | } | |||
5605 | ||||
5606 | // FIXME: Ordering here? | |||
5607 | while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) | |||
5608 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
5609 | ||||
5610 | DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); | |||
5611 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | |||
5612 | } | |||
5613 | ||||
5614 | // If we have different source information for the return type, use | |||
5615 | // that. This really only applies to C++ conversion functions. | |||
5616 | if (ReturnTypeInfo) { | |||
5617 | TypeLoc TL = ReturnTypeInfo->getTypeLoc(); | |||
5618 | assert(TL.getFullDataSize() == CurrTL.getFullDataSize())(static_cast <bool> (TL.getFullDataSize() == CurrTL.getFullDataSize ()) ? void (0) : __assert_fail ("TL.getFullDataSize() == CurrTL.getFullDataSize()" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5618, __extension__ __PRETTY_FUNCTION__)); | |||
5619 | memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); | |||
5620 | } else { | |||
5621 | TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); | |||
5622 | } | |||
5623 | ||||
5624 | return TInfo; | |||
5625 | } | |||
5626 | ||||
5627 | /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. | |||
5628 | ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { | |||
5629 | // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser | |||
5630 | // and Sema during declaration parsing. Try deallocating/caching them when | |||
5631 | // it's appropriate, instead of allocating them and keeping them around. | |||
5632 | LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), | |||
5633 | TypeAlignment); | |||
5634 | new (LocT) LocInfoType(T, TInfo); | |||
5635 | assert(LocT->getTypeClass() != T->getTypeClass() &&(static_cast <bool> (LocT->getTypeClass() != T->getTypeClass () && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? void (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5636, __extension__ __PRETTY_FUNCTION__)) | |||
5636 | "LocInfoType's TypeClass conflicts with an existing Type class")(static_cast <bool> (LocT->getTypeClass() != T->getTypeClass () && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? void (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5636, __extension__ __PRETTY_FUNCTION__)); | |||
5637 | return ParsedType::make(QualType(LocT, 0)); | |||
5638 | } | |||
5639 | ||||
5640 | void LocInfoType::getAsStringInternal(std::string &Str, | |||
5641 | const PrintingPolicy &Policy) const { | |||
5642 | 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-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5644) | |||
5643 | " 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-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5644) | |||
5644 | " 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-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5644); | |||
5645 | } | |||
5646 | ||||
5647 | TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { | |||
5648 | // C99 6.7.6: Type names have no identifier. This is already validated by | |||
5649 | // the parser. | |||
5650 | assert(D.getIdentifier() == nullptr &&(static_cast <bool> (D.getIdentifier() == nullptr && "Type name should have no identifier!") ? void (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5651, __extension__ __PRETTY_FUNCTION__)) | |||
5651 | "Type name should have no identifier!")(static_cast <bool> (D.getIdentifier() == nullptr && "Type name should have no identifier!") ? void (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5651, __extension__ __PRETTY_FUNCTION__)); | |||
5652 | ||||
5653 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
5654 | QualType T = TInfo->getType(); | |||
5655 | if (D.isInvalidType()) | |||
5656 | return true; | |||
5657 | ||||
5658 | // Make sure there are no unused decl attributes on the declarator. | |||
5659 | // We don't want to do this for ObjC parameters because we're going | |||
5660 | // to apply them to the actual parameter declaration. | |||
5661 | // Likewise, we don't want to do this for alias declarations, because | |||
5662 | // we are actually going to build a declaration from this eventually. | |||
5663 | if (D.getContext() != DeclaratorContext::ObjCParameterContext && | |||
5664 | D.getContext() != DeclaratorContext::AliasDeclContext && | |||
5665 | D.getContext() != DeclaratorContext::AliasTemplateContext) | |||
5666 | checkUnusedDeclAttributes(D); | |||
5667 | ||||
5668 | if (getLangOpts().CPlusPlus) { | |||
5669 | // Check that there are no default arguments (C++ only). | |||
5670 | CheckExtraCXXDefaultArguments(D); | |||
5671 | } | |||
5672 | ||||
5673 | return CreateParsedType(T, TInfo); | |||
5674 | } | |||
5675 | ||||
5676 | ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { | |||
5677 | QualType T = Context.getObjCInstanceType(); | |||
5678 | TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
5679 | return CreateParsedType(T, TInfo); | |||
5680 | } | |||
5681 | ||||
5682 | //===----------------------------------------------------------------------===// | |||
5683 | // Type Attribute Processing | |||
5684 | //===----------------------------------------------------------------------===// | |||
5685 | ||||
5686 | /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression | |||
5687 | /// is uninstantiated. If instantiated it will apply the appropriate address space | |||
5688 | /// to the type. This function allows dependent template variables to be used in | |||
5689 | /// conjunction with the address_space attribute | |||
5690 | QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, | |||
5691 | SourceLocation AttrLoc) { | |||
5692 | if (!AddrSpace->isValueDependent()) { | |||
5693 | ||||
5694 | // If this type is already address space qualified, reject it. | |||
5695 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified | |||
5696 | // by qualifiers for two or more different address spaces." | |||
5697 | if (T.getAddressSpace() != LangAS::Default) { | |||
5698 | Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | |||
5699 | return QualType(); | |||
5700 | } | |||
5701 | ||||
5702 | llvm::APSInt addrSpace(32); | |||
5703 | if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) { | |||
5704 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
5705 | << "'address_space'" << AANT_ArgumentIntegerConstant | |||
5706 | << AddrSpace->getSourceRange(); | |||
5707 | return QualType(); | |||
5708 | } | |||
5709 | ||||
5710 | // Bounds checking. | |||
5711 | if (addrSpace.isSigned()) { | |||
5712 | if (addrSpace.isNegative()) { | |||
5713 | Diag(AttrLoc, diag::err_attribute_address_space_negative) | |||
5714 | << AddrSpace->getSourceRange(); | |||
5715 | return QualType(); | |||
5716 | } | |||
5717 | addrSpace.setIsSigned(false); | |||
5718 | } | |||
5719 | ||||
5720 | llvm::APSInt max(addrSpace.getBitWidth()); | |||
5721 | max = | |||
5722 | Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; | |||
5723 | if (addrSpace > max) { | |||
5724 | Diag(AttrLoc, diag::err_attribute_address_space_too_high) | |||
5725 | << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); | |||
5726 | return QualType(); | |||
5727 | } | |||
5728 | ||||
5729 | LangAS ASIdx = | |||
5730 | getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); | |||
5731 | ||||
5732 | return Context.getAddrSpaceQualType(T, ASIdx); | |||
5733 | } | |||
5734 | ||||
5735 | // A check with similar intentions as checking if a type already has an | |||
5736 | // address space except for on a dependent types, basically if the | |||
5737 | // current type is already a DependentAddressSpaceType then its already | |||
5738 | // lined up to have another address space on it and we can't have | |||
5739 | // multiple address spaces on the one pointer indirection | |||
5740 | if (T->getAs<DependentAddressSpaceType>()) { | |||
5741 | Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | |||
5742 | return QualType(); | |||
5743 | } | |||
5744 | ||||
5745 | return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); | |||
5746 | } | |||
5747 | ||||
5748 | /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the | |||
5749 | /// specified type. The attribute contains 1 argument, the id of the address | |||
5750 | /// space for the type. | |||
5751 | static void HandleAddressSpaceTypeAttribute(QualType &Type, | |||
5752 | const AttributeList &Attr, Sema &S){ | |||
5753 | // If this type is already address space qualified, reject it. | |||
5754 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by | |||
5755 | // qualifiers for two or more different address spaces." | |||
5756 | if (Type.getAddressSpace() != LangAS::Default) { | |||
5757 | S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); | |||
5758 | Attr.setInvalid(); | |||
5759 | return; | |||
5760 | } | |||
5761 | ||||
5762 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be | |||
5763 | // qualified by an address-space qualifier." | |||
5764 | if (Type->isFunctionType()) { | |||
5765 | S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); | |||
5766 | Attr.setInvalid(); | |||
5767 | return; | |||
5768 | } | |||
5769 | ||||
5770 | LangAS ASIdx; | |||
5771 | if (Attr.getKind() == AttributeList::AT_AddressSpace) { | |||
5772 | ||||
5773 | // Check the attribute arguments. | |||
5774 | if (Attr.getNumArgs() != 1) { | |||
5775 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
5776 | << Attr.getName() << 1; | |||
5777 | Attr.setInvalid(); | |||
5778 | return; | |||
5779 | } | |||
5780 | ||||
5781 | Expr *ASArgExpr; | |||
5782 | if (Attr.isArgIdent(0)) { | |||
5783 | // Special case where the argument is a template id. | |||
5784 | CXXScopeSpec SS; | |||
5785 | SourceLocation TemplateKWLoc; | |||
5786 | UnqualifiedId id; | |||
5787 | id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); | |||
5788 | ||||
5789 | ExprResult AddrSpace = S.ActOnIdExpression( | |||
5790 | S.getCurScope(), SS, TemplateKWLoc, id, false, false); | |||
5791 | if (AddrSpace.isInvalid()) | |||
5792 | return; | |||
5793 | ||||
5794 | ASArgExpr = static_cast<Expr *>(AddrSpace.get()); | |||
5795 | } else { | |||
5796 | ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); | |||
5797 | } | |||
5798 | ||||
5799 | // Create the DependentAddressSpaceType or append an address space onto | |||
5800 | // the type. | |||
5801 | QualType T = S.BuildAddressSpaceAttr(Type, ASArgExpr, Attr.getLoc()); | |||
5802 | ||||
5803 | if (!T.isNull()) | |||
5804 | Type = T; | |||
5805 | else | |||
5806 | Attr.setInvalid(); | |||
5807 | } else { | |||
5808 | // The keyword-based type attributes imply which address space to use. | |||
5809 | switch (Attr.getKind()) { | |||
5810 | case AttributeList::AT_OpenCLGlobalAddressSpace: | |||
5811 | ASIdx = LangAS::opencl_global; break; | |||
5812 | case AttributeList::AT_OpenCLLocalAddressSpace: | |||
5813 | ASIdx = LangAS::opencl_local; break; | |||
5814 | case AttributeList::AT_OpenCLConstantAddressSpace: | |||
5815 | ASIdx = LangAS::opencl_constant; break; | |||
5816 | case AttributeList::AT_OpenCLGenericAddressSpace: | |||
5817 | ASIdx = LangAS::opencl_generic; break; | |||
5818 | case AttributeList::AT_OpenCLPrivateAddressSpace: | |||
5819 | ASIdx = LangAS::opencl_private; break; | |||
5820 | default: | |||
5821 | llvm_unreachable("Invalid address space")::llvm::llvm_unreachable_internal("Invalid address space", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5821); | |||
5822 | } | |||
5823 | ||||
5824 | Type = S.Context.getAddrSpaceQualType(Type, ASIdx); | |||
5825 | } | |||
5826 | } | |||
5827 | ||||
5828 | /// Does this type have a "direct" ownership qualifier? That is, | |||
5829 | /// is it written like "__strong id", as opposed to something like | |||
5830 | /// "typeof(foo)", where that happens to be strong? | |||
5831 | static bool hasDirectOwnershipQualifier(QualType type) { | |||
5832 | // Fast path: no qualifier at all. | |||
5833 | assert(type.getQualifiers().hasObjCLifetime())(static_cast <bool> (type.getQualifiers().hasObjCLifetime ()) ? void (0) : __assert_fail ("type.getQualifiers().hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 5833, __extension__ __PRETTY_FUNCTION__)); | |||
5834 | ||||
5835 | while (true) { | |||
5836 | // __strong id | |||
5837 | if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { | |||
5838 | if (attr->getAttrKind() == AttributedType::attr_objc_ownership) | |||
5839 | return true; | |||
5840 | ||||
5841 | type = attr->getModifiedType(); | |||
5842 | ||||
5843 | // X *__strong (...) | |||
5844 | } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { | |||
5845 | type = paren->getInnerType(); | |||
5846 | ||||
5847 | // That's it for things we want to complain about. In particular, | |||
5848 | // we do not want to look through typedefs, typeof(expr), | |||
5849 | // typeof(type), or any other way that the type is somehow | |||
5850 | // abstracted. | |||
5851 | } else { | |||
5852 | ||||
5853 | return false; | |||
5854 | } | |||
5855 | } | |||
5856 | } | |||
5857 | ||||
5858 | /// handleObjCOwnershipTypeAttr - Process an objc_ownership | |||
5859 | /// attribute on the specified type. | |||
5860 | /// | |||
5861 | /// Returns 'true' if the attribute was handled. | |||
5862 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | |||
5863 | AttributeList &attr, | |||
5864 | QualType &type) { | |||
5865 | bool NonObjCPointer = false; | |||
5866 | ||||
5867 | if (!type->isDependentType() && !type->isUndeducedType()) { | |||
5868 | if (const PointerType *ptr = type->getAs<PointerType>()) { | |||
5869 | QualType pointee = ptr->getPointeeType(); | |||
5870 | if (pointee->isObjCRetainableType() || pointee->isPointerType()) | |||
5871 | return false; | |||
5872 | // It is important not to lose the source info that there was an attribute | |||
5873 | // applied to non-objc pointer. We will create an attributed type but | |||
5874 | // its type will be the same as the original type. | |||
5875 | NonObjCPointer = true; | |||
5876 | } else if (!type->isObjCRetainableType()) { | |||
5877 | return false; | |||
5878 | } | |||
5879 | ||||
5880 | // Don't accept an ownership attribute in the declspec if it would | |||
5881 | // just be the return type of a block pointer. | |||
5882 | if (state.isProcessingDeclSpec()) { | |||
5883 | Declarator &D = state.getDeclarator(); | |||
5884 | if (maybeMovePastReturnType(D, D.getNumTypeObjects(), | |||
5885 | /*onlyBlockPointers=*/true)) | |||
5886 | return false; | |||
5887 | } | |||
5888 | } | |||
5889 | ||||
5890 | Sema &S = state.getSema(); | |||
5891 | SourceLocation AttrLoc = attr.getLoc(); | |||
5892 | if (AttrLoc.isMacroID()) | |||
5893 | AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; | |||
5894 | ||||
5895 | if (!attr.isArgIdent(0)) { | |||
5896 | S.Diag(AttrLoc, diag::err_attribute_argument_type) | |||
5897 | << attr.getName() << AANT_ArgumentString; | |||
5898 | attr.setInvalid(); | |||
5899 | return true; | |||
5900 | } | |||
5901 | ||||
5902 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | |||
5903 | Qualifiers::ObjCLifetime lifetime; | |||
5904 | if (II->isStr("none")) | |||
5905 | lifetime = Qualifiers::OCL_ExplicitNone; | |||
5906 | else if (II->isStr("strong")) | |||
5907 | lifetime = Qualifiers::OCL_Strong; | |||
5908 | else if (II->isStr("weak")) | |||
5909 | lifetime = Qualifiers::OCL_Weak; | |||
5910 | else if (II->isStr("autoreleasing")) | |||
5911 | lifetime = Qualifiers::OCL_Autoreleasing; | |||
5912 | else { | |||
5913 | S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) | |||
5914 | << attr.getName() << II; | |||
5915 | attr.setInvalid(); | |||
5916 | return true; | |||
5917 | } | |||
5918 | ||||
5919 | // Just ignore lifetime attributes other than __weak and __unsafe_unretained | |||
5920 | // outside of ARC mode. | |||
5921 | if (!S.getLangOpts().ObjCAutoRefCount && | |||
5922 | lifetime != Qualifiers::OCL_Weak && | |||
5923 | lifetime != Qualifiers::OCL_ExplicitNone) { | |||
5924 | return true; | |||
5925 | } | |||
5926 | ||||
5927 | SplitQualType underlyingType = type.split(); | |||
5928 | ||||
5929 | // Check for redundant/conflicting ownership qualifiers. | |||
5930 | if (Qualifiers::ObjCLifetime previousLifetime | |||
5931 | = type.getQualifiers().getObjCLifetime()) { | |||
5932 | // If it's written directly, that's an error. | |||
5933 | if (hasDirectOwnershipQualifier(type)) { | |||
5934 | S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) | |||
5935 | << type; | |||
5936 | return true; | |||
5937 | } | |||
5938 | ||||
5939 | // Otherwise, if the qualifiers actually conflict, pull sugar off | |||
5940 | // and remove the ObjCLifetime qualifiers. | |||
5941 | if (previousLifetime != lifetime) { | |||
5942 | // It's possible to have multiple local ObjCLifetime qualifiers. We | |||
5943 | // can't stop after we reach a type that is directly qualified. | |||
5944 | const Type *prevTy = nullptr; | |||
5945 | while (!prevTy || prevTy != underlyingType.Ty) { | |||
5946 | prevTy = underlyingType.Ty; | |||
5947 | underlyingType = underlyingType.getSingleStepDesugaredType(); | |||
5948 | } | |||
5949 | underlyingType.Quals.removeObjCLifetime(); | |||
5950 | } | |||
5951 | } | |||
5952 | ||||
5953 | underlyingType.Quals.addObjCLifetime(lifetime); | |||
5954 | ||||
5955 | if (NonObjCPointer) { | |||
5956 | StringRef name = attr.getName()->getName(); | |||
5957 | switch (lifetime) { | |||
5958 | case Qualifiers::OCL_None: | |||
5959 | case Qualifiers::OCL_ExplicitNone: | |||
5960 | break; | |||
5961 | case Qualifiers::OCL_Strong: name = "__strong"; break; | |||
5962 | case Qualifiers::OCL_Weak: name = "__weak"; break; | |||
5963 | case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; | |||
5964 | } | |||
5965 | S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name | |||
5966 | << TDS_ObjCObjOrBlock << type; | |||
5967 | } | |||
5968 | ||||
5969 | // Don't actually add the __unsafe_unretained qualifier in non-ARC files, | |||
5970 | // because having both 'T' and '__unsafe_unretained T' exist in the type | |||
5971 | // system causes unfortunate widespread consistency problems. (For example, | |||
5972 | // they're not considered compatible types, and we mangle them identicially | |||
5973 | // as template arguments.) These problems are all individually fixable, | |||
5974 | // but it's easier to just not add the qualifier and instead sniff it out | |||
5975 | // in specific places using isObjCInertUnsafeUnretainedType(). | |||
5976 | // | |||
5977 | // Doing this does means we miss some trivial consistency checks that | |||
5978 | // would've triggered in ARC, but that's better than trying to solve all | |||
5979 | // the coexistence problems with __unsafe_unretained. | |||
5980 | if (!S.getLangOpts().ObjCAutoRefCount && | |||
5981 | lifetime == Qualifiers::OCL_ExplicitNone) { | |||
5982 | type = S.Context.getAttributedType( | |||
5983 | AttributedType::attr_objc_inert_unsafe_unretained, | |||
5984 | type, type); | |||
5985 | return true; | |||
5986 | } | |||
5987 | ||||
5988 | QualType origType = type; | |||
5989 | if (!NonObjCPointer) | |||
5990 | type = S.Context.getQualifiedType(underlyingType); | |||
5991 | ||||
5992 | // If we have a valid source location for the attribute, use an | |||
5993 | // AttributedType instead. | |||
5994 | if (AttrLoc.isValid()) | |||
5995 | type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, | |||
5996 | origType, type); | |||
5997 | ||||
5998 | auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, | |||
5999 | unsigned diagnostic, QualType type) { | |||
6000 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | |||
6001 | S.DelayedDiagnostics.add( | |||
6002 | sema::DelayedDiagnostic::makeForbiddenType( | |||
6003 | S.getSourceManager().getExpansionLoc(loc), | |||
6004 | diagnostic, type, /*ignored*/ 0)); | |||
6005 | } else { | |||
6006 | S.Diag(loc, diagnostic); | |||
6007 | } | |||
6008 | }; | |||
6009 | ||||
6010 | // Sometimes, __weak isn't allowed. | |||
6011 | if (lifetime == Qualifiers::OCL_Weak && | |||
6012 | !S.getLangOpts().ObjCWeak && !NonObjCPointer) { | |||
6013 | ||||
6014 | // Use a specialized diagnostic if the runtime just doesn't support them. | |||
6015 | unsigned diagnostic = | |||
6016 | (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled | |||
6017 | : diag::err_arc_weak_no_runtime); | |||
6018 | ||||
6019 | // In any case, delay the diagnostic until we know what we're parsing. | |||
6020 | diagnoseOrDelay(S, AttrLoc, diagnostic, type); | |||
6021 | ||||
6022 | attr.setInvalid(); | |||
6023 | return true; | |||
6024 | } | |||
6025 | ||||
6026 | // Forbid __weak for class objects marked as | |||
6027 | // objc_arc_weak_reference_unavailable | |||
6028 | if (lifetime == Qualifiers::OCL_Weak) { | |||
6029 | if (const ObjCObjectPointerType *ObjT = | |||
6030 | type->getAs<ObjCObjectPointerType>()) { | |||
6031 | if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { | |||
6032 | if (Class->isArcWeakrefUnavailable()) { | |||
6033 | S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); | |||
6034 | S.Diag(ObjT->getInterfaceDecl()->getLocation(), | |||
6035 | diag::note_class_declared); | |||
6036 | } | |||
6037 | } | |||
6038 | } | |||
6039 | } | |||
6040 | ||||
6041 | return true; | |||
6042 | } | |||
6043 | ||||
6044 | /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type | |||
6045 | /// attribute on the specified type. Returns true to indicate that | |||
6046 | /// the attribute was handled, false to indicate that the type does | |||
6047 | /// not permit the attribute. | |||
6048 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, | |||
6049 | AttributeList &attr, | |||
6050 | QualType &type) { | |||
6051 | Sema &S = state.getSema(); | |||
6052 | ||||
6053 | // Delay if this isn't some kind of pointer. | |||
6054 | if (!type->isPointerType() && | |||
6055 | !type->isObjCObjectPointerType() && | |||
6056 | !type->isBlockPointerType()) | |||
6057 | return false; | |||
6058 | ||||
6059 | if (type.getObjCGCAttr() != Qualifiers::GCNone) { | |||
6060 | S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); | |||
6061 | attr.setInvalid(); | |||
6062 | return true; | |||
6063 | } | |||
6064 | ||||
6065 | // Check the attribute arguments. | |||
6066 | if (!attr.isArgIdent(0)) { | |||
6067 | S.Diag(attr.getLoc(), diag::err_attribute_argument_type) | |||
6068 | << attr.getName() << AANT_ArgumentString; | |||
6069 | attr.setInvalid(); | |||
6070 | return true; | |||
6071 | } | |||
6072 | Qualifiers::GC GCAttr; | |||
6073 | if (attr.getNumArgs() > 1) { | |||
6074 | S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
6075 | << attr.getName() << 1; | |||
6076 | attr.setInvalid(); | |||
6077 | return true; | |||
6078 | } | |||
6079 | ||||
6080 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | |||
6081 | if (II->isStr("weak")) | |||
6082 | GCAttr = Qualifiers::Weak; | |||
6083 | else if (II->isStr("strong")) | |||
6084 | GCAttr = Qualifiers::Strong; | |||
6085 | else { | |||
6086 | S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) | |||
6087 | << attr.getName() << II; | |||
6088 | attr.setInvalid(); | |||
6089 | return true; | |||
6090 | } | |||
6091 | ||||
6092 | QualType origType = type; | |||
6093 | type = S.Context.getObjCGCQualType(origType, GCAttr); | |||
6094 | ||||
6095 | // Make an attributed type to preserve the source information. | |||
6096 | if (attr.getLoc().isValid()) | |||
6097 | type = S.Context.getAttributedType(AttributedType::attr_objc_gc, | |||
6098 | origType, type); | |||
6099 | ||||
6100 | return true; | |||
6101 | } | |||
6102 | ||||
6103 | namespace { | |||
6104 | /// A helper class to unwrap a type down to a function for the | |||
6105 | /// purposes of applying attributes there. | |||
6106 | /// | |||
6107 | /// Use: | |||
6108 | /// FunctionTypeUnwrapper unwrapped(SemaRef, T); | |||
6109 | /// if (unwrapped.isFunctionType()) { | |||
6110 | /// const FunctionType *fn = unwrapped.get(); | |||
6111 | /// // change fn somehow | |||
6112 | /// T = unwrapped.wrap(fn); | |||
6113 | /// } | |||
6114 | struct FunctionTypeUnwrapper { | |||
6115 | enum WrapKind { | |||
6116 | Desugar, | |||
6117 | Attributed, | |||
6118 | Parens, | |||
6119 | Pointer, | |||
6120 | BlockPointer, | |||
6121 | Reference, | |||
6122 | MemberPointer | |||
6123 | }; | |||
6124 | ||||
6125 | QualType Original; | |||
6126 | const FunctionType *Fn; | |||
6127 | SmallVector<unsigned char /*WrapKind*/, 8> Stack; | |||
6128 | ||||
6129 | FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { | |||
6130 | while (true) { | |||
6131 | const Type *Ty = T.getTypePtr(); | |||
6132 | if (isa<FunctionType>(Ty)) { | |||
6133 | Fn = cast<FunctionType>(Ty); | |||
6134 | return; | |||
6135 | } else if (isa<ParenType>(Ty)) { | |||
6136 | T = cast<ParenType>(Ty)->getInnerType(); | |||
6137 | Stack.push_back(Parens); | |||
6138 | } else if (isa<PointerType>(Ty)) { | |||
6139 | T = cast<PointerType>(Ty)->getPointeeType(); | |||
6140 | Stack.push_back(Pointer); | |||
6141 | } else if (isa<BlockPointerType>(Ty)) { | |||
6142 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | |||
6143 | Stack.push_back(BlockPointer); | |||
6144 | } else if (isa<MemberPointerType>(Ty)) { | |||
6145 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | |||
6146 | Stack.push_back(MemberPointer); | |||
6147 | } else if (isa<ReferenceType>(Ty)) { | |||
6148 | T = cast<ReferenceType>(Ty)->getPointeeType(); | |||
6149 | Stack.push_back(Reference); | |||
6150 | } else if (isa<AttributedType>(Ty)) { | |||
6151 | T = cast<AttributedType>(Ty)->getEquivalentType(); | |||
6152 | Stack.push_back(Attributed); | |||
6153 | } else { | |||
6154 | const Type *DTy = Ty->getUnqualifiedDesugaredType(); | |||
6155 | if (Ty == DTy) { | |||
6156 | Fn = nullptr; | |||
6157 | return; | |||
6158 | } | |||
6159 | ||||
6160 | T = QualType(DTy, 0); | |||
6161 | Stack.push_back(Desugar); | |||
6162 | } | |||
6163 | } | |||
6164 | } | |||
6165 | ||||
6166 | bool isFunctionType() const { return (Fn != nullptr); } | |||
6167 | const FunctionType *get() const { return Fn; } | |||
6168 | ||||
6169 | QualType wrap(Sema &S, const FunctionType *New) { | |||
6170 | // If T wasn't modified from the unwrapped type, do nothing. | |||
6171 | if (New == get()) return Original; | |||
6172 | ||||
6173 | Fn = New; | |||
6174 | return wrap(S.Context, Original, 0); | |||
6175 | } | |||
6176 | ||||
6177 | private: | |||
6178 | QualType wrap(ASTContext &C, QualType Old, unsigned I) { | |||
6179 | if (I == Stack.size()) | |||
6180 | return C.getQualifiedType(Fn, Old.getQualifiers()); | |||
6181 | ||||
6182 | // Build up the inner type, applying the qualifiers from the old | |||
6183 | // type to the new type. | |||
6184 | SplitQualType SplitOld = Old.split(); | |||
6185 | ||||
6186 | // As a special case, tail-recurse if there are no qualifiers. | |||
6187 | if (SplitOld.Quals.empty()) | |||
6188 | return wrap(C, SplitOld.Ty, I); | |||
6189 | return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); | |||
6190 | } | |||
6191 | ||||
6192 | QualType wrap(ASTContext &C, const Type *Old, unsigned I) { | |||
6193 | if (I == Stack.size()) return QualType(Fn, 0); | |||
6194 | ||||
6195 | switch (static_cast<WrapKind>(Stack[I++])) { | |||
6196 | case Desugar: | |||
6197 | // This is the point at which we potentially lose source | |||
6198 | // information. | |||
6199 | return wrap(C, Old->getUnqualifiedDesugaredType(), I); | |||
6200 | ||||
6201 | case Attributed: | |||
6202 | return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); | |||
6203 | ||||
6204 | case Parens: { | |||
6205 | QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); | |||
6206 | return C.getParenType(New); | |||
6207 | } | |||
6208 | ||||
6209 | case Pointer: { | |||
6210 | QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); | |||
6211 | return C.getPointerType(New); | |||
6212 | } | |||
6213 | ||||
6214 | case BlockPointer: { | |||
6215 | QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); | |||
6216 | return C.getBlockPointerType(New); | |||
6217 | } | |||
6218 | ||||
6219 | case MemberPointer: { | |||
6220 | const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); | |||
6221 | QualType New = wrap(C, OldMPT->getPointeeType(), I); | |||
6222 | return C.getMemberPointerType(New, OldMPT->getClass()); | |||
6223 | } | |||
6224 | ||||
6225 | case Reference: { | |||
6226 | const ReferenceType *OldRef = cast<ReferenceType>(Old); | |||
6227 | QualType New = wrap(C, OldRef->getPointeeType(), I); | |||
6228 | if (isa<LValueReferenceType>(OldRef)) | |||
6229 | return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); | |||
6230 | else | |||
6231 | return C.getRValueReferenceType(New); | |||
6232 | } | |||
6233 | } | |||
6234 | ||||
6235 | llvm_unreachable("unknown wrapping kind")::llvm::llvm_unreachable_internal("unknown wrapping kind", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 6235); | |||
6236 | } | |||
6237 | }; | |||
6238 | } // end anonymous namespace | |||
6239 | ||||
6240 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, | |||
6241 | AttributeList &Attr, | |||
6242 | QualType &Type) { | |||
6243 | Sema &S = State.getSema(); | |||
6244 | ||||
6245 | AttributeList::Kind Kind = Attr.getKind(); | |||
6246 | QualType Desugared = Type; | |||
6247 | const AttributedType *AT = dyn_cast<AttributedType>(Type); | |||
6248 | while (AT) { | |||
6249 | AttributedType::Kind CurAttrKind = AT->getAttrKind(); | |||
6250 | ||||
6251 | // You cannot specify duplicate type attributes, so if the attribute has | |||
6252 | // already been applied, flag it. | |||
6253 | if (getAttrListKind(CurAttrKind) == Kind) { | |||
6254 | S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) | |||
6255 | << Attr.getName(); | |||
6256 | return true; | |||
6257 | } | |||
6258 | ||||
6259 | // You cannot have both __sptr and __uptr on the same type, nor can you | |||
6260 | // have __ptr32 and __ptr64. | |||
6261 | if ((CurAttrKind == AttributedType::attr_ptr32 && | |||
6262 | Kind == AttributeList::AT_Ptr64) || | |||
6263 | (CurAttrKind == AttributedType::attr_ptr64 && | |||
6264 | Kind == AttributeList::AT_Ptr32)) { | |||
6265 | S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
6266 | << "'__ptr32'" << "'__ptr64'"; | |||
6267 | return true; | |||
6268 | } else if ((CurAttrKind == AttributedType::attr_sptr && | |||
6269 | Kind == AttributeList::AT_UPtr) || | |||
6270 | (CurAttrKind == AttributedType::attr_uptr && | |||
6271 | Kind == AttributeList::AT_SPtr)) { | |||
6272 | S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
6273 | << "'__sptr'" << "'__uptr'"; | |||
6274 | return true; | |||
6275 | } | |||
6276 | ||||
6277 | Desugared = AT->getEquivalentType(); | |||
6278 | AT = dyn_cast<AttributedType>(Desugared); | |||
6279 | } | |||
6280 | ||||
6281 | // Pointer type qualifiers can only operate on pointer types, but not | |||
6282 | // pointer-to-member types. | |||
6283 | if (!isa<PointerType>(Desugared)) { | |||
6284 | if (Type->isMemberPointerType()) | |||
6285 | S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers) | |||
6286 | << Attr.getName(); | |||
6287 | else | |||
6288 | S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) | |||
6289 | << Attr.getName() << 0; | |||
6290 | return true; | |||
6291 | } | |||
6292 | ||||
6293 | AttributedType::Kind TAK; | |||
6294 | switch (Kind) { | |||
6295 | default: llvm_unreachable("Unknown attribute kind")::llvm::llvm_unreachable_internal("Unknown attribute kind", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 6295); | |||
6296 | case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; | |||
6297 | case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; | |||
6298 | case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; | |||
6299 | case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; | |||
6300 | } | |||
6301 | ||||
6302 | Type = S.Context.getAttributedType(TAK, Type, Type); | |||
6303 | return false; | |||
6304 | } | |||
6305 | ||||
6306 | bool Sema::checkNullabilityTypeSpecifier(QualType &type, | |||
6307 | NullabilityKind nullability, | |||
6308 | SourceLocation nullabilityLoc, | |||
6309 | bool isContextSensitive, | |||
6310 | bool allowOnArrayType) { | |||
6311 | recordNullabilitySeen(*this, nullabilityLoc); | |||
6312 | ||||
6313 | // Check for existing nullability attributes on the type. | |||
6314 | QualType desugared = type; | |||
6315 | while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { | |||
6316 | // Check whether there is already a null | |||
6317 | if (auto existingNullability = attributed->getImmediateNullability()) { | |||
6318 | // Duplicated nullability. | |||
6319 | if (nullability == *existingNullability) { | |||
6320 | Diag(nullabilityLoc, diag::warn_nullability_duplicate) | |||
6321 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
6322 | << FixItHint::CreateRemoval(nullabilityLoc); | |||
6323 | ||||
6324 | break; | |||
6325 | } | |||
6326 | ||||
6327 | // Conflicting nullability. | |||
6328 | Diag(nullabilityLoc, diag::err_nullability_conflicting) | |||
6329 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
6330 | << DiagNullabilityKind(*existingNullability, false); | |||
6331 | return true; | |||
6332 | } | |||
6333 | ||||
6334 | desugared = attributed->getModifiedType(); | |||
6335 | } | |||
6336 | ||||
6337 | // If there is already a different nullability specifier, complain. | |||
6338 | // This (unlike the code above) looks through typedefs that might | |||
6339 | // have nullability specifiers on them, which means we cannot | |||
6340 | // provide a useful Fix-It. | |||
6341 | if (auto existingNullability = desugared->getNullability(Context)) { | |||
6342 | if (nullability != *existingNullability) { | |||
6343 | Diag(nullabilityLoc, diag::err_nullability_conflicting) | |||
6344 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
6345 | << DiagNullabilityKind(*existingNullability, false); | |||
6346 | ||||
6347 | // Try to find the typedef with the existing nullability specifier. | |||
6348 | if (auto typedefType = desugared->getAs<TypedefType>()) { | |||
6349 | TypedefNameDecl *typedefDecl = typedefType->getDecl(); | |||
6350 | QualType underlyingType = typedefDecl->getUnderlyingType(); | |||
6351 | if (auto typedefNullability | |||
6352 | = AttributedType::stripOuterNullability(underlyingType)) { | |||
6353 | if (*typedefNullability == *existingNullability) { | |||
6354 | Diag(typedefDecl->getLocation(), diag::note_nullability_here) | |||
6355 | << DiagNullabilityKind(*existingNullability, false); | |||
6356 | } | |||
6357 | } | |||
6358 | } | |||
6359 | ||||
6360 | return true; | |||
6361 | } | |||
6362 | } | |||
6363 | ||||
6364 | // If this definitely isn't a pointer type, reject the specifier. | |||
6365 | if (!desugared->canHaveNullability() && | |||
6366 | !(allowOnArrayType && desugared->isArrayType())) { | |||
6367 | Diag(nullabilityLoc, diag::err_nullability_nonpointer) | |||
6368 | << DiagNullabilityKind(nullability, isContextSensitive) << type; | |||
6369 | return true; | |||
6370 | } | |||
6371 | ||||
6372 | // For the context-sensitive keywords/Objective-C property | |||
6373 | // attributes, require that the type be a single-level pointer. | |||
6374 | if (isContextSensitive) { | |||
6375 | // Make sure that the pointee isn't itself a pointer type. | |||
6376 | const Type *pointeeType; | |||
6377 | if (desugared->isArrayType()) | |||
6378 | pointeeType = desugared->getArrayElementTypeNoTypeQual(); | |||
6379 | else | |||
6380 | pointeeType = desugared->getPointeeType().getTypePtr(); | |||
6381 | ||||
6382 | if (pointeeType->isAnyPointerType() || | |||
6383 | pointeeType->isObjCObjectPointerType() || | |||
6384 | pointeeType->isMemberPointerType()) { | |||
6385 | Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) | |||
6386 | << DiagNullabilityKind(nullability, true) | |||
6387 | << type; | |||
6388 | Diag(nullabilityLoc, diag::note_nullability_type_specifier) | |||
6389 | << DiagNullabilityKind(nullability, false) | |||
6390 | << type | |||
6391 | << FixItHint::CreateReplacement(nullabilityLoc, | |||
6392 | getNullabilitySpelling(nullability)); | |||
6393 | return true; | |||
6394 | } | |||
6395 | } | |||
6396 | ||||
6397 | // Form the attributed type. | |||
6398 | type = Context.getAttributedType( | |||
6399 | AttributedType::getNullabilityAttrKind(nullability), type, type); | |||
6400 | return false; | |||
6401 | } | |||
6402 | ||||
6403 | bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { | |||
6404 | if (isa<ObjCTypeParamType>(type)) { | |||
6405 | // Build the attributed type to record where __kindof occurred. | |||
6406 | type = Context.getAttributedType(AttributedType::attr_objc_kindof, | |||
6407 | type, type); | |||
6408 | return false; | |||
6409 | } | |||
6410 | ||||
6411 | // Find out if it's an Objective-C object or object pointer type; | |||
6412 | const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); | |||
6413 | const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() | |||
6414 | : type->getAs<ObjCObjectType>(); | |||
6415 | ||||
6416 | // If not, we can't apply __kindof. | |||
6417 | if (!objType) { | |||
6418 | // FIXME: Handle dependent types that aren't yet object types. | |||
6419 | Diag(loc, diag::err_objc_kindof_nonobject) | |||
6420 | << type; | |||
6421 | return true; | |||
6422 | } | |||
6423 | ||||
6424 | // Rebuild the "equivalent" type, which pushes __kindof down into | |||
6425 | // the object type. | |||
6426 | // There is no need to apply kindof on an unqualified id type. | |||
6427 | QualType equivType = Context.getObjCObjectType( | |||
6428 | objType->getBaseType(), objType->getTypeArgsAsWritten(), | |||
6429 | objType->getProtocols(), | |||
6430 | /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); | |||
6431 | ||||
6432 | // If we started with an object pointer type, rebuild it. | |||
6433 | if (ptrType) { | |||
6434 | equivType = Context.getObjCObjectPointerType(equivType); | |||
6435 | if (auto nullability = type->getNullability(Context)) { | |||
6436 | auto attrKind = AttributedType::getNullabilityAttrKind(*nullability); | |||
6437 | equivType = Context.getAttributedType(attrKind, equivType, equivType); | |||
6438 | } | |||
6439 | } | |||
6440 | ||||
6441 | // Build the attributed type to record where __kindof occurred. | |||
6442 | type = Context.getAttributedType(AttributedType::attr_objc_kindof, | |||
6443 | type, | |||
6444 | equivType); | |||
6445 | ||||
6446 | return false; | |||
6447 | } | |||
6448 | ||||
6449 | /// Map a nullability attribute kind to a nullability kind. | |||
6450 | static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) { | |||
6451 | switch (kind) { | |||
6452 | case AttributeList::AT_TypeNonNull: | |||
6453 | return NullabilityKind::NonNull; | |||
6454 | ||||
6455 | case AttributeList::AT_TypeNullable: | |||
6456 | return NullabilityKind::Nullable; | |||
6457 | ||||
6458 | case AttributeList::AT_TypeNullUnspecified: | |||
6459 | return NullabilityKind::Unspecified; | |||
6460 | ||||
6461 | default: | |||
6462 | llvm_unreachable("not a nullability attribute kind")::llvm::llvm_unreachable_internal("not a nullability attribute kind" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 6462); | |||
6463 | } | |||
6464 | } | |||
6465 | ||||
6466 | /// Distribute a nullability type attribute that cannot be applied to | |||
6467 | /// the type specifier to a pointer, block pointer, or member pointer | |||
6468 | /// declarator, complaining if necessary. | |||
6469 | /// | |||
6470 | /// \returns true if the nullability annotation was distributed, false | |||
6471 | /// otherwise. | |||
6472 | static bool distributeNullabilityTypeAttr(TypeProcessingState &state, | |||
6473 | QualType type, | |||
6474 | AttributeList &attr) { | |||
6475 | Declarator &declarator = state.getDeclarator(); | |||
6476 | ||||
6477 | /// Attempt to move the attribute to the specified chunk. | |||
6478 | auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { | |||
6479 | // If there is already a nullability attribute there, don't add | |||
6480 | // one. | |||
6481 | if (hasNullabilityAttr(chunk.getAttrListRef())) | |||
6482 | return false; | |||
6483 | ||||
6484 | // Complain about the nullability qualifier being in the wrong | |||
6485 | // place. | |||
6486 | enum { | |||
6487 | PK_Pointer, | |||
6488 | PK_BlockPointer, | |||
6489 | PK_MemberPointer, | |||
6490 | PK_FunctionPointer, | |||
6491 | PK_MemberFunctionPointer, | |||
6492 | } pointerKind | |||
6493 | = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer | |||
6494 | : PK_Pointer) | |||
6495 | : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer | |||
6496 | : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; | |||
6497 | ||||
6498 | auto diag = state.getSema().Diag(attr.getLoc(), | |||
6499 | diag::warn_nullability_declspec) | |||
6500 | << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), | |||
6501 | attr.isContextSensitiveKeywordAttribute()) | |||
6502 | << type | |||
6503 | << static_cast<unsigned>(pointerKind); | |||
6504 | ||||
6505 | // FIXME: MemberPointer chunks don't carry the location of the *. | |||
6506 | if (chunk.Kind != DeclaratorChunk::MemberPointer) { | |||
6507 | diag << FixItHint::CreateRemoval(attr.getLoc()) | |||
6508 | << FixItHint::CreateInsertion( | |||
6509 | state.getSema().getPreprocessor() | |||
6510 | .getLocForEndOfToken(chunk.Loc), | |||
6511 | " " + attr.getName()->getName().str() + " "); | |||
6512 | } | |||
6513 | ||||
6514 | moveAttrFromListToList(attr, state.getCurrentAttrListRef(), | |||
6515 | chunk.getAttrListRef()); | |||
6516 | return true; | |||
6517 | }; | |||
6518 | ||||
6519 | // Move it to the outermost pointer, member pointer, or block | |||
6520 | // pointer declarator. | |||
6521 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
6522 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
6523 | switch (chunk.Kind) { | |||
6524 | case DeclaratorChunk::Pointer: | |||
6525 | case DeclaratorChunk::BlockPointer: | |||
6526 | case DeclaratorChunk::MemberPointer: | |||
6527 | return moveToChunk(chunk, false); | |||
6528 | ||||
6529 | case DeclaratorChunk::Paren: | |||
6530 | case DeclaratorChunk::Array: | |||
6531 | continue; | |||
6532 | ||||
6533 | case DeclaratorChunk::Function: | |||
6534 | // Try to move past the return type to a function/block/member | |||
6535 | // function pointer. | |||
6536 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | |||
6537 | declarator, i, | |||
6538 | /*onlyBlockPointers=*/false)) { | |||
6539 | return moveToChunk(*dest, true); | |||
6540 | } | |||
6541 | ||||
6542 | return false; | |||
6543 | ||||
6544 | // Don't walk through these. | |||
6545 | case DeclaratorChunk::Reference: | |||
6546 | case DeclaratorChunk::Pipe: | |||
6547 | return false; | |||
6548 | } | |||
6549 | } | |||
6550 | ||||
6551 | return false; | |||
6552 | } | |||
6553 | ||||
6554 | static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { | |||
6555 | assert(!Attr.isInvalid())(static_cast <bool> (!Attr.isInvalid()) ? void (0) : __assert_fail ("!Attr.isInvalid()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 6555, __extension__ __PRETTY_FUNCTION__)); | |||
6556 | switch (Attr.getKind()) { | |||
6557 | default: | |||
6558 | llvm_unreachable("not a calling convention attribute")::llvm::llvm_unreachable_internal("not a calling convention attribute" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 6558); | |||
6559 | case AttributeList::AT_CDecl: | |||
6560 | return AttributedType::attr_cdecl; | |||
6561 | case AttributeList::AT_FastCall: | |||
6562 | return AttributedType::attr_fastcall; | |||
6563 | case AttributeList::AT_StdCall: | |||
6564 | return AttributedType::attr_stdcall; | |||
6565 | case AttributeList::AT_ThisCall: | |||
6566 | return AttributedType::attr_thiscall; | |||
6567 | case AttributeList::AT_RegCall: | |||
6568 | return AttributedType::attr_regcall; | |||
6569 | case AttributeList::AT_Pascal: | |||
6570 | return AttributedType::attr_pascal; | |||
6571 | case AttributeList::AT_SwiftCall: | |||
6572 | return AttributedType::attr_swiftcall; | |||
6573 | case AttributeList::AT_VectorCall: | |||
6574 | return AttributedType::attr_vectorcall; | |||
6575 | case AttributeList::AT_Pcs: { | |||
6576 | // The attribute may have had a fixit applied where we treated an | |||
6577 | // identifier as a string literal. The contents of the string are valid, | |||
6578 | // but the form may not be. | |||
6579 | StringRef Str; | |||
6580 | if (Attr.isArgExpr(0)) | |||
6581 | Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); | |||
6582 | else | |||
6583 | Str = Attr.getArgAsIdent(0)->Ident->getName(); | |||
6584 | return llvm::StringSwitch<AttributedType::Kind>(Str) | |||
6585 | .Case("aapcs", AttributedType::attr_pcs) | |||
6586 | .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); | |||
6587 | } | |||
6588 | case AttributeList::AT_IntelOclBicc: | |||
6589 | return AttributedType::attr_inteloclbicc; | |||
6590 | case AttributeList::AT_MSABI: | |||
6591 | return AttributedType::attr_ms_abi; | |||
6592 | case AttributeList::AT_SysVABI: | |||
6593 | return AttributedType::attr_sysv_abi; | |||
6594 | case AttributeList::AT_PreserveMost: | |||
6595 | return AttributedType::attr_preserve_most; | |||
6596 | case AttributeList::AT_PreserveAll: | |||
6597 | return AttributedType::attr_preserve_all; | |||
6598 | } | |||
6599 | llvm_unreachable("unexpected attribute kind!")::llvm::llvm_unreachable_internal("unexpected attribute kind!" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 6599); | |||
6600 | } | |||
6601 | ||||
6602 | /// Process an individual function attribute. Returns true to | |||
6603 | /// indicate that the attribute was handled, false if it wasn't. | |||
6604 | static bool handleFunctionTypeAttr(TypeProcessingState &state, | |||
6605 | AttributeList &attr, | |||
6606 | QualType &type) { | |||
6607 | Sema &S = state.getSema(); | |||
6608 | ||||
6609 | FunctionTypeUnwrapper unwrapped(S, type); | |||
6610 | ||||
6611 | if (attr.getKind() == AttributeList::AT_NoReturn) { | |||
6612 | if (S.CheckNoReturnAttr(attr)) | |||
6613 | return true; | |||
6614 | ||||
6615 | // Delay if this is not a function type. | |||
6616 | if (!unwrapped.isFunctionType()) | |||
6617 | return false; | |||
6618 | ||||
6619 | // Otherwise we can process right away. | |||
6620 | FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); | |||
6621 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6622 | return true; | |||
6623 | } | |||
6624 | ||||
6625 | // ns_returns_retained is not always a type attribute, but if we got | |||
6626 | // here, we're treating it as one right now. | |||
6627 | if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { | |||
6628 | if (attr.getNumArgs()) return true; | |||
6629 | ||||
6630 | // Delay if this is not a function type. | |||
6631 | if (!unwrapped.isFunctionType()) | |||
6632 | return false; | |||
6633 | ||||
6634 | // Check whether the return type is reasonable. | |||
6635 | if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), | |||
6636 | unwrapped.get()->getReturnType())) | |||
6637 | return true; | |||
6638 | ||||
6639 | // Only actually change the underlying type in ARC builds. | |||
6640 | QualType origType = type; | |||
6641 | if (state.getSema().getLangOpts().ObjCAutoRefCount) { | |||
6642 | FunctionType::ExtInfo EI | |||
6643 | = unwrapped.get()->getExtInfo().withProducesResult(true); | |||
6644 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6645 | } | |||
6646 | type = S.Context.getAttributedType(AttributedType::attr_ns_returns_retained, | |||
6647 | origType, type); | |||
6648 | return true; | |||
6649 | } | |||
6650 | ||||
6651 | if (attr.getKind() == AttributeList::AT_AnyX86NoCallerSavedRegisters) { | |||
6652 | if (S.CheckNoCallerSavedRegsAttr(attr)) | |||
6653 | return true; | |||
6654 | ||||
6655 | // Delay if this is not a function type. | |||
6656 | if (!unwrapped.isFunctionType()) | |||
6657 | return false; | |||
6658 | ||||
6659 | FunctionType::ExtInfo EI = | |||
6660 | unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); | |||
6661 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6662 | return true; | |||
6663 | } | |||
6664 | ||||
6665 | if (attr.getKind() == AttributeList::AT_Regparm) { | |||
6666 | unsigned value; | |||
6667 | if (S.CheckRegparmAttr(attr, value)) | |||
6668 | return true; | |||
6669 | ||||
6670 | // Delay if this is not a function type. | |||
6671 | if (!unwrapped.isFunctionType()) | |||
6672 | return false; | |||
6673 | ||||
6674 | // Diagnose regparm with fastcall. | |||
6675 | const FunctionType *fn = unwrapped.get(); | |||
6676 | CallingConv CC = fn->getCallConv(); | |||
6677 | if (CC == CC_X86FastCall) { | |||
6678 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
6679 | << FunctionType::getNameForCallConv(CC) | |||
6680 | << "regparm"; | |||
6681 | attr.setInvalid(); | |||
6682 | return true; | |||
6683 | } | |||
6684 | ||||
6685 | FunctionType::ExtInfo EI = | |||
6686 | unwrapped.get()->getExtInfo().withRegParm(value); | |||
6687 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6688 | return true; | |||
6689 | } | |||
6690 | ||||
6691 | // Delay if the type didn't work out to a function. | |||
6692 | if (!unwrapped.isFunctionType()) return false; | |||
6693 | ||||
6694 | // Otherwise, a calling convention. | |||
6695 | CallingConv CC; | |||
6696 | if (S.CheckCallingConvAttr(attr, CC)) | |||
6697 | return true; | |||
6698 | ||||
6699 | const FunctionType *fn = unwrapped.get(); | |||
6700 | CallingConv CCOld = fn->getCallConv(); | |||
6701 | AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr); | |||
6702 | ||||
6703 | if (CCOld != CC) { | |||
6704 | // Error out on when there's already an attribute on the type | |||
6705 | // and the CCs don't match. | |||
6706 | const AttributedType *AT = S.getCallingConvAttributedType(type); | |||
6707 | if (AT && AT->getAttrKind() != CCAttrKind) { | |||
6708 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
6709 | << FunctionType::getNameForCallConv(CC) | |||
6710 | << FunctionType::getNameForCallConv(CCOld); | |||
6711 | attr.setInvalid(); | |||
6712 | return true; | |||
6713 | } | |||
6714 | } | |||
6715 | ||||
6716 | // Diagnose use of variadic functions with calling conventions that | |||
6717 | // don't support them (e.g. because they're callee-cleanup). | |||
6718 | // We delay warning about this on unprototyped function declarations | |||
6719 | // until after redeclaration checking, just in case we pick up a | |||
6720 | // prototype that way. And apparently we also "delay" warning about | |||
6721 | // unprototyped function types in general, despite not necessarily having | |||
6722 | // much ability to diagnose it later. | |||
6723 | if (!supportsVariadicCall(CC)) { | |||
6724 | const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); | |||
6725 | if (FnP && FnP->isVariadic()) { | |||
6726 | unsigned DiagID = diag::err_cconv_varargs; | |||
6727 | ||||
6728 | // stdcall and fastcall are ignored with a warning for GCC and MS | |||
6729 | // compatibility. | |||
6730 | bool IsInvalid = true; | |||
6731 | if (CC == CC_X86StdCall || CC == CC_X86FastCall) { | |||
6732 | DiagID = diag::warn_cconv_varargs; | |||
6733 | IsInvalid = false; | |||
6734 | } | |||
6735 | ||||
6736 | S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); | |||
6737 | if (IsInvalid) attr.setInvalid(); | |||
6738 | return true; | |||
6739 | } | |||
6740 | } | |||
6741 | ||||
6742 | // Also diagnose fastcall with regparm. | |||
6743 | if (CC == CC_X86FastCall && fn->getHasRegParm()) { | |||
6744 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
6745 | << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); | |||
6746 | attr.setInvalid(); | |||
6747 | return true; | |||
6748 | } | |||
6749 | ||||
6750 | // Modify the CC from the wrapped function type, wrap it all back, and then | |||
6751 | // wrap the whole thing in an AttributedType as written. The modified type | |||
6752 | // might have a different CC if we ignored the attribute. | |||
6753 | QualType Equivalent; | |||
6754 | if (CCOld == CC) { | |||
6755 | Equivalent = type; | |||
6756 | } else { | |||
6757 | auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); | |||
6758 | Equivalent = | |||
6759 | unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
6760 | } | |||
6761 | type = S.Context.getAttributedType(CCAttrKind, type, Equivalent); | |||
6762 | return true; | |||
6763 | } | |||
6764 | ||||
6765 | bool Sema::hasExplicitCallingConv(QualType &T) { | |||
6766 | QualType R = T.IgnoreParens(); | |||
6767 | while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { | |||
6768 | if (AT->isCallingConv()) | |||
6769 | return true; | |||
6770 | R = AT->getModifiedType().IgnoreParens(); | |||
6771 | } | |||
6772 | return false; | |||
6773 | } | |||
6774 | ||||
6775 | void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, | |||
6776 | SourceLocation Loc) { | |||
6777 | FunctionTypeUnwrapper Unwrapped(*this, T); | |||
6778 | const FunctionType *FT = Unwrapped.get(); | |||
6779 | bool IsVariadic = (isa<FunctionProtoType>(FT) && | |||
6780 | cast<FunctionProtoType>(FT)->isVariadic()); | |||
6781 | CallingConv CurCC = FT->getCallConv(); | |||
6782 | CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); | |||
6783 | ||||
6784 | if (CurCC == ToCC) | |||
6785 | return; | |||
6786 | ||||
6787 | // MS compiler ignores explicit calling convention attributes on structors. We | |||
6788 | // should do the same. | |||
6789 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { | |||
6790 | // Issue a warning on ignored calling convention -- except of __stdcall. | |||
6791 | // Again, this is what MS compiler does. | |||
6792 | if (CurCC != CC_X86StdCall) | |||
6793 | Diag(Loc, diag::warn_cconv_structors) | |||
6794 | << FunctionType::getNameForCallConv(CurCC); | |||
6795 | // Default adjustment. | |||
6796 | } else { | |||
6797 | // Only adjust types with the default convention. For example, on Windows | |||
6798 | // we should adjust a __cdecl type to __thiscall for instance methods, and a | |||
6799 | // __thiscall type to __cdecl for static methods. | |||
6800 | CallingConv DefaultCC = | |||
6801 | Context.getDefaultCallingConvention(IsVariadic, IsStatic); | |||
6802 | ||||
6803 | if (CurCC != DefaultCC || DefaultCC == ToCC) | |||
6804 | return; | |||
6805 | ||||
6806 | if (hasExplicitCallingConv(T)) | |||
6807 | return; | |||
6808 | } | |||
6809 | ||||
6810 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); | |||
6811 | QualType Wrapped = Unwrapped.wrap(*this, FT); | |||
6812 | T = Context.getAdjustedType(T, Wrapped); | |||
6813 | } | |||
6814 | ||||
6815 | /// HandleVectorSizeAttribute - this attribute is only applicable to integral | |||
6816 | /// and float scalars, although arrays, pointers, and function return values are | |||
6817 | /// allowed in conjunction with this construct. Aggregates with this attribute | |||
6818 | /// are invalid, even if they are of the same size as a corresponding scalar. | |||
6819 | /// The raw attribute should contain precisely 1 argument, the vector size for | |||
6820 | /// the variable, measured in bytes. If curType and rawAttr are well formed, | |||
6821 | /// this routine will return a new vector type. | |||
6822 | static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, | |||
6823 | Sema &S) { | |||
6824 | // Check the attribute arguments. | |||
6825 | if (Attr.getNumArgs() != 1) { | |||
6826 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
6827 | << Attr.getName() << 1; | |||
6828 | Attr.setInvalid(); | |||
6829 | return; | |||
6830 | } | |||
6831 | Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); | |||
6832 | llvm::APSInt vecSize(32); | |||
6833 | if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || | |||
6834 | !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { | |||
6835 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) | |||
6836 | << Attr.getName() << AANT_ArgumentIntegerConstant | |||
6837 | << sizeExpr->getSourceRange(); | |||
6838 | Attr.setInvalid(); | |||
6839 | return; | |||
6840 | } | |||
6841 | // The base type must be integer (not Boolean or enumeration) or float, and | |||
6842 | // can't already be a vector. | |||
6843 | if (!CurType->isBuiltinType() || CurType->isBooleanType() || | |||
6844 | (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { | |||
6845 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; | |||
6846 | Attr.setInvalid(); | |||
6847 | return; | |||
6848 | } | |||
6849 | unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); | |||
6850 | // vecSize is specified in bytes - convert to bits. | |||
6851 | unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); | |||
6852 | ||||
6853 | // the vector size needs to be an integral multiple of the type size. | |||
6854 | if (vectorSize % typeSize) { | |||
6855 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) | |||
6856 | << sizeExpr->getSourceRange(); | |||
6857 | Attr.setInvalid(); | |||
6858 | return; | |||
6859 | } | |||
6860 | if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { | |||
6861 | S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) | |||
6862 | << sizeExpr->getSourceRange(); | |||
6863 | Attr.setInvalid(); | |||
6864 | return; | |||
6865 | } | |||
6866 | if (vectorSize == 0) { | |||
6867 | S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) | |||
6868 | << sizeExpr->getSourceRange(); | |||
6869 | Attr.setInvalid(); | |||
6870 | return; | |||
6871 | } | |||
6872 | ||||
6873 | // Success! Instantiate the vector type, the number of elements is > 0, and | |||
6874 | // not required to be a power of 2, unlike GCC. | |||
6875 | CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, | |||
6876 | VectorType::GenericVector); | |||
6877 | } | |||
6878 | ||||
6879 | /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on | |||
6880 | /// a type. | |||
6881 | static void HandleExtVectorTypeAttr(QualType &CurType, | |||
6882 | const AttributeList &Attr, | |||
6883 | Sema &S) { | |||
6884 | // check the attribute arguments. | |||
6885 | if (Attr.getNumArgs() != 1) { | |||
6886 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
6887 | << Attr.getName() << 1; | |||
6888 | return; | |||
6889 | } | |||
6890 | ||||
6891 | Expr *sizeExpr; | |||
6892 | ||||
6893 | // Special case where the argument is a template id. | |||
6894 | if (Attr.isArgIdent(0)) { | |||
6895 | CXXScopeSpec SS; | |||
6896 | SourceLocation TemplateKWLoc; | |||
6897 | UnqualifiedId id; | |||
6898 | id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); | |||
6899 | ||||
6900 | ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, | |||
6901 | id, false, false); | |||
6902 | if (Size.isInvalid()) | |||
6903 | return; | |||
6904 | ||||
6905 | sizeExpr = Size.get(); | |||
6906 | } else { | |||
6907 | sizeExpr = Attr.getArgAsExpr(0); | |||
6908 | } | |||
6909 | ||||
6910 | // Create the vector type. | |||
6911 | QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); | |||
6912 | if (!T.isNull()) | |||
6913 | CurType = T; | |||
6914 | } | |||
6915 | ||||
6916 | static bool isPermittedNeonBaseType(QualType &Ty, | |||
6917 | VectorType::VectorKind VecKind, Sema &S) { | |||
6918 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
6919 | if (!BTy) | |||
6920 | return false; | |||
6921 | ||||
6922 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); | |||
6923 | ||||
6924 | // Signed poly is mathematically wrong, but has been baked into some ABIs by | |||
6925 | // now. | |||
6926 | bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || | |||
6927 | Triple.getArch() == llvm::Triple::aarch64_be; | |||
6928 | if (VecKind == VectorType::NeonPolyVector) { | |||
6929 | if (IsPolyUnsigned) { | |||
6930 | // AArch64 polynomial vectors are unsigned and support poly64. | |||
6931 | return BTy->getKind() == BuiltinType::UChar || | |||
6932 | BTy->getKind() == BuiltinType::UShort || | |||
6933 | BTy->getKind() == BuiltinType::ULong || | |||
6934 | BTy->getKind() == BuiltinType::ULongLong; | |||
6935 | } else { | |||
6936 | // AArch32 polynomial vector are signed. | |||
6937 | return BTy->getKind() == BuiltinType::SChar || | |||
6938 | BTy->getKind() == BuiltinType::Short; | |||
6939 | } | |||
6940 | } | |||
6941 | ||||
6942 | // Non-polynomial vector types: the usual suspects are allowed, as well as | |||
6943 | // float64_t on AArch64. | |||
6944 | bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || | |||
6945 | Triple.getArch() == llvm::Triple::aarch64_be; | |||
6946 | ||||
6947 | if (Is64Bit && BTy->getKind() == BuiltinType::Double) | |||
6948 | return true; | |||
6949 | ||||
6950 | return BTy->getKind() == BuiltinType::SChar || | |||
6951 | BTy->getKind() == BuiltinType::UChar || | |||
6952 | BTy->getKind() == BuiltinType::Short || | |||
6953 | BTy->getKind() == BuiltinType::UShort || | |||
6954 | BTy->getKind() == BuiltinType::Int || | |||
6955 | BTy->getKind() == BuiltinType::UInt || | |||
6956 | BTy->getKind() == BuiltinType::Long || | |||
6957 | BTy->getKind() == BuiltinType::ULong || | |||
6958 | BTy->getKind() == BuiltinType::LongLong || | |||
6959 | BTy->getKind() == BuiltinType::ULongLong || | |||
6960 | BTy->getKind() == BuiltinType::Float || | |||
6961 | BTy->getKind() == BuiltinType::Half; | |||
6962 | } | |||
6963 | ||||
6964 | /// HandleNeonVectorTypeAttr - The "neon_vector_type" and | |||
6965 | /// "neon_polyvector_type" attributes are used to create vector types that | |||
6966 | /// are mangled according to ARM's ABI. Otherwise, these types are identical | |||
6967 | /// to those created with the "vector_size" attribute. Unlike "vector_size" | |||
6968 | /// the argument to these Neon attributes is the number of vector elements, | |||
6969 | /// not the vector size in bytes. The vector width and element type must | |||
6970 | /// match one of the standard Neon vector types. | |||
6971 | static void HandleNeonVectorTypeAttr(QualType& CurType, | |||
6972 | const AttributeList &Attr, Sema &S, | |||
6973 | VectorType::VectorKind VecKind) { | |||
6974 | // Target must have NEON | |||
6975 | if (!S.Context.getTargetInfo().hasFeature("neon")) { | |||
6976 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName(); | |||
6977 | Attr.setInvalid(); | |||
6978 | return; | |||
6979 | } | |||
6980 | // Check the attribute arguments. | |||
6981 | if (Attr.getNumArgs() != 1) { | |||
6982 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
6983 | << Attr.getName() << 1; | |||
6984 | Attr.setInvalid(); | |||
6985 | return; | |||
6986 | } | |||
6987 | // The number of elements must be an ICE. | |||
6988 | Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); | |||
6989 | llvm::APSInt numEltsInt(32); | |||
6990 | if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || | |||
6991 | !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { | |||
6992 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) | |||
6993 | << Attr.getName() << AANT_ArgumentIntegerConstant | |||
6994 | << numEltsExpr->getSourceRange(); | |||
6995 | Attr.setInvalid(); | |||
6996 | return; | |||
6997 | } | |||
6998 | // Only certain element types are supported for Neon vectors. | |||
6999 | if (!isPermittedNeonBaseType(CurType, VecKind, S)) { | |||
7000 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; | |||
7001 | Attr.setInvalid(); | |||
7002 | return; | |||
7003 | } | |||
7004 | ||||
7005 | // The total size of the vector must be 64 or 128 bits. | |||
7006 | unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); | |||
7007 | unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); | |||
7008 | unsigned vecSize = typeSize * numElts; | |||
7009 | if (vecSize != 64 && vecSize != 128) { | |||
7010 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; | |||
7011 | Attr.setInvalid(); | |||
7012 | return; | |||
7013 | } | |||
7014 | ||||
7015 | CurType = S.Context.getVectorType(CurType, numElts, VecKind); | |||
7016 | } | |||
7017 | ||||
7018 | /// Handle OpenCL Access Qualifier Attribute. | |||
7019 | static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr, | |||
7020 | Sema &S) { | |||
7021 | // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. | |||
7022 | if (!(CurType->isImageType() || CurType->isPipeType())) { | |||
7023 | S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); | |||
7024 | Attr.setInvalid(); | |||
7025 | return; | |||
7026 | } | |||
7027 | ||||
7028 | if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { | |||
7029 | QualType PointeeTy = TypedefTy->desugar(); | |||
7030 | S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); | |||
7031 | ||||
7032 | std::string PrevAccessQual; | |||
7033 | switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) { | |||
7034 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
7035 | case BuiltinType::Id: \ | |||
7036 | PrevAccessQual = #Access; \ | |||
7037 | break; | |||
7038 | #include "clang/Basic/OpenCLImageTypes.def" | |||
7039 | default: | |||
7040 | assert(0 && "Unable to find corresponding image type.")(static_cast <bool> (0 && "Unable to find corresponding image type." ) ? void (0) : __assert_fail ("0 && \"Unable to find corresponding image type.\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7040, __extension__ __PRETTY_FUNCTION__)); | |||
7041 | } | |||
7042 | ||||
7043 | S.Diag(TypedefTy->getDecl()->getLocStart(), | |||
7044 | diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; | |||
7045 | } else if (CurType->isPipeType()) { | |||
7046 | if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { | |||
7047 | QualType ElemType = CurType->getAs<PipeType>()->getElementType(); | |||
7048 | CurType = S.Context.getWritePipeType(ElemType); | |||
7049 | } | |||
7050 | } | |||
7051 | } | |||
7052 | ||||
7053 | static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State, | |||
7054 | QualType &T, TypeAttrLocation TAL) { | |||
7055 | Declarator &D = State.getDeclarator(); | |||
7056 | ||||
7057 | // Handle the cases where address space should not be deduced. | |||
7058 | // | |||
7059 | // The pointee type of a pointer type is alwasy deduced since a pointer always | |||
7060 | // points to some memory location which should has an address space. | |||
7061 | // | |||
7062 | // There are situations that at the point of certain declarations, the address | |||
7063 | // space may be unknown and better to be left as default. For example, when | |||
7064 | // definining a typedef or struct type, they are not associated with any | |||
7065 | // specific address space. Later on, they may be used with any address space | |||
7066 | // to declare a variable. | |||
7067 | // | |||
7068 | // The return value of a function is r-value, therefore should not have | |||
7069 | // address space. | |||
7070 | // | |||
7071 | // The void type does not occupy memory, therefore should not have address | |||
7072 | // space, except when it is used as a pointee type. | |||
7073 | // | |||
7074 | // Since LLVM assumes function type is in default address space, it should not | |||
7075 | // have address space. | |||
7076 | auto ChunkIndex = State.getCurrentChunkIndex(); | |||
7077 | bool IsPointee = | |||
7078 | ChunkIndex > 0 && | |||
7079 | (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer || | |||
7080 | D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer); | |||
7081 | bool IsFuncReturnType = | |||
7082 | ChunkIndex > 0 && | |||
7083 | D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function; | |||
7084 | bool IsFuncType = | |||
7085 | ChunkIndex < D.getNumTypeObjects() && | |||
7086 | D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function; | |||
7087 | if ( // Do not deduce addr space for function return type and function type, | |||
7088 | // otherwise it will fail some sema check. | |||
7089 | IsFuncReturnType || IsFuncType || | |||
7090 | // Do not deduce addr space for member types of struct, except the pointee | |||
7091 | // type of a pointer member type. | |||
7092 | (D.getContext() == DeclaratorContext::MemberContext && !IsPointee) || | |||
7093 | // Do not deduce addr space for types used to define a typedef and the | |||
7094 | // typedef itself, except the pointee type of a pointer type which is used | |||
7095 | // to define the typedef. | |||
7096 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef && | |||
7097 | !IsPointee) || | |||
7098 | // Do not deduce addr space of the void type, e.g. in f(void), otherwise | |||
7099 | // it will fail some sema check. | |||
7100 | (T->isVoidType() && !IsPointee)) | |||
7101 | return; | |||
7102 | ||||
7103 | LangAS ImpAddr; | |||
7104 | // Put OpenCL automatic variable in private address space. | |||
7105 | // OpenCL v1.2 s6.5: | |||
7106 | // The default address space name for arguments to a function in a | |||
7107 | // program, or local variables of a function is __private. All function | |||
7108 | // arguments shall be in the __private address space. | |||
7109 | if (State.getSema().getLangOpts().OpenCLVersion <= 120) { | |||
7110 | ImpAddr = LangAS::opencl_private; | |||
7111 | } else { | |||
7112 | // If address space is not set, OpenCL 2.0 defines non private default | |||
7113 | // address spaces for some cases: | |||
7114 | // OpenCL 2.0, section 6.5: | |||
7115 | // The address space for a variable at program scope or a static variable | |||
7116 | // inside a function can either be __global or __constant, but defaults to | |||
7117 | // __global if not specified. | |||
7118 | // (...) | |||
7119 | // Pointers that are declared without pointing to a named address space | |||
7120 | // point to the generic address space. | |||
7121 | if (IsPointee) { | |||
7122 | ImpAddr = LangAS::opencl_generic; | |||
7123 | } else { | |||
7124 | if (D.getContext() == DeclaratorContext::FileContext) { | |||
7125 | ImpAddr = LangAS::opencl_global; | |||
7126 | } else { | |||
7127 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || | |||
7128 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) { | |||
7129 | ImpAddr = LangAS::opencl_global; | |||
7130 | } else { | |||
7131 | ImpAddr = LangAS::opencl_private; | |||
7132 | } | |||
7133 | } | |||
7134 | } | |||
7135 | } | |||
7136 | T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr); | |||
7137 | } | |||
7138 | ||||
7139 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, | |||
7140 | TypeAttrLocation TAL, AttributeList *attrs) { | |||
7141 | // Scan through and apply attributes to this type where it makes sense. Some | |||
7142 | // attributes (such as __address_space__, __vector_size__, etc) apply to the | |||
7143 | // type, but others can be present in the type specifiers even though they | |||
7144 | // apply to the decl. Here we apply type attributes and ignore the rest. | |||
7145 | ||||
7146 | while (attrs) { | |||
7147 | AttributeList &attr = *attrs; | |||
7148 | attrs = attr.getNext(); // reset to the next here due to early loop continue | |||
7149 | // stmts | |||
7150 | ||||
7151 | // Skip attributes that were marked to be invalid. | |||
7152 | if (attr.isInvalid()) | |||
7153 | continue; | |||
7154 | ||||
7155 | if (attr.isCXX11Attribute()) { | |||
7156 | // [[gnu::...]] attributes are treated as declaration attributes, so may | |||
7157 | // not appertain to a DeclaratorChunk, even if we handle them as type | |||
7158 | // attributes. | |||
7159 | if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { | |||
7160 | if (TAL == TAL_DeclChunk) { | |||
7161 | state.getSema().Diag(attr.getLoc(), | |||
7162 | diag::warn_cxx11_gnu_attribute_on_type) | |||
7163 | << attr.getName(); | |||
7164 | continue; | |||
7165 | } | |||
7166 | } else if (TAL != TAL_DeclChunk) { | |||
7167 | // Otherwise, only consider type processing for a C++11 attribute if | |||
7168 | // it's actually been applied to a type. | |||
7169 | continue; | |||
7170 | } | |||
7171 | } | |||
7172 | ||||
7173 | // If this is an attribute we can handle, do so now, | |||
7174 | // otherwise, add it to the FnAttrs list for rechaining. | |||
7175 | switch (attr.getKind()) { | |||
7176 | default: | |||
7177 | // A C++11 attribute on a declarator chunk must appertain to a type. | |||
7178 | if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { | |||
7179 | state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) | |||
7180 | << attr.getName(); | |||
7181 | attr.setUsedAsTypeAttr(); | |||
7182 | } | |||
7183 | break; | |||
7184 | ||||
7185 | case AttributeList::UnknownAttribute: | |||
7186 | if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) | |||
7187 | state.getSema().Diag(attr.getLoc(), | |||
7188 | diag::warn_unknown_attribute_ignored) | |||
7189 | << attr.getName(); | |||
7190 | break; | |||
7191 | ||||
7192 | case AttributeList::IgnoredAttribute: | |||
7193 | break; | |||
7194 | ||||
7195 | case AttributeList::AT_MayAlias: | |||
7196 | // FIXME: This attribute needs to actually be handled, but if we ignore | |||
7197 | // it it breaks large amounts of Linux software. | |||
7198 | attr.setUsedAsTypeAttr(); | |||
7199 | break; | |||
7200 | case AttributeList::AT_OpenCLPrivateAddressSpace: | |||
7201 | case AttributeList::AT_OpenCLGlobalAddressSpace: | |||
7202 | case AttributeList::AT_OpenCLLocalAddressSpace: | |||
7203 | case AttributeList::AT_OpenCLConstantAddressSpace: | |||
7204 | case AttributeList::AT_OpenCLGenericAddressSpace: | |||
7205 | case AttributeList::AT_AddressSpace: | |||
7206 | HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); | |||
7207 | attr.setUsedAsTypeAttr(); | |||
7208 | break; | |||
7209 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase AttributeList::AT_ObjCGC: case AttributeList::AT_ObjCOwnership: | |||
7210 | if (!handleObjCPointerTypeAttr(state, attr, type)) | |||
7211 | distributeObjCPointerTypeAttr(state, attr, type); | |||
7212 | attr.setUsedAsTypeAttr(); | |||
7213 | break; | |||
7214 | case AttributeList::AT_VectorSize: | |||
7215 | HandleVectorSizeAttr(type, attr, state.getSema()); | |||
7216 | attr.setUsedAsTypeAttr(); | |||
7217 | break; | |||
7218 | case AttributeList::AT_ExtVectorType: | |||
7219 | HandleExtVectorTypeAttr(type, attr, state.getSema()); | |||
7220 | attr.setUsedAsTypeAttr(); | |||
7221 | break; | |||
7222 | case AttributeList::AT_NeonVectorType: | |||
7223 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | |||
7224 | VectorType::NeonVector); | |||
7225 | attr.setUsedAsTypeAttr(); | |||
7226 | break; | |||
7227 | case AttributeList::AT_NeonPolyVectorType: | |||
7228 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | |||
7229 | VectorType::NeonPolyVector); | |||
7230 | attr.setUsedAsTypeAttr(); | |||
7231 | break; | |||
7232 | case AttributeList::AT_OpenCLAccess: | |||
7233 | HandleOpenCLAccessAttr(type, attr, state.getSema()); | |||
7234 | attr.setUsedAsTypeAttr(); | |||
7235 | break; | |||
7236 | ||||
7237 | MS_TYPE_ATTRS_CASELISTcase AttributeList::AT_Ptr32: case AttributeList::AT_Ptr64: case AttributeList::AT_SPtr: case AttributeList::AT_UPtr: | |||
7238 | if (!handleMSPointerTypeQualifierAttr(state, attr, type)) | |||
7239 | attr.setUsedAsTypeAttr(); | |||
7240 | break; | |||
7241 | ||||
7242 | ||||
7243 | NULLABILITY_TYPE_ATTRS_CASELISTcase AttributeList::AT_TypeNonNull: case AttributeList::AT_TypeNullable : case AttributeList::AT_TypeNullUnspecified: | |||
7244 | // Either add nullability here or try to distribute it. We | |||
7245 | // don't want to distribute the nullability specifier past any | |||
7246 | // dependent type, because that complicates the user model. | |||
7247 | if (type->canHaveNullability() || type->isDependentType() || | |||
7248 | type->isArrayType() || | |||
7249 | !distributeNullabilityTypeAttr(state, type, attr)) { | |||
7250 | unsigned endIndex; | |||
7251 | if (TAL == TAL_DeclChunk) | |||
7252 | endIndex = state.getCurrentChunkIndex(); | |||
7253 | else | |||
7254 | endIndex = state.getDeclarator().getNumTypeObjects(); | |||
7255 | bool allowOnArrayType = | |||
7256 | state.getDeclarator().isPrototypeContext() && | |||
7257 | !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); | |||
7258 | if (state.getSema().checkNullabilityTypeSpecifier( | |||
7259 | type, | |||
7260 | mapNullabilityAttrKind(attr.getKind()), | |||
7261 | attr.getLoc(), | |||
7262 | attr.isContextSensitiveKeywordAttribute(), | |||
7263 | allowOnArrayType)) { | |||
7264 | attr.setInvalid(); | |||
7265 | } | |||
7266 | ||||
7267 | attr.setUsedAsTypeAttr(); | |||
7268 | } | |||
7269 | break; | |||
7270 | ||||
7271 | case AttributeList::AT_ObjCKindOf: | |||
7272 | // '__kindof' must be part of the decl-specifiers. | |||
7273 | switch (TAL) { | |||
7274 | case TAL_DeclSpec: | |||
7275 | break; | |||
7276 | ||||
7277 | case TAL_DeclChunk: | |||
7278 | case TAL_DeclName: | |||
7279 | state.getSema().Diag(attr.getLoc(), | |||
7280 | diag::err_objc_kindof_wrong_position) | |||
7281 | << FixItHint::CreateRemoval(attr.getLoc()) | |||
7282 | << FixItHint::CreateInsertion( | |||
7283 | state.getDeclarator().getDeclSpec().getLocStart(), "__kindof "); | |||
7284 | break; | |||
7285 | } | |||
7286 | ||||
7287 | // Apply it regardless. | |||
7288 | if (state.getSema().checkObjCKindOfType(type, attr.getLoc())) | |||
7289 | attr.setInvalid(); | |||
7290 | attr.setUsedAsTypeAttr(); | |||
7291 | break; | |||
7292 | ||||
7293 | FUNCTION_TYPE_ATTRS_CASELISTcase AttributeList::AT_NSReturnsRetained: case AttributeList:: AT_NoReturn: case AttributeList::AT_Regparm: case AttributeList ::AT_AnyX86NoCallerSavedRegisters: case AttributeList::AT_CDecl : case AttributeList::AT_FastCall: case AttributeList::AT_StdCall : case AttributeList::AT_ThisCall: case AttributeList::AT_RegCall : case AttributeList::AT_Pascal: case AttributeList::AT_SwiftCall : case AttributeList::AT_VectorCall: case AttributeList::AT_MSABI : case AttributeList::AT_SysVABI: case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc: case AttributeList::AT_PreserveMost : case AttributeList::AT_PreserveAll: | |||
7294 | attr.setUsedAsTypeAttr(); | |||
7295 | ||||
7296 | // Never process function type attributes as part of the | |||
7297 | // declaration-specifiers. | |||
7298 | if (TAL == TAL_DeclSpec) | |||
7299 | distributeFunctionTypeAttrFromDeclSpec(state, attr, type); | |||
7300 | ||||
7301 | // Otherwise, handle the possible delays. | |||
7302 | else if (!handleFunctionTypeAttr(state, attr, type)) | |||
7303 | distributeFunctionTypeAttr(state, attr, type); | |||
7304 | break; | |||
7305 | } | |||
7306 | } | |||
7307 | ||||
7308 | if (!state.getSema().getLangOpts().OpenCL || | |||
7309 | type.getAddressSpace() != LangAS::Default) | |||
7310 | return; | |||
7311 | ||||
7312 | deduceOpenCLImplicitAddrSpace(state, type, TAL); | |||
7313 | } | |||
7314 | ||||
7315 | void Sema::completeExprArrayBound(Expr *E) { | |||
7316 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
7317 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
7318 | if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { | |||
7319 | auto *Def = Var->getDefinition(); | |||
7320 | if (!Def) { | |||
7321 | SourceLocation PointOfInstantiation = E->getExprLoc(); | |||
7322 | InstantiateVariableDefinition(PointOfInstantiation, Var); | |||
7323 | Def = Var->getDefinition(); | |||
7324 | ||||
7325 | // If we don't already have a point of instantiation, and we managed | |||
7326 | // to instantiate a definition, this is the point of instantiation. | |||
7327 | // Otherwise, we don't request an end-of-TU instantiation, so this is | |||
7328 | // not a point of instantiation. | |||
7329 | // FIXME: Is this really the right behavior? | |||
7330 | if (Var->getPointOfInstantiation().isInvalid() && Def) { | |||
7331 | assert(Var->getTemplateSpecializationKind() ==(static_cast <bool> (Var->getTemplateSpecializationKind () == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? void (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7333, __extension__ __PRETTY_FUNCTION__)) | |||
7332 | TSK_ImplicitInstantiation &&(static_cast <bool> (Var->getTemplateSpecializationKind () == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? void (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7333, __extension__ __PRETTY_FUNCTION__)) | |||
7333 | "explicit instantiation with no point of instantiation")(static_cast <bool> (Var->getTemplateSpecializationKind () == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? void (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7333, __extension__ __PRETTY_FUNCTION__)); | |||
7334 | Var->setTemplateSpecializationKind( | |||
7335 | Var->getTemplateSpecializationKind(), PointOfInstantiation); | |||
7336 | } | |||
7337 | } | |||
7338 | ||||
7339 | // Update the type to the definition's type both here and within the | |||
7340 | // expression. | |||
7341 | if (Def) { | |||
7342 | DRE->setDecl(Def); | |||
7343 | QualType T = Def->getType(); | |||
7344 | DRE->setType(T); | |||
7345 | // FIXME: Update the type on all intervening expressions. | |||
7346 | E->setType(T); | |||
7347 | } | |||
7348 | ||||
7349 | // We still go on to try to complete the type independently, as it | |||
7350 | // may also require instantiations or diagnostics if it remains | |||
7351 | // incomplete. | |||
7352 | } | |||
7353 | } | |||
7354 | } | |||
7355 | } | |||
7356 | ||||
7357 | /// \brief Ensure that the type of the given expression is complete. | |||
7358 | /// | |||
7359 | /// This routine checks whether the expression \p E has a complete type. If the | |||
7360 | /// expression refers to an instantiable construct, that instantiation is | |||
7361 | /// performed as needed to complete its type. Furthermore | |||
7362 | /// Sema::RequireCompleteType is called for the expression's type (or in the | |||
7363 | /// case of a reference type, the referred-to type). | |||
7364 | /// | |||
7365 | /// \param E The expression whose type is required to be complete. | |||
7366 | /// \param Diagnoser The object that will emit a diagnostic if the type is | |||
7367 | /// incomplete. | |||
7368 | /// | |||
7369 | /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false | |||
7370 | /// otherwise. | |||
7371 | bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { | |||
7372 | QualType T = E->getType(); | |||
7373 | ||||
7374 | // Incomplete array types may be completed by the initializer attached to | |||
7375 | // their definitions. For static data members of class templates and for | |||
7376 | // variable templates, we need to instantiate the definition to get this | |||
7377 | // initializer and complete the type. | |||
7378 | if (T->isIncompleteArrayType()) { | |||
7379 | completeExprArrayBound(E); | |||
7380 | T = E->getType(); | |||
7381 | } | |||
7382 | ||||
7383 | // FIXME: Are there other cases which require instantiating something other | |||
7384 | // than the type to complete the type of an expression? | |||
7385 | ||||
7386 | return RequireCompleteType(E->getExprLoc(), T, Diagnoser); | |||
7387 | } | |||
7388 | ||||
7389 | bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { | |||
7390 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
7391 | return RequireCompleteExprType(E, Diagnoser); | |||
7392 | } | |||
7393 | ||||
7394 | /// @brief Ensure that the type T is a complete type. | |||
7395 | /// | |||
7396 | /// This routine checks whether the type @p T is complete in any | |||
7397 | /// context where a complete type is required. If @p T is a complete | |||
7398 | /// type, returns false. If @p T is a class template specialization, | |||
7399 | /// this routine then attempts to perform class template | |||
7400 | /// instantiation. If instantiation fails, or if @p T is incomplete | |||
7401 | /// and cannot be completed, issues the diagnostic @p diag (giving it | |||
7402 | /// the type @p T) and returns true. | |||
7403 | /// | |||
7404 | /// @param Loc The location in the source that the incomplete type | |||
7405 | /// diagnostic should refer to. | |||
7406 | /// | |||
7407 | /// @param T The type that this routine is examining for completeness. | |||
7408 | /// | |||
7409 | /// @returns @c true if @p T is incomplete and a diagnostic was emitted, | |||
7410 | /// @c false otherwise. | |||
7411 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | |||
7412 | TypeDiagnoser &Diagnoser) { | |||
7413 | if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) | |||
7414 | return true; | |||
7415 | if (const TagType *Tag = T->getAs<TagType>()) { | |||
7416 | if (!Tag->getDecl()->isCompleteDefinitionRequired()) { | |||
7417 | Tag->getDecl()->setCompleteDefinitionRequired(); | |||
7418 | Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); | |||
7419 | } | |||
7420 | } | |||
7421 | return false; | |||
7422 | } | |||
7423 | ||||
7424 | bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { | |||
7425 | llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; | |||
7426 | if (!Suggested) | |||
7427 | return false; | |||
7428 | ||||
7429 | // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext | |||
7430 | // and isolate from other C++ specific checks. | |||
7431 | StructuralEquivalenceContext Ctx( | |||
7432 | D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, | |||
7433 | false /*StrictTypeSpelling*/, true /*Complain*/, | |||
7434 | true /*ErrorOnTagTypeMismatch*/); | |||
7435 | return Ctx.IsStructurallyEquivalent(D, Suggested); | |||
7436 | } | |||
7437 | ||||
7438 | /// \brief Determine whether there is any declaration of \p D that was ever a | |||
7439 | /// definition (perhaps before module merging) and is currently visible. | |||
7440 | /// \param D The definition of the entity. | |||
7441 | /// \param Suggested Filled in with the declaration that should be made visible | |||
7442 | /// in order to provide a definition of this entity. | |||
7443 | /// \param OnlyNeedComplete If \c true, we only need the type to be complete, | |||
7444 | /// not defined. This only matters for enums with a fixed underlying | |||
7445 | /// type, since in all other cases, a type is complete if and only if it | |||
7446 | /// is defined. | |||
7447 | bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, | |||
7448 | bool OnlyNeedComplete) { | |||
7449 | // Easy case: if we don't have modules, all declarations are visible. | |||
7450 | if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) | |||
7451 | return true; | |||
7452 | ||||
7453 | // If this definition was instantiated from a template, map back to the | |||
7454 | // pattern from which it was instantiated. | |||
7455 | if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { | |||
7456 | // We're in the middle of defining it; this definition should be treated | |||
7457 | // as visible. | |||
7458 | return true; | |||
7459 | } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { | |||
7460 | if (auto *Pattern = RD->getTemplateInstantiationPattern()) | |||
7461 | RD = Pattern; | |||
7462 | D = RD->getDefinition(); | |||
7463 | } else if (auto *ED = dyn_cast<EnumDecl>(D)) { | |||
7464 | if (auto *Pattern = ED->getTemplateInstantiationPattern()) | |||
7465 | ED = Pattern; | |||
7466 | if (OnlyNeedComplete && ED->isFixed()) { | |||
7467 | // If the enum has a fixed underlying type, and we're only looking for a | |||
7468 | // complete type (not a definition), any visible declaration of it will | |||
7469 | // do. | |||
7470 | *Suggested = nullptr; | |||
7471 | for (auto *Redecl : ED->redecls()) { | |||
7472 | if (isVisible(Redecl)) | |||
7473 | return true; | |||
7474 | if (Redecl->isThisDeclarationADefinition() || | |||
7475 | (Redecl->isCanonicalDecl() && !*Suggested)) | |||
7476 | *Suggested = Redecl; | |||
7477 | } | |||
7478 | return false; | |||
7479 | } | |||
7480 | D = ED->getDefinition(); | |||
7481 | } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
7482 | if (auto *Pattern = FD->getTemplateInstantiationPattern()) | |||
7483 | FD = Pattern; | |||
7484 | D = FD->getDefinition(); | |||
7485 | } else if (auto *VD = dyn_cast<VarDecl>(D)) { | |||
7486 | if (auto *Pattern = VD->getTemplateInstantiationPattern()) | |||
7487 | VD = Pattern; | |||
7488 | D = VD->getDefinition(); | |||
7489 | } | |||
7490 | assert(D && "missing definition for pattern of instantiated definition")(static_cast <bool> (D && "missing definition for pattern of instantiated definition" ) ? void (0) : __assert_fail ("D && \"missing definition for pattern of instantiated definition\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7490, __extension__ __PRETTY_FUNCTION__)); | |||
7491 | ||||
7492 | *Suggested = D; | |||
7493 | if (isVisible(D)) | |||
7494 | return true; | |||
7495 | ||||
7496 | // The external source may have additional definitions of this entity that are | |||
7497 | // visible, so complete the redeclaration chain now and ask again. | |||
7498 | if (auto *Source = Context.getExternalSource()) { | |||
7499 | Source->CompleteRedeclChain(D); | |||
7500 | return isVisible(D); | |||
7501 | } | |||
7502 | ||||
7503 | return false; | |||
7504 | } | |||
7505 | ||||
7506 | /// Locks in the inheritance model for the given class and all of its bases. | |||
7507 | static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { | |||
7508 | RD = RD->getMostRecentDecl(); | |||
7509 | if (!RD->hasAttr<MSInheritanceAttr>()) { | |||
7510 | MSInheritanceAttr::Spelling IM; | |||
7511 | ||||
7512 | switch (S.MSPointerToMemberRepresentationMethod) { | |||
7513 | case LangOptions::PPTMK_BestCase: | |||
7514 | IM = RD->calculateInheritanceModel(); | |||
7515 | break; | |||
7516 | case LangOptions::PPTMK_FullGeneralitySingleInheritance: | |||
7517 | IM = MSInheritanceAttr::Keyword_single_inheritance; | |||
7518 | break; | |||
7519 | case LangOptions::PPTMK_FullGeneralityMultipleInheritance: | |||
7520 | IM = MSInheritanceAttr::Keyword_multiple_inheritance; | |||
7521 | break; | |||
7522 | case LangOptions::PPTMK_FullGeneralityVirtualInheritance: | |||
7523 | IM = MSInheritanceAttr::Keyword_unspecified_inheritance; | |||
7524 | break; | |||
7525 | } | |||
7526 | ||||
7527 | RD->addAttr(MSInheritanceAttr::CreateImplicit( | |||
7528 | S.getASTContext(), IM, | |||
7529 | /*BestCase=*/S.MSPointerToMemberRepresentationMethod == | |||
7530 | LangOptions::PPTMK_BestCase, | |||
7531 | S.ImplicitMSInheritanceAttrLoc.isValid() | |||
7532 | ? S.ImplicitMSInheritanceAttrLoc | |||
7533 | : RD->getSourceRange())); | |||
7534 | S.Consumer.AssignInheritanceModel(RD); | |||
7535 | } | |||
7536 | } | |||
7537 | ||||
7538 | /// \brief The implementation of RequireCompleteType | |||
7539 | bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, | |||
7540 | TypeDiagnoser *Diagnoser) { | |||
7541 | // FIXME: Add this assertion to make sure we always get instantiation points. | |||
7542 | // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); | |||
7543 | // FIXME: Add this assertion to help us flush out problems with | |||
7544 | // checking for dependent types and type-dependent expressions. | |||
7545 | // | |||
7546 | // assert(!T->isDependentType() && | |||
7547 | // "Can't ask whether a dependent type is complete"); | |||
7548 | ||||
7549 | // We lock in the inheritance model once somebody has asked us to ensure | |||
7550 | // that a pointer-to-member type is complete. | |||
7551 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
7552 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { | |||
7553 | if (!MPTy->getClass()->isDependentType()) { | |||
7554 | (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); | |||
7555 | assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); | |||
7556 | } | |||
7557 | } | |||
7558 | } | |||
7559 | ||||
7560 | NamedDecl *Def = nullptr; | |||
7561 | bool Incomplete = T->isIncompleteType(&Def); | |||
7562 | ||||
7563 | // Check that any necessary explicit specializations are visible. For an | |||
7564 | // enum, we just need the declaration, so don't check this. | |||
7565 | if (Def && !isa<EnumDecl>(Def)) | |||
7566 | checkSpecializationVisibility(Loc, Def); | |||
7567 | ||||
7568 | // If we have a complete type, we're done. | |||
7569 | if (!Incomplete) { | |||
7570 | // If we know about the definition but it is not visible, complain. | |||
7571 | NamedDecl *SuggestedDef = nullptr; | |||
7572 | if (Def && | |||
7573 | !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { | |||
7574 | // If the user is going to see an error here, recover by making the | |||
7575 | // definition visible. | |||
7576 | bool TreatAsComplete = Diagnoser && !isSFINAEContext(); | |||
7577 | if (Diagnoser) | |||
7578 | diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, | |||
7579 | /*Recover*/TreatAsComplete); | |||
7580 | return !TreatAsComplete; | |||
7581 | } else if (Def && !TemplateInstCallbacks.empty()) { | |||
7582 | CodeSynthesisContext TempInst; | |||
7583 | TempInst.Kind = CodeSynthesisContext::Memoization; | |||
7584 | TempInst.Template = Def; | |||
7585 | TempInst.Entity = Def; | |||
7586 | TempInst.PointOfInstantiation = Loc; | |||
7587 | atTemplateBegin(TemplateInstCallbacks, *this, TempInst); | |||
7588 | atTemplateEnd(TemplateInstCallbacks, *this, TempInst); | |||
7589 | } | |||
7590 | ||||
7591 | return false; | |||
7592 | } | |||
7593 | ||||
7594 | const TagType *Tag = T->getAs<TagType>(); | |||
7595 | const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>(); | |||
7596 | ||||
7597 | // If there's an unimported definition of this type in a module (for | |||
7598 | // instance, because we forward declared it, then imported the definition), | |||
7599 | // import that definition now. | |||
7600 | // | |||
7601 | // FIXME: What about other cases where an import extends a redeclaration | |||
7602 | // chain for a declaration that can be accessed through a mechanism other | |||
7603 | // than name lookup (eg, referenced in a template, or a variable whose type | |||
7604 | // could be completed by the module)? | |||
7605 | // | |||
7606 | // FIXME: Should we map through to the base array element type before | |||
7607 | // checking for a tag type? | |||
7608 | if (Tag || IFace) { | |||
7609 | NamedDecl *D = | |||
7610 | Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl(); | |||
7611 | ||||
7612 | // Avoid diagnosing invalid decls as incomplete. | |||
7613 | if (D->isInvalidDecl()) | |||
7614 | return true; | |||
7615 | ||||
7616 | // Give the external AST source a chance to complete the type. | |||
7617 | if (auto *Source = Context.getExternalSource()) { | |||
7618 | if (Tag) { | |||
7619 | TagDecl *TagD = Tag->getDecl(); | |||
7620 | if (TagD->hasExternalLexicalStorage()) | |||
7621 | Source->CompleteType(TagD); | |||
7622 | } else { | |||
7623 | ObjCInterfaceDecl *IFaceD = IFace->getDecl(); | |||
7624 | if (IFaceD->hasExternalLexicalStorage()) | |||
7625 | Source->CompleteType(IFace->getDecl()); | |||
7626 | } | |||
7627 | // If the external source completed the type, go through the motions | |||
7628 | // again to ensure we're allowed to use the completed type. | |||
7629 | if (!T->isIncompleteType()) | |||
7630 | return RequireCompleteTypeImpl(Loc, T, Diagnoser); | |||
7631 | } | |||
7632 | } | |||
7633 | ||||
7634 | // If we have a class template specialization or a class member of a | |||
7635 | // class template specialization, or an array with known size of such, | |||
7636 | // try to instantiate it. | |||
7637 | QualType MaybeTemplate = T; | |||
7638 | while (const ConstantArrayType *Array | |||
7639 | = Context.getAsConstantArrayType(MaybeTemplate)) | |||
7640 | MaybeTemplate = Array->getElementType(); | |||
7641 | if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { | |||
7642 | bool Instantiated = false; | |||
7643 | bool Diagnosed = false; | |||
7644 | if (ClassTemplateSpecializationDecl *ClassTemplateSpec | |||
7645 | = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { | |||
7646 | if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { | |||
7647 | Diagnosed = InstantiateClassTemplateSpecialization( | |||
7648 | Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, | |||
7649 | /*Complain=*/Diagnoser); | |||
7650 | Instantiated = true; | |||
7651 | } | |||
7652 | } else if (CXXRecordDecl *Rec | |||
7653 | = dyn_cast<CXXRecordDecl>(Record->getDecl())) { | |||
7654 | CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); | |||
7655 | if (!Rec->isBeingDefined() && Pattern) { | |||
7656 | MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); | |||
7657 | assert(MSI && "Missing member specialization information?")(static_cast <bool> (MSI && "Missing member specialization information?" ) ? void (0) : __assert_fail ("MSI && \"Missing member specialization information?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7657, __extension__ __PRETTY_FUNCTION__)); | |||
7658 | // This record was instantiated from a class within a template. | |||
7659 | if (MSI->getTemplateSpecializationKind() != | |||
7660 | TSK_ExplicitSpecialization) { | |||
7661 | Diagnosed = InstantiateClass(Loc, Rec, Pattern, | |||
7662 | getTemplateInstantiationArgs(Rec), | |||
7663 | TSK_ImplicitInstantiation, | |||
7664 | /*Complain=*/Diagnoser); | |||
7665 | Instantiated = true; | |||
7666 | } | |||
7667 | } | |||
7668 | } | |||
7669 | ||||
7670 | if (Instantiated) { | |||
7671 | // Instantiate* might have already complained that the template is not | |||
7672 | // defined, if we asked it to. | |||
7673 | if (Diagnoser && Diagnosed) | |||
7674 | return true; | |||
7675 | // If we instantiated a definition, check that it's usable, even if | |||
7676 | // instantiation produced an error, so that repeated calls to this | |||
7677 | // function give consistent answers. | |||
7678 | if (!T->isIncompleteType()) | |||
7679 | return RequireCompleteTypeImpl(Loc, T, Diagnoser); | |||
7680 | } | |||
7681 | } | |||
7682 | ||||
7683 | // FIXME: If we didn't instantiate a definition because of an explicit | |||
7684 | // specialization declaration, check that it's visible. | |||
7685 | ||||
7686 | if (!Diagnoser) | |||
7687 | return true; | |||
7688 | ||||
7689 | Diagnoser->diagnose(*this, Loc, T); | |||
7690 | ||||
7691 | // If the type was a forward declaration of a class/struct/union | |||
7692 | // type, produce a note. | |||
7693 | if (Tag && !Tag->getDecl()->isInvalidDecl()) | |||
7694 | Diag(Tag->getDecl()->getLocation(), | |||
7695 | Tag->isBeingDefined() ? diag::note_type_being_defined | |||
7696 | : diag::note_forward_declaration) | |||
7697 | << QualType(Tag, 0); | |||
7698 | ||||
7699 | // If the Objective-C class was a forward declaration, produce a note. | |||
7700 | if (IFace && !IFace->getDecl()->isInvalidDecl()) | |||
7701 | Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); | |||
7702 | ||||
7703 | // If we have external information that we can use to suggest a fix, | |||
7704 | // produce a note. | |||
7705 | if (ExternalSource) | |||
7706 | ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); | |||
7707 | ||||
7708 | return true; | |||
7709 | } | |||
7710 | ||||
7711 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | |||
7712 | unsigned DiagID) { | |||
7713 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
7714 | return RequireCompleteType(Loc, T, Diagnoser); | |||
7715 | } | |||
7716 | ||||
7717 | /// \brief Get diagnostic %select index for tag kind for | |||
7718 | /// literal type diagnostic message. | |||
7719 | /// WARNING: Indexes apply to particular diagnostics only! | |||
7720 | /// | |||
7721 | /// \returns diagnostic %select index. | |||
7722 | static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { | |||
7723 | switch (Tag) { | |||
7724 | case TTK_Struct: return 0; | |||
7725 | case TTK_Interface: return 1; | |||
7726 | case TTK_Class: return 2; | |||
7727 | 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-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7727); | |||
7728 | } | |||
7729 | } | |||
7730 | ||||
7731 | /// @brief Ensure that the type T is a literal type. | |||
7732 | /// | |||
7733 | /// This routine checks whether the type @p T is a literal type. If @p T is an | |||
7734 | /// incomplete type, an attempt is made to complete it. If @p T is a literal | |||
7735 | /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, | |||
7736 | /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving | |||
7737 | /// it the type @p T), along with notes explaining why the type is not a | |||
7738 | /// literal type, and returns true. | |||
7739 | /// | |||
7740 | /// @param Loc The location in the source that the non-literal type | |||
7741 | /// diagnostic should refer to. | |||
7742 | /// | |||
7743 | /// @param T The type that this routine is examining for literalness. | |||
7744 | /// | |||
7745 | /// @param Diagnoser Emits a diagnostic if T is not a literal type. | |||
7746 | /// | |||
7747 | /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, | |||
7748 | /// @c false otherwise. | |||
7749 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, | |||
7750 | TypeDiagnoser &Diagnoser) { | |||
7751 | assert(!T->isDependentType() && "type should not be dependent")(static_cast <bool> (!T->isDependentType() && "type should not be dependent") ? void (0) : __assert_fail ( "!T->isDependentType() && \"type should not be dependent\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7751, __extension__ __PRETTY_FUNCTION__)); | |||
7752 | ||||
7753 | QualType ElemType = Context.getBaseElementType(T); | |||
7754 | if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && | |||
7755 | T->isLiteralType(Context)) | |||
7756 | return false; | |||
7757 | ||||
7758 | Diagnoser.diagnose(*this, Loc, T); | |||
7759 | ||||
7760 | if (T->isVariableArrayType()) | |||
7761 | return true; | |||
7762 | ||||
7763 | const RecordType *RT = ElemType->getAs<RecordType>(); | |||
7764 | if (!RT) | |||
7765 | return true; | |||
7766 | ||||
7767 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
7768 | ||||
7769 | // A partially-defined class type can't be a literal type, because a literal | |||
7770 | // class type must have a trivial destructor (which can't be checked until | |||
7771 | // the class definition is complete). | |||
7772 | if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) | |||
7773 | return true; | |||
7774 | ||||
7775 | // If the class has virtual base classes, then it's not an aggregate, and | |||
7776 | // cannot have any constexpr constructors or a trivial default constructor, | |||
7777 | // so is non-literal. This is better to diagnose than the resulting absence | |||
7778 | // of constexpr constructors. | |||
7779 | if (RD->getNumVBases()) { | |||
7780 | Diag(RD->getLocation(), diag::note_non_literal_virtual_base) | |||
7781 | << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); | |||
7782 | for (const auto &I : RD->vbases()) | |||
7783 | Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here) | |||
7784 | << I.getSourceRange(); | |||
7785 | } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && | |||
7786 | !RD->hasTrivialDefaultConstructor()) { | |||
7787 | Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; | |||
7788 | } else if (RD->hasNonLiteralTypeFieldsOrBases()) { | |||
7789 | for (const auto &I : RD->bases()) { | |||
7790 | if (!I.getType()->isLiteralType(Context)) { | |||
7791 | Diag(I.getLocStart(), | |||
7792 | diag::note_non_literal_base_class) | |||
7793 | << RD << I.getType() << I.getSourceRange(); | |||
7794 | return true; | |||
7795 | } | |||
7796 | } | |||
7797 | for (const auto *I : RD->fields()) { | |||
7798 | if (!I->getType()->isLiteralType(Context) || | |||
7799 | I->getType().isVolatileQualified()) { | |||
7800 | Diag(I->getLocation(), diag::note_non_literal_field) | |||
7801 | << RD << I << I->getType() | |||
7802 | << I->getType().isVolatileQualified(); | |||
7803 | return true; | |||
7804 | } | |||
7805 | } | |||
7806 | } else if (!RD->hasTrivialDestructor()) { | |||
7807 | // All fields and bases are of literal types, so have trivial destructors. | |||
7808 | // If this class's destructor is non-trivial it must be user-declared. | |||
7809 | CXXDestructorDecl *Dtor = RD->getDestructor(); | |||
7810 | assert(Dtor && "class has literal fields and bases but no dtor?")(static_cast <bool> (Dtor && "class has literal fields and bases but no dtor?" ) ? void (0) : __assert_fail ("Dtor && \"class has literal fields and bases but no dtor?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7810, __extension__ __PRETTY_FUNCTION__)); | |||
7811 | if (!Dtor) | |||
7812 | return true; | |||
7813 | ||||
7814 | Diag(Dtor->getLocation(), Dtor->isUserProvided() ? | |||
7815 | diag::note_non_literal_user_provided_dtor : | |||
7816 | diag::note_non_literal_nontrivial_dtor) << RD; | |||
7817 | if (!Dtor->isUserProvided()) | |||
7818 | SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, | |||
7819 | /*Diagnose*/true); | |||
7820 | } | |||
7821 | ||||
7822 | return true; | |||
7823 | } | |||
7824 | ||||
7825 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { | |||
7826 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
7827 | return RequireLiteralType(Loc, T, Diagnoser); | |||
7828 | } | |||
7829 | ||||
7830 | /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword | |||
7831 | /// and qualified by the nested-name-specifier contained in SS. | |||
7832 | QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, | |||
7833 | const CXXScopeSpec &SS, QualType T) { | |||
7834 | if (T.isNull()) | |||
7835 | return T; | |||
7836 | NestedNameSpecifier *NNS; | |||
7837 | if (SS.isValid()) | |||
7838 | NNS = SS.getScopeRep(); | |||
7839 | else { | |||
7840 | if (Keyword == ETK_None) | |||
7841 | return T; | |||
7842 | NNS = nullptr; | |||
7843 | } | |||
7844 | return Context.getElaboratedType(Keyword, NNS, T); | |||
7845 | } | |||
7846 | ||||
7847 | QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { | |||
7848 | ExprResult ER = CheckPlaceholderExpr(E); | |||
7849 | if (ER.isInvalid()) return QualType(); | |||
7850 | E = ER.get(); | |||
7851 | ||||
7852 | if (!getLangOpts().CPlusPlus && E->refersToBitField()) | |||
7853 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; | |||
7854 | ||||
7855 | if (!E->isTypeDependent()) { | |||
7856 | QualType T = E->getType(); | |||
7857 | if (const TagType *TT = T->getAs<TagType>()) | |||
7858 | DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); | |||
7859 | } | |||
7860 | return Context.getTypeOfExprType(E); | |||
7861 | } | |||
7862 | ||||
7863 | /// getDecltypeForExpr - Given an expr, will return the decltype for | |||
7864 | /// that expression, according to the rules in C++11 | |||
7865 | /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. | |||
7866 | static QualType getDecltypeForExpr(Sema &S, Expr *E) { | |||
7867 | if (E->isTypeDependent()) | |||
7868 | return S.Context.DependentTy; | |||
7869 | ||||
7870 | // C++11 [dcl.type.simple]p4: | |||
7871 | // The type denoted by decltype(e) is defined as follows: | |||
7872 | // | |||
7873 | // - if e is an unparenthesized id-expression or an unparenthesized class | |||
7874 | // member access (5.2.5), decltype(e) is the type of the entity named | |||
7875 | // by e. If there is no such entity, or if e names a set of overloaded | |||
7876 | // functions, the program is ill-formed; | |||
7877 | // | |||
7878 | // We apply the same rules for Objective-C ivar and property references. | |||
7879 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { | |||
7880 | const ValueDecl *VD = DRE->getDecl(); | |||
7881 | return VD->getType(); | |||
7882 | } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
7883 | if (const ValueDecl *VD = ME->getMemberDecl()) | |||
7884 | if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) | |||
7885 | return VD->getType(); | |||
7886 | } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { | |||
7887 | return IR->getDecl()->getType(); | |||
7888 | } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { | |||
7889 | if (PR->isExplicitProperty()) | |||
7890 | return PR->getExplicitProperty()->getType(); | |||
7891 | } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { | |||
7892 | return PE->getType(); | |||
7893 | } | |||
7894 | ||||
7895 | // C++11 [expr.lambda.prim]p18: | |||
7896 | // Every occurrence of decltype((x)) where x is a possibly | |||
7897 | // parenthesized id-expression that names an entity of automatic | |||
7898 | // storage duration is treated as if x were transformed into an | |||
7899 | // access to a corresponding data member of the closure type that | |||
7900 | // would have been declared if x were an odr-use of the denoted | |||
7901 | // entity. | |||
7902 | using namespace sema; | |||
7903 | if (S.getCurLambda()) { | |||
7904 | if (isa<ParenExpr>(E)) { | |||
7905 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
7906 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
7907 | QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); | |||
7908 | if (!T.isNull()) | |||
7909 | return S.Context.getLValueReferenceType(T); | |||
7910 | } | |||
7911 | } | |||
7912 | } | |||
7913 | } | |||
7914 | ||||
7915 | ||||
7916 | // C++11 [dcl.type.simple]p4: | |||
7917 | // [...] | |||
7918 | QualType T = E->getType(); | |||
7919 | switch (E->getValueKind()) { | |||
7920 | // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the | |||
7921 | // type of e; | |||
7922 | case VK_XValue: T = S.Context.getRValueReferenceType(T); break; | |||
7923 | // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the | |||
7924 | // type of e; | |||
7925 | case VK_LValue: T = S.Context.getLValueReferenceType(T); break; | |||
7926 | // - otherwise, decltype(e) is the type of e. | |||
7927 | case VK_RValue: break; | |||
7928 | } | |||
7929 | ||||
7930 | return T; | |||
7931 | } | |||
7932 | ||||
7933 | QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, | |||
7934 | bool AsUnevaluated) { | |||
7935 | ExprResult ER = CheckPlaceholderExpr(E); | |||
7936 | if (ER.isInvalid()) return QualType(); | |||
7937 | E = ER.get(); | |||
7938 | ||||
7939 | if (AsUnevaluated && CodeSynthesisContexts.empty() && | |||
7940 | E->HasSideEffects(Context, false)) { | |||
7941 | // The expression operand for decltype is in an unevaluated expression | |||
7942 | // context, so side effects could result in unintended consequences. | |||
7943 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
7944 | } | |||
7945 | ||||
7946 | return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); | |||
7947 | } | |||
7948 | ||||
7949 | QualType Sema::BuildUnaryTransformType(QualType BaseType, | |||
7950 | UnaryTransformType::UTTKind UKind, | |||
7951 | SourceLocation Loc) { | |||
7952 | switch (UKind) { | |||
7953 | case UnaryTransformType::EnumUnderlyingType: | |||
7954 | if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { | |||
7955 | Diag(Loc, diag::err_only_enums_have_underlying_types); | |||
7956 | return QualType(); | |||
7957 | } else { | |||
7958 | QualType Underlying = BaseType; | |||
7959 | if (!BaseType->isDependentType()) { | |||
7960 | // The enum could be incomplete if we're parsing its definition or | |||
7961 | // recovering from an error. | |||
7962 | NamedDecl *FwdDecl = nullptr; | |||
7963 | if (BaseType->isIncompleteType(&FwdDecl)) { | |||
7964 | Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; | |||
7965 | Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; | |||
7966 | return QualType(); | |||
7967 | } | |||
7968 | ||||
7969 | EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); | |||
7970 | assert(ED && "EnumType has no EnumDecl")(static_cast <bool> (ED && "EnumType has no EnumDecl" ) ? void (0) : __assert_fail ("ED && \"EnumType has no EnumDecl\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7970, __extension__ __PRETTY_FUNCTION__)); | |||
7971 | ||||
7972 | DiagnoseUseOfDecl(ED, Loc); | |||
7973 | ||||
7974 | Underlying = ED->getIntegerType(); | |||
7975 | assert(!Underlying.isNull())(static_cast <bool> (!Underlying.isNull()) ? void (0) : __assert_fail ("!Underlying.isNull()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7975, __extension__ __PRETTY_FUNCTION__)); | |||
7976 | } | |||
7977 | return Context.getUnaryTransformType(BaseType, Underlying, | |||
7978 | UnaryTransformType::EnumUnderlyingType); | |||
7979 | } | |||
7980 | } | |||
7981 | llvm_unreachable("unknown unary transform type")::llvm::llvm_unreachable_internal("unknown unary transform type" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp" , 7981); | |||
7982 | } | |||
7983 | ||||
7984 | QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { | |||
7985 | if (!T->isDependentType()) { | |||
7986 | // FIXME: It isn't entirely clear whether incomplete atomic types | |||
7987 | // are allowed or not; for simplicity, ban them for the moment. | |||
7988 | if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) | |||
7989 | return QualType(); | |||
7990 | ||||
7991 | int DisallowedKind = -1; | |||
7992 | if (T->isArrayType()) | |||
7993 | DisallowedKind = 1; | |||
7994 | else if (T->isFunctionType()) | |||
7995 | DisallowedKind = 2; | |||
7996 | else if (T->isReferenceType()) | |||
7997 | DisallowedKind = 3; | |||
7998 | else if (T->isAtomicType()) | |||
7999 | DisallowedKind = 4; | |||
8000 | else if (T.hasQualifiers()) | |||
8001 | DisallowedKind = 5; | |||
8002 | else if (!T.isTriviallyCopyableType(Context)) | |||
8003 | // Some other non-trivially-copyable type (probably a C++ class) | |||
8004 | DisallowedKind = 6; | |||
8005 | ||||
8006 | if (DisallowedKind != -1) { | |||
8007 | Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; | |||
8008 | return QualType(); | |||
8009 | } | |||
8010 | ||||
8011 | // FIXME: Do we need any handling for ARC here? | |||
8012 | } | |||
8013 | ||||
8014 | // Build the pointer type. | |||
8015 | return Context.getAtomicType(T); | |||
8016 | } |
1 | //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// |
2 | // |
3 | // The LLVM Compiler Infrastructure |
4 | // |
5 | // This file is distributed under the University of Illinois Open Source |
6 | // License. See LICENSE.TXT for details. |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | // |
10 | // This file defines the Sema class, which performs semantic analysis and |
11 | // builds ASTs. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_CLANG_SEMA_SEMA_H |
16 | #define LLVM_CLANG_SEMA_SEMA_H |
17 | |
18 | #include "clang/AST/Attr.h" |
19 | #include "clang/AST/Availability.h" |
20 | #include "clang/AST/DeclarationName.h" |
21 | #include "clang/AST/DeclTemplate.h" |
22 | #include "clang/AST/Expr.h" |
23 | #include "clang/AST/ExprObjC.h" |
24 | #include "clang/AST/ExternalASTSource.h" |
25 | #include "clang/AST/LocInfoType.h" |
26 | #include "clang/AST/MangleNumberingContext.h" |
27 | #include "clang/AST/NSAPI.h" |
28 | #include "clang/AST/PrettyPrinter.h" |
29 | #include "clang/AST/StmtCXX.h" |
30 | #include "clang/AST/TypeLoc.h" |
31 | #include "clang/AST/TypeOrdering.h" |
32 | #include "clang/Basic/ExpressionTraits.h" |
33 | #include "clang/Basic/LangOptions.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/ScopeInfo.h" |
49 | #include "clang/Sema/TypoCorrection.h" |
50 | #include "clang/Sema/Weak.h" |
51 | #include "llvm/ADT/ArrayRef.h" |
52 | #include "llvm/ADT/Optional.h" |
53 | #include "llvm/ADT/SetVector.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 AttributeList; |
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 OMPDeclareReductionDecl; |
156 | class OMPDeclareSimdDecl; |
157 | class OMPClause; |
158 | struct OverloadCandidate; |
159 | class OverloadCandidateSet; |
160 | class OverloadExpr; |
161 | class ParenListExpr; |
162 | class ParmVarDecl; |
163 | class Preprocessor; |
164 | class PseudoDestructorTypeStorage; |
165 | class PseudoObjectExpr; |
166 | class QualType; |
167 | class StandardConversionSequence; |
168 | class Stmt; |
169 | class StringLiteral; |
170 | class SwitchStmt; |
171 | class TemplateArgument; |
172 | class TemplateArgumentList; |
173 | class TemplateArgumentLoc; |
174 | class TemplateDecl; |
175 | class TemplateInstantiationCallback; |
176 | class TemplateParameterList; |
177 | class TemplatePartialOrderingContext; |
178 | class TemplateTemplateParmDecl; |
179 | class Token; |
180 | class TypeAliasDecl; |
181 | class TypedefDecl; |
182 | class TypedefNameDecl; |
183 | class TypeLoc; |
184 | class TypoCorrectionConsumer; |
185 | class UnqualifiedId; |
186 | class UnresolvedLookupExpr; |
187 | class UnresolvedMemberExpr; |
188 | class UnresolvedSetImpl; |
189 | class UnresolvedSetIterator; |
190 | class UsingDecl; |
191 | class UsingShadowDecl; |
192 | class ValueDecl; |
193 | class VarDecl; |
194 | class VarTemplateSpecializationDecl; |
195 | class VisibilityAttr; |
196 | class VisibleDeclConsumer; |
197 | class IndirectFieldDecl; |
198 | struct DeductionFailureInfo; |
199 | class TemplateSpecCandidateSet; |
200 | |
201 | namespace sema { |
202 | class AccessedEntity; |
203 | class BlockScopeInfo; |
204 | class CapturedRegionScopeInfo; |
205 | class CapturingScopeInfo; |
206 | class CompoundScopeInfo; |
207 | class DelayedDiagnostic; |
208 | class DelayedDiagnosticPool; |
209 | class FunctionScopeInfo; |
210 | class LambdaScopeInfo; |
211 | class PossiblyUnreachableDiag; |
212 | class SemaPPCallbacks; |
213 | class TemplateDeductionInfo; |
214 | } |
215 | |
216 | namespace threadSafety { |
217 | class BeforeSet; |
218 | void threadSafetyCleanup(BeforeSet* Cache); |
219 | } |
220 | |
221 | // FIXME: No way to easily map from TemplateTypeParmTypes to |
222 | // TemplateTypeParmDecls, so we have this horrible PointerUnion. |
223 | typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, |
224 | SourceLocation> UnexpandedParameterPack; |
225 | |
226 | /// Describes whether we've seen any nullability information for the given |
227 | /// file. |
228 | struct FileNullability { |
229 | /// The first pointer declarator (of any pointer kind) in the file that does |
230 | /// not have a corresponding nullability annotation. |
231 | SourceLocation PointerLoc; |
232 | |
233 | /// The end location for the first pointer declarator in the file. Used for |
234 | /// placing fix-its. |
235 | SourceLocation PointerEndLoc; |
236 | |
237 | /// Which kind of pointer declarator we saw. |
238 | uint8_t PointerKind; |
239 | |
240 | /// Whether we saw any type nullability annotations in the given file. |
241 | bool SawTypeNullability = false; |
242 | }; |
243 | |
244 | /// A mapping from file IDs to a record of whether we've seen nullability |
245 | /// information in that file. |
246 | class FileNullabilityMap { |
247 | /// A mapping from file IDs to the nullability information for each file ID. |
248 | llvm::DenseMap<FileID, FileNullability> Map; |
249 | |
250 | /// A single-element cache based on the file ID. |
251 | struct { |
252 | FileID File; |
253 | FileNullability Nullability; |
254 | } Cache; |
255 | |
256 | public: |
257 | FileNullability &operator[](FileID file) { |
258 | // Check the single-element cache. |
259 | if (file == Cache.File) |
260 | return Cache.Nullability; |
261 | |
262 | // It's not in the single-element cache; flush the cache if we have one. |
263 | if (!Cache.File.isInvalid()) { |
264 | Map[Cache.File] = Cache.Nullability; |
265 | } |
266 | |
267 | // Pull this entry into the cache. |
268 | Cache.File = file; |
269 | Cache.Nullability = Map[file]; |
270 | return Cache.Nullability; |
271 | } |
272 | }; |
273 | |
274 | /// Sema - This implements semantic analysis and AST building for C. |
275 | class Sema { |
276 | Sema(const Sema &) = delete; |
277 | void operator=(const Sema &) = delete; |
278 | |
279 | ///\brief Source of additional semantic information. |
280 | ExternalSemaSource *ExternalSource; |
281 | |
282 | ///\brief Whether Sema has generated a multiplexer and has to delete it. |
283 | bool isMultiplexExternalSource; |
284 | |
285 | static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); |
286 | |
287 | bool isVisibleSlow(const NamedDecl *D); |
288 | |
289 | /// Determine whether two declarations should be linked together, given that |
290 | /// the old declaration might not be visible and the new declaration might |
291 | /// not have external linkage. |
292 | bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, |
293 | const NamedDecl *New) { |
294 | if (isVisible(Old)) |
295 | return true; |
296 | // See comment in below overload for why it's safe to compute the linkage |
297 | // of the new declaration here. |
298 | if (New->isExternallyDeclarable()) { |
299 | assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl" ) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 300, __extension__ __PRETTY_FUNCTION__)) |
300 | "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl" ) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 300, __extension__ __PRETTY_FUNCTION__)); |
301 | return true; |
302 | } |
303 | return false; |
304 | } |
305 | bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); |
306 | |
307 | public: |
308 | typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; |
309 | typedef OpaquePtr<TemplateName> TemplateTy; |
310 | typedef OpaquePtr<QualType> TypeTy; |
311 | |
312 | OpenCLOptions OpenCLFeatures; |
313 | FPOptions FPFeatures; |
314 | |
315 | const LangOptions &LangOpts; |
316 | Preprocessor &PP; |
317 | ASTContext &Context; |
318 | ASTConsumer &Consumer; |
319 | DiagnosticsEngine &Diags; |
320 | SourceManager &SourceMgr; |
321 | |
322 | /// \brief Flag indicating whether or not to collect detailed statistics. |
323 | bool CollectStats; |
324 | |
325 | /// \brief Code-completion consumer. |
326 | CodeCompleteConsumer *CodeCompleter; |
327 | |
328 | /// CurContext - This is the current declaration context of parsing. |
329 | DeclContext *CurContext; |
330 | |
331 | /// \brief Generally null except when we temporarily switch decl contexts, |
332 | /// like in \see ActOnObjCTemporaryExitContainerContext. |
333 | DeclContext *OriginalLexicalContext; |
334 | |
335 | /// VAListTagName - The declaration name corresponding to __va_list_tag. |
336 | /// This is used as part of a hack to omit that class from ADL results. |
337 | DeclarationName VAListTagName; |
338 | |
339 | bool MSStructPragmaOn; // True when \#pragma ms_struct on |
340 | |
341 | /// \brief Controls member pointer representation format under the MS ABI. |
342 | LangOptions::PragmaMSPointersToMembersKind |
343 | MSPointerToMemberRepresentationMethod; |
344 | |
345 | /// Stack of active SEH __finally scopes. Can be empty. |
346 | SmallVector<Scope*, 2> CurrentSEHFinally; |
347 | |
348 | /// \brief Source location for newly created implicit MSInheritanceAttrs |
349 | SourceLocation ImplicitMSInheritanceAttrLoc; |
350 | |
351 | /// \brief pragma clang section kind |
352 | enum PragmaClangSectionKind { |
353 | PCSK_Invalid = 0, |
354 | PCSK_BSS = 1, |
355 | PCSK_Data = 2, |
356 | PCSK_Rodata = 3, |
357 | PCSK_Text = 4 |
358 | }; |
359 | |
360 | enum PragmaClangSectionAction { |
361 | PCSA_Set = 0, |
362 | PCSA_Clear = 1 |
363 | }; |
364 | |
365 | struct PragmaClangSection { |
366 | std::string SectionName; |
367 | bool Valid = false; |
368 | SourceLocation PragmaLocation; |
369 | |
370 | void Act(SourceLocation PragmaLocation, |
371 | PragmaClangSectionAction Action, |
372 | StringLiteral* Name); |
373 | }; |
374 | |
375 | PragmaClangSection PragmaClangBSSSection; |
376 | PragmaClangSection PragmaClangDataSection; |
377 | PragmaClangSection PragmaClangRodataSection; |
378 | PragmaClangSection PragmaClangTextSection; |
379 | |
380 | enum PragmaMsStackAction { |
381 | PSK_Reset = 0x0, // #pragma () |
382 | PSK_Set = 0x1, // #pragma (value) |
383 | PSK_Push = 0x2, // #pragma (push[, id]) |
384 | PSK_Pop = 0x4, // #pragma (pop[, id]) |
385 | PSK_Show = 0x8, // #pragma (show) -- only for "pack"! |
386 | PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) |
387 | PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) |
388 | }; |
389 | |
390 | template<typename ValueType> |
391 | struct PragmaStack { |
392 | struct Slot { |
393 | llvm::StringRef StackSlotLabel; |
394 | ValueType Value; |
395 | SourceLocation PragmaLocation; |
396 | SourceLocation PragmaPushLocation; |
397 | Slot(llvm::StringRef StackSlotLabel, ValueType Value, |
398 | SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) |
399 | : StackSlotLabel(StackSlotLabel), Value(Value), |
400 | PragmaLocation(PragmaLocation), |
401 | PragmaPushLocation(PragmaPushLocation) {} |
402 | }; |
403 | void Act(SourceLocation PragmaLocation, |
404 | PragmaMsStackAction Action, |
405 | llvm::StringRef StackSlotLabel, |
406 | ValueType Value); |
407 | |
408 | // MSVC seems to add artificial slots to #pragma stacks on entering a C++ |
409 | // method body to restore the stacks on exit, so it works like this: |
410 | // |
411 | // struct S { |
412 | // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) |
413 | // void Method {} |
414 | // #pragma <name>(pop, InternalPragmaSlot) |
415 | // }; |
416 | // |
417 | // It works even with #pragma vtordisp, although MSVC doesn't support |
418 | // #pragma vtordisp(push [, id], n) |
419 | // syntax. |
420 | // |
421 | // Push / pop a named sentinel slot. |
422 | void SentinelAction(PragmaMsStackAction Action, StringRef Label) { |
423 | assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop ) && "Can only push / pop #pragma stack sentinels!") ? void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 424, __extension__ __PRETTY_FUNCTION__)) |
424 | "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop ) && "Can only push / pop #pragma stack sentinels!") ? void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 424, __extension__ __PRETTY_FUNCTION__)); |
425 | Act(CurrentPragmaLocation, Action, Label, CurrentValue); |
426 | } |
427 | |
428 | // Constructors. |
429 | explicit PragmaStack(const ValueType &Default) |
430 | : DefaultValue(Default), CurrentValue(Default) {} |
431 | |
432 | bool hasValue() const { return CurrentValue != DefaultValue; } |
433 | |
434 | SmallVector<Slot, 2> Stack; |
435 | ValueType DefaultValue; // Value used for PSK_Reset action. |
436 | ValueType CurrentValue; |
437 | SourceLocation CurrentPragmaLocation; |
438 | }; |
439 | // FIXME: We should serialize / deserialize these if they occur in a PCH (but |
440 | // we shouldn't do so if they're in a module). |
441 | |
442 | /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft |
443 | /// C++ ABI. Possible values are 0, 1, and 2, which mean: |
444 | /// |
445 | /// 0: Suppress all vtordisps |
446 | /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial |
447 | /// structors |
448 | /// 2: Always insert vtordisps to support RTTI on partially constructed |
449 | /// objects |
450 | PragmaStack<MSVtorDispAttr::Mode> VtorDispStack; |
451 | // #pragma pack. |
452 | // Sentinel to represent when the stack is set to mac68k alignment. |
453 | static const unsigned kMac68kAlignmentSentinel = ~0U; |
454 | PragmaStack<unsigned> PackStack; |
455 | // The current #pragma pack values and locations at each #include. |
456 | struct PackIncludeState { |
457 | unsigned CurrentValue; |
458 | SourceLocation CurrentPragmaLocation; |
459 | bool HasNonDefaultValue, ShouldWarnOnInclude; |
460 | }; |
461 | SmallVector<PackIncludeState, 8> PackIncludeStack; |
462 | // Segment #pragmas. |
463 | PragmaStack<StringLiteral *> DataSegStack; |
464 | PragmaStack<StringLiteral *> BSSSegStack; |
465 | PragmaStack<StringLiteral *> ConstSegStack; |
466 | PragmaStack<StringLiteral *> CodeSegStack; |
467 | |
468 | // RAII object to push / pop sentinel slots for all MS #pragma stacks. |
469 | // Actions should be performed only if we enter / exit a C++ method body. |
470 | class PragmaStackSentinelRAII { |
471 | public: |
472 | PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); |
473 | ~PragmaStackSentinelRAII(); |
474 | |
475 | private: |
476 | Sema &S; |
477 | StringRef SlotLabel; |
478 | bool ShouldAct; |
479 | }; |
480 | |
481 | /// A mapping that describes the nullability we've seen in each header file. |
482 | FileNullabilityMap NullabilityMap; |
483 | |
484 | /// Last section used with #pragma init_seg. |
485 | StringLiteral *CurInitSeg; |
486 | SourceLocation CurInitSegLoc; |
487 | |
488 | /// VisContext - Manages the stack for \#pragma GCC visibility. |
489 | void *VisContext; // Really a "PragmaVisStack*" |
490 | |
491 | /// \brief This represents the stack of attributes that were pushed by |
492 | /// \#pragma clang attribute. |
493 | struct PragmaAttributeEntry { |
494 | SourceLocation Loc; |
495 | AttributeList *Attribute; |
496 | SmallVector<attr::SubjectMatchRule, 4> MatchRules; |
497 | bool IsUsed; |
498 | }; |
499 | SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack; |
500 | |
501 | /// \brief The declaration that is currently receiving an attribute from the |
502 | /// #pragma attribute stack. |
503 | const Decl *PragmaAttributeCurrentTargetDecl; |
504 | |
505 | /// \brief This represents the last location of a "#pragma clang optimize off" |
506 | /// directive if such a directive has not been closed by an "on" yet. If |
507 | /// optimizations are currently "on", this is set to an invalid location. |
508 | SourceLocation OptimizeOffPragmaLocation; |
509 | |
510 | /// \brief Flag indicating if Sema is building a recovery call expression. |
511 | /// |
512 | /// This flag is used to avoid building recovery call expressions |
513 | /// if Sema is already doing so, which would cause infinite recursions. |
514 | bool IsBuildingRecoveryCallExpr; |
515 | |
516 | /// Used to control the generation of ExprWithCleanups. |
517 | CleanupInfo Cleanup; |
518 | |
519 | /// ExprCleanupObjects - This is the stack of objects requiring |
520 | /// cleanup that are created by the current full expression. The |
521 | /// element type here is ExprWithCleanups::Object. |
522 | SmallVector<BlockDecl*, 8> ExprCleanupObjects; |
523 | |
524 | /// \brief Store a list of either DeclRefExprs or MemberExprs |
525 | /// that contain a reference to a variable (constant) that may or may not |
526 | /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue |
527 | /// and discarded value conversions have been applied to all subexpressions |
528 | /// of the enclosing full expression. This is cleared at the end of each |
529 | /// full expression. |
530 | llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs; |
531 | |
532 | /// \brief Stack containing information about each of the nested |
533 | /// function, block, and method scopes that are currently active. |
534 | /// |
535 | /// This array is never empty. Clients should ignore the first |
536 | /// element, which is used to cache a single FunctionScopeInfo |
537 | /// that's used to parse every top-level function. |
538 | SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; |
539 | |
540 | typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, |
541 | &ExternalSemaSource::ReadExtVectorDecls, 2, 2> |
542 | ExtVectorDeclsType; |
543 | |
544 | /// ExtVectorDecls - This is a list all the extended vector types. This allows |
545 | /// us to associate a raw vector type with one of the ext_vector type names. |
546 | /// This is only necessary for issuing pretty diagnostics. |
547 | ExtVectorDeclsType ExtVectorDecls; |
548 | |
549 | /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. |
550 | std::unique_ptr<CXXFieldCollector> FieldCollector; |
551 | |
552 | typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType; |
553 | |
554 | /// \brief Set containing all declared private fields that are not used. |
555 | NamedDeclSetType UnusedPrivateFields; |
556 | |
557 | /// \brief Set containing all typedefs that are likely unused. |
558 | llvm::SmallSetVector<const TypedefNameDecl *, 4> |
559 | UnusedLocalTypedefNameCandidates; |
560 | |
561 | /// \brief Delete-expressions to be analyzed at the end of translation unit |
562 | /// |
563 | /// This list contains class members, and locations of delete-expressions |
564 | /// that could not be proven as to whether they mismatch with new-expression |
565 | /// used in initializer of the field. |
566 | typedef std::pair<SourceLocation, bool> DeleteExprLoc; |
567 | typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; |
568 | llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; |
569 | |
570 | typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; |
571 | |
572 | /// PureVirtualClassDiagSet - a set of class declarations which we have |
573 | /// emitted a list of pure virtual functions. Used to prevent emitting the |
574 | /// same list more than once. |
575 | std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; |
576 | |
577 | /// ParsingInitForAutoVars - a set of declarations with auto types for which |
578 | /// we are currently parsing the initializer. |
579 | llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; |
580 | |
581 | /// \brief Look for a locally scoped extern "C" declaration by the given name. |
582 | NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); |
583 | |
584 | typedef LazyVector<VarDecl *, ExternalSemaSource, |
585 | &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> |
586 | TentativeDefinitionsType; |
587 | |
588 | /// \brief All the tentative definitions encountered in the TU. |
589 | TentativeDefinitionsType TentativeDefinitions; |
590 | |
591 | typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, |
592 | &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> |
593 | UnusedFileScopedDeclsType; |
594 | |
595 | /// \brief The set of file scoped decls seen so far that have not been used |
596 | /// and must warn if not used. Only contains the first declaration. |
597 | UnusedFileScopedDeclsType UnusedFileScopedDecls; |
598 | |
599 | typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, |
600 | &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> |
601 | DelegatingCtorDeclsType; |
602 | |
603 | /// \brief All the delegating constructors seen so far in the file, used for |
604 | /// cycle detection at the end of the TU. |
605 | DelegatingCtorDeclsType DelegatingCtorDecls; |
606 | |
607 | /// \brief All the overriding functions seen during a class definition |
608 | /// that had their exception spec checks delayed, plus the overridden |
609 | /// function. |
610 | SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> |
611 | DelayedExceptionSpecChecks; |
612 | |
613 | /// \brief All the members seen during a class definition which were both |
614 | /// explicitly defaulted and had explicitly-specified exception |
615 | /// specifications, along with the function type containing their |
616 | /// user-specified exception specification. Those exception specifications |
617 | /// were overridden with the default specifications, but we still need to |
618 | /// check whether they are compatible with the default specification, and |
619 | /// we can't do that until the nesting set of class definitions is complete. |
620 | SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2> |
621 | DelayedDefaultedMemberExceptionSpecs; |
622 | |
623 | typedef llvm::MapVector<const FunctionDecl *, |
624 | std::unique_ptr<LateParsedTemplate>> |
625 | LateParsedTemplateMapT; |
626 | LateParsedTemplateMapT LateParsedTemplateMap; |
627 | |
628 | /// \brief Callback to the parser to parse templated functions when needed. |
629 | typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); |
630 | typedef void LateTemplateParserCleanupCB(void *P); |
631 | LateTemplateParserCB *LateTemplateParser; |
632 | LateTemplateParserCleanupCB *LateTemplateParserCleanup; |
633 | void *OpaqueParser; |
634 | |
635 | void SetLateTemplateParser(LateTemplateParserCB *LTP, |
636 | LateTemplateParserCleanupCB *LTPCleanup, |
637 | void *P) { |
638 | LateTemplateParser = LTP; |
639 | LateTemplateParserCleanup = LTPCleanup; |
640 | OpaqueParser = P; |
641 | } |
642 | |
643 | class DelayedDiagnostics; |
644 | |
645 | class DelayedDiagnosticsState { |
646 | sema::DelayedDiagnosticPool *SavedPool; |
647 | friend class Sema::DelayedDiagnostics; |
648 | }; |
649 | typedef DelayedDiagnosticsState ParsingDeclState; |
650 | typedef DelayedDiagnosticsState ProcessingContextState; |
651 | |
652 | /// A class which encapsulates the logic for delaying diagnostics |
653 | /// during parsing and other processing. |
654 | class DelayedDiagnostics { |
655 | /// \brief The current pool of diagnostics into which delayed |
656 | /// diagnostics should go. |
657 | sema::DelayedDiagnosticPool *CurPool; |
658 | |
659 | public: |
660 | DelayedDiagnostics() : CurPool(nullptr) {} |
661 | |
662 | /// Adds a delayed diagnostic. |
663 | void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h |
664 | |
665 | /// Determines whether diagnostics should be delayed. |
666 | bool shouldDelayDiagnostics() { return CurPool != nullptr; } |
667 | |
668 | /// Returns the current delayed-diagnostics pool. |
669 | sema::DelayedDiagnosticPool *getCurrentPool() const { |
670 | return CurPool; |
671 | } |
672 | |
673 | /// Enter a new scope. Access and deprecation diagnostics will be |
674 | /// collected in this pool. |
675 | DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { |
676 | DelayedDiagnosticsState state; |
677 | state.SavedPool = CurPool; |
678 | CurPool = &pool; |
679 | return state; |
680 | } |
681 | |
682 | /// Leave a delayed-diagnostic state that was previously pushed. |
683 | /// Do not emit any of the diagnostics. This is performed as part |
684 | /// of the bookkeeping of popping a pool "properly". |
685 | void popWithoutEmitting(DelayedDiagnosticsState state) { |
686 | CurPool = state.SavedPool; |
687 | } |
688 | |
689 | /// Enter a new scope where access and deprecation diagnostics are |
690 | /// not delayed. |
691 | DelayedDiagnosticsState pushUndelayed() { |
692 | DelayedDiagnosticsState state; |
693 | state.SavedPool = CurPool; |
694 | CurPool = nullptr; |
695 | return state; |
696 | } |
697 | |
698 | /// Undo a previous pushUndelayed(). |
699 | void popUndelayed(DelayedDiagnosticsState state) { |
700 | assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail ("CurPool == nullptr", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 700, __extension__ __PRETTY_FUNCTION__)); |
701 | CurPool = state.SavedPool; |
702 | } |
703 | } DelayedDiagnostics; |
704 | |
705 | /// A RAII object to temporarily push a declaration context. |
706 | class ContextRAII { |
707 | private: |
708 | Sema &S; |
709 | DeclContext *SavedContext; |
710 | ProcessingContextState SavedContextState; |
711 | QualType SavedCXXThisTypeOverride; |
712 | |
713 | public: |
714 | ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) |
715 | : S(S), SavedContext(S.CurContext), |
716 | SavedContextState(S.DelayedDiagnostics.pushUndelayed()), |
717 | SavedCXXThisTypeOverride(S.CXXThisTypeOverride) |
718 | { |
719 | assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context" ) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 719, __extension__ __PRETTY_FUNCTION__)); |
720 | S.CurContext = ContextToPush; |
721 | if (NewThisContext) |
722 | S.CXXThisTypeOverride = QualType(); |
723 | } |
724 | |
725 | void pop() { |
726 | if (!SavedContext) return; |
727 | S.CurContext = SavedContext; |
728 | S.DelayedDiagnostics.popUndelayed(SavedContextState); |
729 | S.CXXThisTypeOverride = SavedCXXThisTypeOverride; |
730 | SavedContext = nullptr; |
731 | } |
732 | |
733 | ~ContextRAII() { |
734 | pop(); |
735 | } |
736 | }; |
737 | |
738 | /// \brief RAII object to handle the state changes required to synthesize |
739 | /// a function body. |
740 | class SynthesizedFunctionScope { |
741 | Sema &S; |
742 | Sema::ContextRAII SavedContext; |
743 | bool PushedCodeSynthesisContext = false; |
744 | |
745 | public: |
746 | SynthesizedFunctionScope(Sema &S, DeclContext *DC) |
747 | : S(S), SavedContext(S, DC) { |
748 | S.PushFunctionScope(); |
749 | S.PushExpressionEvaluationContext( |
750 | Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
751 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) |
752 | FD->setWillHaveBody(true); |
753 | else |
754 | assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void (0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 754, __extension__ __PRETTY_FUNCTION__)); |
755 | } |
756 | |
757 | void addContextNote(SourceLocation UseLoc) { |
758 | assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void (0) : __assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 758, __extension__ __PRETTY_FUNCTION__)); |
759 | |
760 | Sema::CodeSynthesisContext Ctx; |
761 | Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; |
762 | Ctx.PointOfInstantiation = UseLoc; |
763 | Ctx.Entity = cast<Decl>(S.CurContext); |
764 | S.pushCodeSynthesisContext(Ctx); |
765 | |
766 | PushedCodeSynthesisContext = true; |
767 | } |
768 | |
769 | ~SynthesizedFunctionScope() { |
770 | if (PushedCodeSynthesisContext) |
771 | S.popCodeSynthesisContext(); |
772 | if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) |
773 | FD->setWillHaveBody(false); |
774 | S.PopExpressionEvaluationContext(); |
775 | S.PopFunctionScopeInfo(); |
776 | } |
777 | }; |
778 | |
779 | /// WeakUndeclaredIdentifiers - Identifiers contained in |
780 | /// \#pragma weak before declared. rare. may alias another |
781 | /// identifier, declared or undeclared |
782 | llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; |
783 | |
784 | /// ExtnameUndeclaredIdentifiers - Identifiers contained in |
785 | /// \#pragma redefine_extname before declared. Used in Solaris system headers |
786 | /// to define functions that occur in multiple standards to call the version |
787 | /// in the currently selected standard. |
788 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; |
789 | |
790 | |
791 | /// \brief Load weak undeclared identifiers from the external source. |
792 | void LoadExternalWeakUndeclaredIdentifiers(); |
793 | |
794 | /// WeakTopLevelDecl - Translation-unit scoped declarations generated by |
795 | /// \#pragma weak during processing of other Decls. |
796 | /// I couldn't figure out a clean way to generate these in-line, so |
797 | /// we store them here and handle separately -- which is a hack. |
798 | /// It would be best to refactor this. |
799 | SmallVector<Decl*,2> WeakTopLevelDecl; |
800 | |
801 | IdentifierResolver IdResolver; |
802 | |
803 | /// Translation Unit Scope - useful to Objective-C actions that need |
804 | /// to lookup file scope declarations in the "ordinary" C decl namespace. |
805 | /// For example, user-defined classes, built-in "id" type, etc. |
806 | Scope *TUScope; |
807 | |
808 | /// \brief The C++ "std" namespace, where the standard library resides. |
809 | LazyDeclPtr StdNamespace; |
810 | |
811 | /// \brief The C++ "std::bad_alloc" class, which is defined by the C++ |
812 | /// standard library. |
813 | LazyDeclPtr StdBadAlloc; |
814 | |
815 | /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++ |
816 | /// standard library. |
817 | LazyDeclPtr StdAlignValT; |
818 | |
819 | /// \brief The C++ "std::experimental" namespace, where the experimental parts |
820 | /// of the standard library resides. |
821 | NamespaceDecl *StdExperimentalNamespaceCache; |
822 | |
823 | /// \brief The C++ "std::initializer_list" template, which is defined in |
824 | /// \<initializer_list>. |
825 | ClassTemplateDecl *StdInitializerList; |
826 | |
827 | /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>. |
828 | RecordDecl *CXXTypeInfoDecl; |
829 | |
830 | /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files. |
831 | RecordDecl *MSVCGuidDecl; |
832 | |
833 | /// \brief Caches identifiers/selectors for NSFoundation APIs. |
834 | std::unique_ptr<NSAPI> NSAPIObj; |
835 | |
836 | /// \brief The declaration of the Objective-C NSNumber class. |
837 | ObjCInterfaceDecl *NSNumberDecl; |
838 | |
839 | /// \brief The declaration of the Objective-C NSValue class. |
840 | ObjCInterfaceDecl *NSValueDecl; |
841 | |
842 | /// \brief Pointer to NSNumber type (NSNumber *). |
843 | QualType NSNumberPointer; |
844 | |
845 | /// \brief Pointer to NSValue type (NSValue *). |
846 | QualType NSValuePointer; |
847 | |
848 | /// \brief The Objective-C NSNumber methods used to create NSNumber literals. |
849 | ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; |
850 | |
851 | /// \brief The declaration of the Objective-C NSString class. |
852 | ObjCInterfaceDecl *NSStringDecl; |
853 | |
854 | /// \brief Pointer to NSString type (NSString *). |
855 | QualType NSStringPointer; |
856 | |
857 | /// \brief The declaration of the stringWithUTF8String: method. |
858 | ObjCMethodDecl *StringWithUTF8StringMethod; |
859 | |
860 | /// \brief The declaration of the valueWithBytes:objCType: method. |
861 | ObjCMethodDecl *ValueWithBytesObjCTypeMethod; |
862 | |
863 | /// \brief The declaration of the Objective-C NSArray class. |
864 | ObjCInterfaceDecl *NSArrayDecl; |
865 | |
866 | /// \brief The declaration of the arrayWithObjects:count: method. |
867 | ObjCMethodDecl *ArrayWithObjectsMethod; |
868 | |
869 | /// \brief The declaration of the Objective-C NSDictionary class. |
870 | ObjCInterfaceDecl *NSDictionaryDecl; |
871 | |
872 | /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method. |
873 | ObjCMethodDecl *DictionaryWithObjectsMethod; |
874 | |
875 | /// \brief id<NSCopying> type. |
876 | QualType QIDNSCopying; |
877 | |
878 | /// \brief will hold 'respondsToSelector:' |
879 | Selector RespondsToSelectorSel; |
880 | |
881 | /// A flag to remember whether the implicit forms of operator new and delete |
882 | /// have been declared. |
883 | bool GlobalNewDeleteDeclared; |
884 | |
885 | /// A flag to indicate that we're in a context that permits abstract |
886 | /// references to fields. This is really a |
887 | bool AllowAbstractFieldReference; |
888 | |
889 | /// \brief Describes how the expressions currently being parsed are |
890 | /// evaluated at run-time, if at all. |
891 | enum class ExpressionEvaluationContext { |
892 | /// \brief The current expression and its subexpressions occur within an |
893 | /// unevaluated operand (C++11 [expr]p7), such as the subexpression of |
894 | /// \c sizeof, where the type of the expression may be significant but |
895 | /// no code will be generated to evaluate the value of the expression at |
896 | /// run time. |
897 | Unevaluated, |
898 | |
899 | /// \brief The current expression occurs within a braced-init-list within |
900 | /// an unevaluated operand. This is mostly like a regular unevaluated |
901 | /// context, except that we still instantiate constexpr functions that are |
902 | /// referenced here so that we can perform narrowing checks correctly. |
903 | UnevaluatedList, |
904 | |
905 | /// \brief The current expression occurs within a discarded statement. |
906 | /// This behaves largely similarly to an unevaluated operand in preventing |
907 | /// definitions from being required, but not in other ways. |
908 | DiscardedStatement, |
909 | |
910 | /// \brief The current expression occurs within an unevaluated |
911 | /// operand that unconditionally permits abstract references to |
912 | /// fields, such as a SIZE operator in MS-style inline assembly. |
913 | UnevaluatedAbstract, |
914 | |
915 | /// \brief The current context is "potentially evaluated" in C++11 terms, |
916 | /// but the expression is evaluated at compile-time (like the values of |
917 | /// cases in a switch statement). |
918 | ConstantEvaluated, |
919 | |
920 | /// \brief The current expression is potentially evaluated at run time, |
921 | /// which means that code may be generated to evaluate the value of the |
922 | /// expression at run time. |
923 | PotentiallyEvaluated, |
924 | |
925 | /// \brief The current expression is potentially evaluated, but any |
926 | /// declarations referenced inside that expression are only used if |
927 | /// in fact the current expression is used. |
928 | /// |
929 | /// This value is used when parsing default function arguments, for which |
930 | /// we would like to provide diagnostics (e.g., passing non-POD arguments |
931 | /// through varargs) but do not want to mark declarations as "referenced" |
932 | /// until the default argument is used. |
933 | PotentiallyEvaluatedIfUsed |
934 | }; |
935 | |
936 | /// \brief Data structure used to record current or nested |
937 | /// expression evaluation contexts. |
938 | struct ExpressionEvaluationContextRecord { |
939 | /// \brief The expression evaluation context. |
940 | ExpressionEvaluationContext Context; |
941 | |
942 | /// \brief Whether the enclosing context needed a cleanup. |
943 | CleanupInfo ParentCleanup; |
944 | |
945 | /// \brief Whether we are in a decltype expression. |
946 | bool IsDecltype; |
947 | |
948 | /// \brief The number of active cleanup objects when we entered |
949 | /// this expression evaluation context. |
950 | unsigned NumCleanupObjects; |
951 | |
952 | /// \brief The number of typos encountered during this expression evaluation |
953 | /// context (i.e. the number of TypoExprs created). |
954 | unsigned NumTypos; |
955 | |
956 | llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs; |
957 | |
958 | /// \brief The lambdas that are present within this context, if it |
959 | /// is indeed an unevaluated context. |
960 | SmallVector<LambdaExpr *, 2> Lambdas; |
961 | |
962 | /// \brief The declaration that provides context for lambda expressions |
963 | /// and block literals if the normal declaration context does not |
964 | /// suffice, e.g., in a default function argument. |
965 | Decl *ManglingContextDecl; |
966 | |
967 | /// \brief The context information used to mangle lambda expressions |
968 | /// and block literals within this context. |
969 | /// |
970 | /// This mangling information is allocated lazily, since most contexts |
971 | /// do not have lambda expressions or block literals. |
972 | std::unique_ptr<MangleNumberingContext> MangleNumbering; |
973 | |
974 | /// \brief If we are processing a decltype type, a set of call expressions |
975 | /// for which we have deferred checking the completeness of the return type. |
976 | SmallVector<CallExpr *, 8> DelayedDecltypeCalls; |
977 | |
978 | /// \brief If we are processing a decltype type, a set of temporary binding |
979 | /// expressions for which we have deferred checking the destructor. |
980 | SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; |
981 | |
982 | ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, |
983 | unsigned NumCleanupObjects, |
984 | CleanupInfo ParentCleanup, |
985 | Decl *ManglingContextDecl, |
986 | bool IsDecltype) |
987 | : Context(Context), ParentCleanup(ParentCleanup), |
988 | IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects), |
989 | NumTypos(0), |
990 | ManglingContextDecl(ManglingContextDecl), MangleNumbering() { } |
991 | |
992 | /// \brief Retrieve the mangling numbering context, used to consistently |
993 | /// number constructs like lambdas for mangling. |
994 | MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx); |
995 | |
996 | bool isUnevaluated() const { |
997 | return Context == ExpressionEvaluationContext::Unevaluated || |
998 | Context == ExpressionEvaluationContext::UnevaluatedAbstract || |
999 | Context == ExpressionEvaluationContext::UnevaluatedList; |
1000 | } |
1001 | bool isConstantEvaluated() const { |
1002 | return Context == ExpressionEvaluationContext::ConstantEvaluated; |
1003 | } |
1004 | }; |
1005 | |
1006 | /// A stack of expression evaluation contexts. |
1007 | SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; |
1008 | |
1009 | /// \brief Compute the mangling number context for a lambda expression or |
1010 | /// block literal. |
1011 | /// |
1012 | /// \param DC - The DeclContext containing the lambda expression or |
1013 | /// block literal. |
1014 | /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl |
1015 | /// associated with the context, if relevant. |
1016 | MangleNumberingContext *getCurrentMangleNumberContext( |
1017 | const DeclContext *DC, |
1018 | Decl *&ManglingContextDecl); |
1019 | |
1020 | |
1021 | /// SpecialMemberOverloadResult - The overloading result for a special member |
1022 | /// function. |
1023 | /// |
1024 | /// This is basically a wrapper around PointerIntPair. The lowest bits of the |
1025 | /// integer are used to determine whether overload resolution succeeded. |
1026 | class SpecialMemberOverloadResult { |
1027 | public: |
1028 | enum Kind { |
1029 | NoMemberOrDeleted, |
1030 | Ambiguous, |
1031 | Success |
1032 | }; |
1033 | |
1034 | private: |
1035 | llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; |
1036 | |
1037 | public: |
1038 | SpecialMemberOverloadResult() : Pair() {} |
1039 | SpecialMemberOverloadResult(CXXMethodDecl *MD) |
1040 | : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} |
1041 | |
1042 | CXXMethodDecl *getMethod() const { return Pair.getPointer(); } |
1043 | void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } |
1044 | |
1045 | Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } |
1046 | void setKind(Kind K) { Pair.setInt(K); } |
1047 | }; |
1048 | |
1049 | class SpecialMemberOverloadResultEntry |
1050 | : public llvm::FastFoldingSetNode, |
1051 | public SpecialMemberOverloadResult { |
1052 | public: |
1053 | SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) |
1054 | : FastFoldingSetNode(ID) |
1055 | {} |
1056 | }; |
1057 | |
1058 | /// \brief A cache of special member function overload resolution results |
1059 | /// for C++ records. |
1060 | llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; |
1061 | |
1062 | /// \brief A cache of the flags available in enumerations with the flag_bits |
1063 | /// attribute. |
1064 | mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; |
1065 | |
1066 | /// \brief The kind of translation unit we are processing. |
1067 | /// |
1068 | /// When we're processing a complete translation unit, Sema will perform |
1069 | /// end-of-translation-unit semantic tasks (such as creating |
1070 | /// initializers for tentative definitions in C) once parsing has |
1071 | /// completed. Modules and precompiled headers perform different kinds of |
1072 | /// checks. |
1073 | TranslationUnitKind TUKind; |
1074 | |
1075 | llvm::BumpPtrAllocator BumpAlloc; |
1076 | |
1077 | /// \brief The number of SFINAE diagnostics that have been trapped. |
1078 | unsigned NumSFINAEErrors; |
1079 | |
1080 | typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> |
1081 | UnparsedDefaultArgInstantiationsMap; |
1082 | |
1083 | /// \brief A mapping from parameters with unparsed default arguments to the |
1084 | /// set of instantiations of each parameter. |
1085 | /// |
1086 | /// This mapping is a temporary data structure used when parsing |
1087 | /// nested class templates or nested classes of class templates, |
1088 | /// where we might end up instantiating an inner class before the |
1089 | /// default arguments of its methods have been parsed. |
1090 | UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; |
1091 | |
1092 | // Contains the locations of the beginning of unparsed default |
1093 | // argument locations. |
1094 | llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; |
1095 | |
1096 | /// UndefinedInternals - all the used, undefined objects which require a |
1097 | /// definition in this translation unit. |
1098 | llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; |
1099 | |
1100 | /// Determine if VD, which must be a variable or function, is an external |
1101 | /// symbol that nonetheless can't be referenced from outside this translation |
1102 | /// unit because its type has no linkage and it's not extern "C". |
1103 | bool isExternalWithNoLinkageType(ValueDecl *VD); |
1104 | |
1105 | /// Obtain a sorted list of functions that are undefined but ODR-used. |
1106 | void getUndefinedButUsed( |
1107 | SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); |
1108 | |
1109 | /// Retrieves list of suspicious delete-expressions that will be checked at |
1110 | /// the end of translation unit. |
1111 | const llvm::MapVector<FieldDecl *, DeleteLocs> & |
1112 | getMismatchingDeleteExpressions() const; |
1113 | |
1114 | typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; |
1115 | typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; |
1116 | |
1117 | /// Method Pool - allows efficient lookup when typechecking messages to "id". |
1118 | /// We need to maintain a list, since selectors can have differing signatures |
1119 | /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% |
1120 | /// of selectors are "overloaded"). |
1121 | /// At the head of the list it is recorded whether there were 0, 1, or >= 2 |
1122 | /// methods inside categories with a particular selector. |
1123 | GlobalMethodPool MethodPool; |
1124 | |
1125 | /// Method selectors used in a \@selector expression. Used for implementation |
1126 | /// of -Wselector. |
1127 | llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; |
1128 | |
1129 | /// Kinds of C++ special members. |
1130 | enum CXXSpecialMember { |
1131 | CXXDefaultConstructor, |
1132 | CXXCopyConstructor, |
1133 | CXXMoveConstructor, |
1134 | CXXCopyAssignment, |
1135 | CXXMoveAssignment, |
1136 | CXXDestructor, |
1137 | CXXInvalid |
1138 | }; |
1139 | |
1140 | typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> |
1141 | SpecialMemberDecl; |
1142 | |
1143 | /// The C++ special members which we are currently in the process of |
1144 | /// declaring. If this process recursively triggers the declaration of the |
1145 | /// same special member, we should act as if it is not yet declared. |
1146 | llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; |
1147 | |
1148 | /// The function definitions which were renamed as part of typo-correction |
1149 | /// to match their respective declarations. We want to keep track of them |
1150 | /// to ensure that we don't emit a "redefinition" error if we encounter a |
1151 | /// correctly named definition after the renamed definition. |
1152 | llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; |
1153 | |
1154 | /// Stack of types that correspond to the parameter entities that are |
1155 | /// currently being copy-initialized. Can be empty. |
1156 | llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; |
1157 | |
1158 | void ReadMethodPool(Selector Sel); |
1159 | void updateOutOfDateSelector(Selector Sel); |
1160 | |
1161 | /// Private Helper predicate to check for 'self'. |
1162 | bool isSelfExpr(Expr *RExpr); |
1163 | bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); |
1164 | |
1165 | /// \brief Cause the active diagnostic on the DiagosticsEngine to be |
1166 | /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and |
1167 | /// should not be used elsewhere. |
1168 | void EmitCurrentDiagnostic(unsigned DiagID); |
1169 | |
1170 | /// Records and restores the FP_CONTRACT state on entry/exit of compound |
1171 | /// statements. |
1172 | class FPContractStateRAII { |
1173 | public: |
1174 | FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {} |
1175 | ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; } |
1176 | |
1177 | private: |
1178 | Sema& S; |
1179 | FPOptions OldFPFeaturesState; |
1180 | }; |
1181 | |
1182 | void addImplicitTypedef(StringRef Name, QualType T); |
1183 | |
1184 | public: |
1185 | Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, |
1186 | TranslationUnitKind TUKind = TU_Complete, |
1187 | CodeCompleteConsumer *CompletionConsumer = nullptr); |
1188 | ~Sema(); |
1189 | |
1190 | /// \brief Perform initialization that occurs after the parser has been |
1191 | /// initialized but before it parses anything. |
1192 | void Initialize(); |
1193 | |
1194 | const LangOptions &getLangOpts() const { return LangOpts; } |
1195 | OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } |
1196 | FPOptions &getFPOptions() { return FPFeatures; } |
1197 | |
1198 | DiagnosticsEngine &getDiagnostics() const { return Diags; } |
1199 | SourceManager &getSourceManager() const { return SourceMgr; } |
1200 | Preprocessor &getPreprocessor() const { return PP; } |
1201 | ASTContext &getASTContext() const { return Context; } |
1202 | ASTConsumer &getASTConsumer() const { return Consumer; } |
1203 | ASTMutationListener *getASTMutationListener() const; |
1204 | ExternalSemaSource* getExternalSource() const { return ExternalSource; } |
1205 | |
1206 | ///\brief Registers an external source. If an external source already exists, |
1207 | /// creates a multiplex external source and appends to it. |
1208 | /// |
1209 | ///\param[in] E - A non-null external sema source. |
1210 | /// |
1211 | void addExternalSource(ExternalSemaSource *E); |
1212 | |
1213 | void PrintStats() const; |
1214 | |
1215 | /// \brief Helper class that creates diagnostics with optional |
1216 | /// template instantiation stacks. |
1217 | /// |
1218 | /// This class provides a wrapper around the basic DiagnosticBuilder |
1219 | /// class that emits diagnostics. SemaDiagnosticBuilder is |
1220 | /// responsible for emitting the diagnostic (as DiagnosticBuilder |
1221 | /// does) and, if the diagnostic comes from inside a template |
1222 | /// instantiation, printing the template instantiation stack as |
1223 | /// well. |
1224 | class SemaDiagnosticBuilder : public DiagnosticBuilder { |
1225 | Sema &SemaRef; |
1226 | unsigned DiagID; |
1227 | |
1228 | public: |
1229 | SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) |
1230 | : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } |
1231 | |
1232 | // This is a cunning lie. DiagnosticBuilder actually performs move |
1233 | // construction in its copy constructor (but due to varied uses, it's not |
1234 | // possible to conveniently express this as actual move construction). So |
1235 | // the default copy ctor here is fine, because the base class disables the |
1236 | // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op |
1237 | // in that case anwyay. |
1238 | SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; |
1239 | |
1240 | ~SemaDiagnosticBuilder() { |
1241 | // If we aren't active, there is nothing to do. |
1242 | if (!isActive()) return; |
1243 | |
1244 | // Otherwise, we need to emit the diagnostic. First flush the underlying |
1245 | // DiagnosticBuilder data, and clear the diagnostic builder itself so it |
1246 | // won't emit the diagnostic in its own destructor. |
1247 | // |
1248 | // This seems wasteful, in that as written the DiagnosticBuilder dtor will |
1249 | // do its own needless checks to see if the diagnostic needs to be |
1250 | // emitted. However, because we take care to ensure that the builder |
1251 | // objects never escape, a sufficiently smart compiler will be able to |
1252 | // eliminate that code. |
1253 | FlushCounts(); |
1254 | Clear(); |
1255 | |
1256 | // Dispatch to Sema to emit the diagnostic. |
1257 | SemaRef.EmitCurrentDiagnostic(DiagID); |
1258 | } |
1259 | |
1260 | /// Teach operator<< to produce an object of the correct type. |
1261 | template<typename T> |
1262 | friend const SemaDiagnosticBuilder &operator<<( |
1263 | const SemaDiagnosticBuilder &Diag, const T &Value) { |
1264 | const DiagnosticBuilder &BaseDiag = Diag; |
1265 | BaseDiag << Value; |
1266 | return Diag; |
1267 | } |
1268 | }; |
1269 | |
1270 | /// \brief Emit a diagnostic. |
1271 | SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { |
1272 | DiagnosticBuilder DB = Diags.Report(Loc, DiagID); |
1273 | return SemaDiagnosticBuilder(DB, *this, DiagID); |
1274 | } |
1275 | |
1276 | /// \brief Emit a partial diagnostic. |
1277 | SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); |
1278 | |
1279 | /// \brief Build a partial diagnostic. |
1280 | PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h |
1281 | |
1282 | bool findMacroSpelling(SourceLocation &loc, StringRef name); |
1283 | |
1284 | /// \brief Get a string to suggest for zero-initialization of a type. |
1285 | std::string |
1286 | getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; |
1287 | std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; |
1288 | |
1289 | /// \brief Calls \c Lexer::getLocForEndOfToken() |
1290 | SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); |
1291 | |
1292 | /// \brief Retrieve the module loader associated with the preprocessor. |
1293 | ModuleLoader &getModuleLoader() const; |
1294 | |
1295 | void emitAndClearUnusedLocalTypedefWarnings(); |
1296 | |
1297 | void ActOnStartOfTranslationUnit(); |
1298 | void ActOnEndOfTranslationUnit(); |
1299 | |
1300 | void CheckDelegatingCtorCycles(); |
1301 | |
1302 | Scope *getScopeForContext(DeclContext *Ctx); |
1303 | |
1304 | void PushFunctionScope(); |
1305 | void PushBlockScope(Scope *BlockScope, BlockDecl *Block); |
1306 | sema::LambdaScopeInfo *PushLambdaScope(); |
1307 | |
1308 | /// \brief This is used to inform Sema what the current TemplateParameterDepth |
1309 | /// is during Parsing. Currently it is used to pass on the depth |
1310 | /// when parsing generic lambda 'auto' parameters. |
1311 | void RecordParsingTemplateParameterDepth(unsigned Depth); |
1312 | |
1313 | void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, |
1314 | RecordDecl *RD, |
1315 | CapturedRegionKind K); |
1316 | void |
1317 | PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, |
1318 | const Decl *D = nullptr, |
1319 | const BlockExpr *blkExpr = nullptr); |
1320 | |
1321 | sema::FunctionScopeInfo *getCurFunction() const { |
1322 | return FunctionScopes.back(); |
1323 | } |
1324 | |
1325 | sema::FunctionScopeInfo *getEnclosingFunction() const { |
1326 | if (FunctionScopes.empty()) |
1327 | return nullptr; |
1328 | |
1329 | for (int e = FunctionScopes.size()-1; e >= 0; --e) { |
1330 | if (isa<sema::BlockScopeInfo>(FunctionScopes[e])) |
1331 | continue; |
1332 | return FunctionScopes[e]; |
1333 | } |
1334 | return nullptr; |
1335 | } |
1336 | |
1337 | template <typename ExprT> |
1338 | void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) { |
1339 | if (!isUnevaluatedContext()) |
1340 | getCurFunction()->recordUseOfWeak(E, IsRead); |
1341 | } |
1342 | |
1343 | void PushCompoundScope(bool IsStmtExpr); |
1344 | void PopCompoundScope(); |
1345 | |
1346 | sema::CompoundScopeInfo &getCurCompoundScope() const; |
1347 | |
1348 | bool hasAnyUnrecoverableErrorsInThisFunction() const; |
1349 | |
1350 | /// \brief Retrieve the current block, if any. |
1351 | sema::BlockScopeInfo *getCurBlock(); |
1352 | |
1353 | /// Retrieve the current lambda scope info, if any. |
1354 | /// \param IgnoreNonLambdaCapturingScope true if should find the top-most |
1355 | /// lambda scope info ignoring all inner capturing scopes that are not |
1356 | /// lambda scopes. |
1357 | sema::LambdaScopeInfo * |
1358 | getCurLambda(bool IgnoreNonLambdaCapturingScope = false); |
1359 | |
1360 | /// \brief Retrieve the current generic lambda info, if any. |
1361 | sema::LambdaScopeInfo *getCurGenericLambda(); |
1362 | |
1363 | /// \brief Retrieve the current captured region, if any. |
1364 | sema::CapturedRegionScopeInfo *getCurCapturedRegion(); |
1365 | |
1366 | /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls |
1367 | SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } |
1368 | |
1369 | void ActOnComment(SourceRange Comment); |
1370 | |
1371 | //===--------------------------------------------------------------------===// |
1372 | // Type Analysis / Processing: SemaType.cpp. |
1373 | // |
1374 | |
1375 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, |
1376 | const DeclSpec *DS = nullptr); |
1377 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, |
1378 | const DeclSpec *DS = nullptr); |
1379 | QualType BuildPointerType(QualType T, |
1380 | SourceLocation Loc, DeclarationName Entity); |
1381 | QualType BuildReferenceType(QualType T, bool LValueRef, |
1382 | SourceLocation Loc, DeclarationName Entity); |
1383 | QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, |
1384 | Expr *ArraySize, unsigned Quals, |
1385 | SourceRange Brackets, DeclarationName Entity); |
1386 | QualType BuildExtVectorType(QualType T, Expr *ArraySize, |
1387 | SourceLocation AttrLoc); |
1388 | QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, |
1389 | SourceLocation AttrLoc); |
1390 | |
1391 | bool CheckFunctionReturnType(QualType T, SourceLocation Loc); |
1392 | |
1393 | /// \brief Build a function type. |
1394 | /// |
1395 | /// This routine checks the function type according to C++ rules and |
1396 | /// under the assumption that the result type and parameter types have |
1397 | /// just been instantiated from a template. It therefore duplicates |
1398 | /// some of the behavior of GetTypeForDeclarator, but in a much |
1399 | /// simpler form that is only suitable for this narrow use case. |
1400 | /// |
1401 | /// \param T The return type of the function. |
1402 | /// |
1403 | /// \param ParamTypes The parameter types of the function. This array |
1404 | /// will be modified to account for adjustments to the types of the |
1405 | /// function parameters. |
1406 | /// |
1407 | /// \param Loc The location of the entity whose type involves this |
1408 | /// function type or, if there is no such entity, the location of the |
1409 | /// type that will have function type. |
1410 | /// |
1411 | /// \param Entity The name of the entity that involves the function |
1412 | /// type, if known. |
1413 | /// |
1414 | /// \param EPI Extra information about the function type. Usually this will |
1415 | /// be taken from an existing function with the same prototype. |
1416 | /// |
1417 | /// \returns A suitable function type, if there are no errors. The |
1418 | /// unqualified type will always be a FunctionProtoType. |
1419 | /// Otherwise, returns a NULL type. |
1420 | QualType BuildFunctionType(QualType T, |
1421 | MutableArrayRef<QualType> ParamTypes, |
1422 | SourceLocation Loc, DeclarationName Entity, |
1423 | const FunctionProtoType::ExtProtoInfo &EPI); |
1424 | |
1425 | QualType BuildMemberPointerType(QualType T, QualType Class, |
1426 | SourceLocation Loc, |
1427 | DeclarationName Entity); |
1428 | QualType BuildBlockPointerType(QualType T, |
1429 | SourceLocation Loc, DeclarationName Entity); |
1430 | QualType BuildParenType(QualType T); |
1431 | QualType BuildAtomicType(QualType T, SourceLocation Loc); |
1432 | QualType BuildReadPipeType(QualType T, |
1433 | SourceLocation Loc); |
1434 | QualType BuildWritePipeType(QualType T, |
1435 | SourceLocation Loc); |
1436 | |
1437 | TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); |
1438 | TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); |
1439 | TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, |
1440 | TypeSourceInfo *ReturnTypeInfo); |
1441 | |
1442 | /// \brief Package the given type and TSI into a ParsedType. |
1443 | ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); |
1444 | DeclarationNameInfo GetNameForDeclarator(Declarator &D); |
1445 | DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); |
1446 | static QualType GetTypeFromParser(ParsedType Ty, |
1447 | TypeSourceInfo **TInfo = nullptr); |
1448 | CanThrowResult canThrow(const Expr *E); |
1449 | const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, |
1450 | const FunctionProtoType *FPT); |
1451 | void UpdateExceptionSpec(FunctionDecl *FD, |
1452 | const FunctionProtoType::ExceptionSpecInfo &ESI); |
1453 | bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); |
1454 | bool CheckDistantExceptionSpec(QualType T); |
1455 | bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); |
1456 | bool CheckEquivalentExceptionSpec( |
1457 | const FunctionProtoType *Old, SourceLocation OldLoc, |
1458 | const FunctionProtoType *New, SourceLocation NewLoc); |
1459 | bool CheckEquivalentExceptionSpec( |
1460 | const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, |
1461 | const FunctionProtoType *Old, SourceLocation OldLoc, |
1462 | const FunctionProtoType *New, SourceLocation NewLoc); |
1463 | bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); |
1464 | bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, |
1465 | const PartialDiagnostic &NestedDiagID, |
1466 | const PartialDiagnostic &NoteID, |
1467 | const FunctionProtoType *Superset, |
1468 | SourceLocation SuperLoc, |
1469 | const FunctionProtoType *Subset, |
1470 | SourceLocation SubLoc); |
1471 | bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, |
1472 | const PartialDiagnostic &NoteID, |
1473 | const FunctionProtoType *Target, |
1474 | SourceLocation TargetLoc, |
1475 | const FunctionProtoType *Source, |
1476 | SourceLocation SourceLoc); |
1477 | |
1478 | TypeResult ActOnTypeName(Scope *S, Declarator &D); |
1479 | |
1480 | /// \brief The parser has parsed the context-sensitive type 'instancetype' |
1481 | /// in an Objective-C message declaration. Return the appropriate type. |
1482 | ParsedType ActOnObjCInstanceType(SourceLocation Loc); |
1483 | |
1484 | /// \brief Abstract class used to diagnose incomplete types. |
1485 | struct TypeDiagnoser { |
1486 | TypeDiagnoser() {} |
1487 | |
1488 | virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; |
1489 | virtual ~TypeDiagnoser() {} |
1490 | }; |
1491 | |
1492 | static int getPrintable(int I) { return I; } |
1493 | static unsigned getPrintable(unsigned I) { return I; } |
1494 | static bool getPrintable(bool B) { return B; } |
1495 | static const char * getPrintable(const char *S) { return S; } |
1496 | static StringRef getPrintable(StringRef S) { return S; } |
1497 | static const std::string &getPrintable(const std::string &S) { return S; } |
1498 | static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { |
1499 | return II; |
1500 | } |
1501 | static DeclarationName getPrintable(DeclarationName N) { return N; } |
1502 | static QualType getPrintable(QualType T) { return T; } |
1503 | static SourceRange getPrintable(SourceRange R) { return R; } |
1504 | static SourceRange getPrintable(SourceLocation L) { return L; } |
1505 | static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } |
1506 | static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} |
1507 | |
1508 | template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { |
1509 | unsigned DiagID; |
1510 | std::tuple<const Ts &...> Args; |
1511 | |
1512 | template <std::size_t... Is> |
1513 | void emit(const SemaDiagnosticBuilder &DB, |
1514 | llvm::index_sequence<Is...>) const { |
1515 | // Apply all tuple elements to the builder in order. |
1516 | bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; |
1517 | (void)Dummy; |
1518 | } |
1519 | |
1520 | public: |
1521 | BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) |
1522 | : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { |
1523 | assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser" ) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 1523, __extension__ __PRETTY_FUNCTION__)); |
1524 | } |
1525 | |
1526 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
1527 | const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); |
1528 | emit(DB, llvm::index_sequence_for<Ts...>()); |
1529 | DB << T; |
1530 | } |
1531 | }; |
1532 | |
1533 | private: |
1534 | bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, |
1535 | TypeDiagnoser *Diagnoser); |
1536 | |
1537 | struct ModuleScope { |
1538 | clang::Module *Module = nullptr; |
1539 | bool ModuleInterface = false; |
1540 | VisibleModuleSet OuterVisibleModules; |
1541 | }; |
1542 | /// The modules we're currently parsing. |
1543 | llvm::SmallVector<ModuleScope, 16> ModuleScopes; |
1544 | |
1545 | /// Get the module whose scope we are currently within. |
1546 | Module *getCurrentModule() const { |
1547 | return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; |
1548 | } |
1549 | |
1550 | VisibleModuleSet VisibleModules; |
1551 | |
1552 | public: |
1553 | /// \brief Get the module owning an entity. |
1554 | Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); } |
1555 | |
1556 | /// \brief Make a merged definition of an existing hidden definition \p ND |
1557 | /// visible at the specified location. |
1558 | void makeMergedDefinitionVisible(NamedDecl *ND); |
1559 | |
1560 | bool isModuleVisible(const Module *M) { return VisibleModules.isVisible(M); } |
1561 | |
1562 | /// Determine whether a declaration is visible to name lookup. |
1563 | bool isVisible(const NamedDecl *D) { |
1564 | return !D->isHidden() || isVisibleSlow(D); |
1565 | } |
1566 | |
1567 | /// Determine whether any declaration of an entity is visible. |
1568 | bool |
1569 | hasVisibleDeclaration(const NamedDecl *D, |
1570 | llvm::SmallVectorImpl<Module *> *Modules = nullptr) { |
1571 | return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); |
1572 | } |
1573 | bool hasVisibleDeclarationSlow(const NamedDecl *D, |
1574 | llvm::SmallVectorImpl<Module *> *Modules); |
1575 | |
1576 | bool hasVisibleMergedDefinition(NamedDecl *Def); |
1577 | bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); |
1578 | |
1579 | /// Determine if \p D and \p Suggested have a structurally compatible |
1580 | /// layout as described in C11 6.2.7/1. |
1581 | bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); |
1582 | |
1583 | /// Determine if \p D has a visible definition. If not, suggest a declaration |
1584 | /// that should be made visible to expose the definition. |
1585 | bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, |
1586 | bool OnlyNeedComplete = false); |
1587 | bool hasVisibleDefinition(const NamedDecl *D) { |
1588 | NamedDecl *Hidden; |
1589 | return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); |
1590 | } |
1591 | |
1592 | /// Determine if the template parameter \p D has a visible default argument. |
1593 | bool |
1594 | hasVisibleDefaultArgument(const NamedDecl *D, |
1595 | llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
1596 | |
1597 | /// Determine if there is a visible declaration of \p D that is an explicit |
1598 | /// specialization declaration for a specialization of a template. (For a |
1599 | /// member specialization, use hasVisibleMemberSpecialization.) |
1600 | bool hasVisibleExplicitSpecialization( |
1601 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
1602 | |
1603 | /// Determine if there is a visible declaration of \p D that is a member |
1604 | /// specialization declaration (as opposed to an instantiated declaration). |
1605 | bool hasVisibleMemberSpecialization( |
1606 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); |
1607 | |
1608 | /// Determine if \p A and \p B are equivalent internal linkage declarations |
1609 | /// from different modules, and thus an ambiguity error can be downgraded to |
1610 | /// an extension warning. |
1611 | bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, |
1612 | const NamedDecl *B); |
1613 | void diagnoseEquivalentInternalLinkageDeclarations( |
1614 | SourceLocation Loc, const NamedDecl *D, |
1615 | ArrayRef<const NamedDecl *> Equiv); |
1616 | |
1617 | bool isCompleteType(SourceLocation Loc, QualType T) { |
1618 | return !RequireCompleteTypeImpl(Loc, T, nullptr); |
1619 | } |
1620 | bool RequireCompleteType(SourceLocation Loc, QualType T, |
1621 | TypeDiagnoser &Diagnoser); |
1622 | bool RequireCompleteType(SourceLocation Loc, QualType T, |
1623 | unsigned DiagID); |
1624 | |
1625 | template <typename... Ts> |
1626 | bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, |
1627 | const Ts &...Args) { |
1628 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
1629 | return RequireCompleteType(Loc, T, Diagnoser); |
1630 | } |
1631 | |
1632 | void completeExprArrayBound(Expr *E); |
1633 | bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); |
1634 | bool RequireCompleteExprType(Expr *E, unsigned DiagID); |
1635 | |
1636 | template <typename... Ts> |
1637 | bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { |
1638 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
1639 | return RequireCompleteExprType(E, Diagnoser); |
1640 | } |
1641 | |
1642 | bool RequireLiteralType(SourceLocation Loc, QualType T, |
1643 | TypeDiagnoser &Diagnoser); |
1644 | bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); |
1645 | |
1646 | template <typename... Ts> |
1647 | bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, |
1648 | const Ts &...Args) { |
1649 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
1650 | return RequireLiteralType(Loc, T, Diagnoser); |
1651 | } |
1652 | |
1653 | QualType getElaboratedType(ElaboratedTypeKeyword Keyword, |
1654 | const CXXScopeSpec &SS, QualType T); |
1655 | |
1656 | QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); |
1657 | /// If AsUnevaluated is false, E is treated as though it were an evaluated |
1658 | /// context, such as when building a type for decltype(auto). |
1659 | QualType BuildDecltypeType(Expr *E, SourceLocation Loc, |
1660 | bool AsUnevaluated = true); |
1661 | QualType BuildUnaryTransformType(QualType BaseType, |
1662 | UnaryTransformType::UTTKind UKind, |
1663 | SourceLocation Loc); |
1664 | |
1665 | //===--------------------------------------------------------------------===// |
1666 | // Symbol table / Decl tracking callbacks: SemaDecl.cpp. |
1667 | // |
1668 | |
1669 | struct SkipBodyInfo { |
1670 | SkipBodyInfo() |
1671 | : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), |
1672 | New(nullptr) {} |
1673 | bool ShouldSkip; |
1674 | bool CheckSameAsPrevious; |
1675 | NamedDecl *Previous; |
1676 | NamedDecl *New; |
1677 | }; |
1678 | |
1679 | DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); |
1680 | |
1681 | void DiagnoseUseOfUnimplementedSelectors(); |
1682 | |
1683 | bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; |
1684 | |
1685 | ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, |
1686 | Scope *S, CXXScopeSpec *SS = nullptr, |
1687 | bool isClassName = false, bool HasTrailingDot = false, |
1688 | ParsedType ObjectType = nullptr, |
1689 | bool IsCtorOrDtorName = false, |
1690 | bool WantNontrivialTypeSourceInfo = false, |
1691 | bool IsClassTemplateDeductionContext = true, |
1692 | IdentifierInfo **CorrectedII = nullptr); |
1693 | TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); |
1694 | bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); |
1695 | void DiagnoseUnknownTypeName(IdentifierInfo *&II, |
1696 | SourceLocation IILoc, |
1697 | Scope *S, |
1698 | CXXScopeSpec *SS, |
1699 | ParsedType &SuggestedType, |
1700 | bool IsTemplateName = false); |
1701 | |
1702 | /// Attempt to behave like MSVC in situations where lookup of an unqualified |
1703 | /// type name has failed in a dependent context. In these situations, we |
1704 | /// automatically form a DependentTypeName that will retry lookup in a related |
1705 | /// scope during instantiation. |
1706 | ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, |
1707 | SourceLocation NameLoc, |
1708 | bool IsTemplateTypeArg); |
1709 | |
1710 | /// \brief Describes the result of the name lookup and resolution performed |
1711 | /// by \c ClassifyName(). |
1712 | enum NameClassificationKind { |
1713 | NC_Unknown, |
1714 | NC_Error, |
1715 | NC_Keyword, |
1716 | NC_Type, |
1717 | NC_Expression, |
1718 | NC_NestedNameSpecifier, |
1719 | NC_TypeTemplate, |
1720 | NC_VarTemplate, |
1721 | NC_FunctionTemplate |
1722 | }; |
1723 | |
1724 | class NameClassification { |
1725 | NameClassificationKind Kind; |
1726 | ExprResult Expr; |
1727 | TemplateName Template; |
1728 | ParsedType Type; |
1729 | |
1730 | explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} |
1731 | |
1732 | public: |
1733 | NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} |
1734 | |
1735 | NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} |
1736 | |
1737 | NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} |
1738 | |
1739 | static NameClassification Error() { |
1740 | return NameClassification(NC_Error); |
1741 | } |
1742 | |
1743 | static NameClassification Unknown() { |
1744 | return NameClassification(NC_Unknown); |
1745 | } |
1746 | |
1747 | static NameClassification NestedNameSpecifier() { |
1748 | return NameClassification(NC_NestedNameSpecifier); |
1749 | } |
1750 | |
1751 | static NameClassification TypeTemplate(TemplateName Name) { |
1752 | NameClassification Result(NC_TypeTemplate); |
1753 | Result.Template = Name; |
1754 | return Result; |
1755 | } |
1756 | |
1757 | static NameClassification VarTemplate(TemplateName Name) { |
1758 | NameClassification Result(NC_VarTemplate); |
1759 | Result.Template = Name; |
1760 | return Result; |
1761 | } |
1762 | |
1763 | static NameClassification FunctionTemplate(TemplateName Name) { |
1764 | NameClassification Result(NC_FunctionTemplate); |
1765 | Result.Template = Name; |
1766 | return Result; |
1767 | } |
1768 | |
1769 | NameClassificationKind getKind() const { return Kind; } |
1770 | |
1771 | ParsedType getType() const { |
1772 | assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail ("Kind == NC_Type", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 1772, __extension__ __PRETTY_FUNCTION__)); |
1773 | return Type; |
1774 | } |
1775 | |
1776 | ExprResult getExpression() const { |
1777 | assert(Kind == NC_Expression)(static_cast <bool> (Kind == NC_Expression) ? void (0) : __assert_fail ("Kind == NC_Expression", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 1777, __extension__ __PRETTY_FUNCTION__)); |
1778 | return Expr; |
1779 | } |
1780 | |
1781 | TemplateName getTemplateName() const { |
1782 | assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 1783, __extension__ __PRETTY_FUNCTION__)) |
1783 | Kind == NC_VarTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 1783, __extension__ __PRETTY_FUNCTION__)); |
1784 | return Template; |
1785 | } |
1786 | |
1787 | TemplateNameKind getTemplateNameKind() const { |
1788 | switch (Kind) { |
1789 | case NC_TypeTemplate: |
1790 | return TNK_Type_template; |
1791 | case NC_FunctionTemplate: |
1792 | return TNK_Function_template; |
1793 | case NC_VarTemplate: |
1794 | return TNK_Var_template; |
1795 | default: |
1796 | llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification." , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 1796); |
1797 | } |
1798 | } |
1799 | }; |
1800 | |
1801 | /// \brief Perform name lookup on the given name, classifying it based on |
1802 | /// the results of name lookup and the following token. |
1803 | /// |
1804 | /// This routine is used by the parser to resolve identifiers and help direct |
1805 | /// parsing. When the identifier cannot be found, this routine will attempt |
1806 | /// to correct the typo and classify based on the resulting name. |
1807 | /// |
1808 | /// \param S The scope in which we're performing name lookup. |
1809 | /// |
1810 | /// \param SS The nested-name-specifier that precedes the name. |
1811 | /// |
1812 | /// \param Name The identifier. If typo correction finds an alternative name, |
1813 | /// this pointer parameter will be updated accordingly. |
1814 | /// |
1815 | /// \param NameLoc The location of the identifier. |
1816 | /// |
1817 | /// \param NextToken The token following the identifier. Used to help |
1818 | /// disambiguate the name. |
1819 | /// |
1820 | /// \param IsAddressOfOperand True if this name is the operand of a unary |
1821 | /// address of ('&') expression, assuming it is classified as an |
1822 | /// expression. |
1823 | /// |
1824 | /// \param CCC The correction callback, if typo correction is desired. |
1825 | NameClassification |
1826 | ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, |
1827 | SourceLocation NameLoc, const Token &NextToken, |
1828 | bool IsAddressOfOperand, |
1829 | std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr); |
1830 | |
1831 | /// Describes the detailed kind of a template name. Used in diagnostics. |
1832 | enum class TemplateNameKindForDiagnostics { |
1833 | ClassTemplate, |
1834 | FunctionTemplate, |
1835 | VarTemplate, |
1836 | AliasTemplate, |
1837 | TemplateTemplateParam, |
1838 | DependentTemplate |
1839 | }; |
1840 | TemplateNameKindForDiagnostics |
1841 | getTemplateNameKindForDiagnostics(TemplateName Name); |
1842 | |
1843 | /// Determine whether it's plausible that E was intended to be a |
1844 | /// template-name. |
1845 | bool mightBeIntendedToBeTemplateName(ExprResult E) { |
1846 | if (!getLangOpts().CPlusPlus || E.isInvalid()) |
1847 | return false; |
1848 | if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) |
1849 | return !DRE->hasExplicitTemplateArgs(); |
1850 | if (auto *ME = dyn_cast<MemberExpr>(E.get())) |
1851 | return !ME->hasExplicitTemplateArgs(); |
1852 | // Any additional cases recognized here should also be handled by |
1853 | // diagnoseExprIntendedAsTemplateName. |
1854 | return false; |
1855 | } |
1856 | void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, |
1857 | SourceLocation Less, |
1858 | SourceLocation Greater); |
1859 | |
1860 | Decl *ActOnDeclarator(Scope *S, Declarator &D); |
1861 | |
1862 | NamedDecl *HandleDeclarator(Scope *S, Declarator &D, |
1863 | MultiTemplateParamsArg TemplateParameterLists); |
1864 | void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); |
1865 | bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); |
1866 | bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, |
1867 | DeclarationName Name, |
1868 | SourceLocation Loc); |
1869 | void |
1870 | diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, |
1871 | SourceLocation FallbackLoc, |
1872 | SourceLocation ConstQualLoc = SourceLocation(), |
1873 | SourceLocation VolatileQualLoc = SourceLocation(), |
1874 | SourceLocation RestrictQualLoc = SourceLocation(), |
1875 | SourceLocation AtomicQualLoc = SourceLocation(), |
1876 | SourceLocation UnalignedQualLoc = SourceLocation()); |
1877 | |
1878 | static bool adjustContextForLocalExternDecl(DeclContext *&DC); |
1879 | void DiagnoseFunctionSpecifiers(const DeclSpec &DS); |
1880 | NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, |
1881 | const LookupResult &R); |
1882 | NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); |
1883 | void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, |
1884 | const LookupResult &R); |
1885 | void CheckShadow(Scope *S, VarDecl *D); |
1886 | |
1887 | /// Warn if 'E', which is an expression that is about to be modified, refers |
1888 | /// to a shadowing declaration. |
1889 | void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); |
1890 | |
1891 | void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); |
1892 | |
1893 | private: |
1894 | /// Map of current shadowing declarations to shadowed declarations. Warn if |
1895 | /// it looks like the user is trying to modify the shadowing declaration. |
1896 | llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; |
1897 | |
1898 | public: |
1899 | void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); |
1900 | void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); |
1901 | void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, |
1902 | TypedefNameDecl *NewTD); |
1903 | void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); |
1904 | NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, |
1905 | TypeSourceInfo *TInfo, |
1906 | LookupResult &Previous); |
1907 | NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, |
1908 | LookupResult &Previous, bool &Redeclaration); |
1909 | NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, |
1910 | TypeSourceInfo *TInfo, |
1911 | LookupResult &Previous, |
1912 | MultiTemplateParamsArg TemplateParamLists, |
1913 | bool &AddToScope, |
1914 | ArrayRef<BindingDecl *> Bindings = None); |
1915 | NamedDecl * |
1916 | ActOnDecompositionDeclarator(Scope *S, Declarator &D, |
1917 | MultiTemplateParamsArg TemplateParamLists); |
1918 | // Returns true if the variable declaration is a redeclaration |
1919 | bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); |
1920 | void CheckVariableDeclarationType(VarDecl *NewVD); |
1921 | bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, |
1922 | Expr *Init); |
1923 | void CheckCompleteVariableDeclaration(VarDecl *VD); |
1924 | void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); |
1925 | void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); |
1926 | |
1927 | NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, |
1928 | TypeSourceInfo *TInfo, |
1929 | LookupResult &Previous, |
1930 | MultiTemplateParamsArg TemplateParamLists, |
1931 | bool &AddToScope); |
1932 | bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); |
1933 | |
1934 | bool CheckConstexprFunctionDecl(const FunctionDecl *FD); |
1935 | bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); |
1936 | |
1937 | void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); |
1938 | void FindHiddenVirtualMethods(CXXMethodDecl *MD, |
1939 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); |
1940 | void NoteHiddenVirtualMethods(CXXMethodDecl *MD, |
1941 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); |
1942 | // Returns true if the function declaration is a redeclaration |
1943 | bool CheckFunctionDeclaration(Scope *S, |
1944 | FunctionDecl *NewFD, LookupResult &Previous, |
1945 | bool IsMemberSpecialization); |
1946 | bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); |
1947 | void CheckMain(FunctionDecl *FD, const DeclSpec &D); |
1948 | void CheckMSVCRTEntryPoint(FunctionDecl *FD); |
1949 | Decl *ActOnParamDeclarator(Scope *S, Declarator &D); |
1950 | ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, |
1951 | SourceLocation Loc, |
1952 | QualType T); |
1953 | ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, |
1954 | SourceLocation NameLoc, IdentifierInfo *Name, |
1955 | QualType T, TypeSourceInfo *TSInfo, |
1956 | StorageClass SC); |
1957 | void ActOnParamDefaultArgument(Decl *param, |
1958 | SourceLocation EqualLoc, |
1959 | Expr *defarg); |
1960 | void ActOnParamUnparsedDefaultArgument(Decl *param, |
1961 | SourceLocation EqualLoc, |
1962 | SourceLocation ArgLoc); |
1963 | void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); |
1964 | bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, |
1965 | SourceLocation EqualLoc); |
1966 | |
1967 | void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); |
1968 | void ActOnUninitializedDecl(Decl *dcl); |
1969 | void ActOnInitializerError(Decl *Dcl); |
1970 | |
1971 | void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); |
1972 | void ActOnCXXForRangeDecl(Decl *D); |
1973 | StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, |
1974 | IdentifierInfo *Ident, |
1975 | ParsedAttributes &Attrs, |
1976 | SourceLocation AttrEnd); |
1977 | void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); |
1978 | void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); |
1979 | void FinalizeDeclaration(Decl *D); |
1980 | DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, |
1981 | ArrayRef<Decl *> Group); |
1982 | DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); |
1983 | |
1984 | /// Should be called on all declarations that might have attached |
1985 | /// documentation comments. |
1986 | void ActOnDocumentableDecl(Decl *D); |
1987 | void ActOnDocumentableDecls(ArrayRef<Decl *> Group); |
1988 | |
1989 | void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, |
1990 | SourceLocation LocAfterDecls); |
1991 | void CheckForFunctionRedefinition( |
1992 | FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, |
1993 | SkipBodyInfo *SkipBody = nullptr); |
1994 | Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, |
1995 | MultiTemplateParamsArg TemplateParamLists, |
1996 | SkipBodyInfo *SkipBody = nullptr); |
1997 | Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, |
1998 | SkipBodyInfo *SkipBody = nullptr); |
1999 | void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); |
2000 | bool isObjCMethodDecl(Decl *D) { |
2001 | return D && isa<ObjCMethodDecl>(D); |
2002 | } |
2003 | |
2004 | /// \brief Determine whether we can delay parsing the body of a function or |
2005 | /// function template until it is used, assuming we don't care about emitting |
2006 | /// code for that function. |
2007 | /// |
2008 | /// This will be \c false if we may need the body of the function in the |
2009 | /// middle of parsing an expression (where it's impractical to switch to |
2010 | /// parsing a different function), for instance, if it's constexpr in C++11 |
2011 | /// or has an 'auto' return type in C++14. These cases are essentially bugs. |
2012 | bool canDelayFunctionBody(const Declarator &D); |
2013 | |
2014 | /// \brief Determine whether we can skip parsing the body of a function |
2015 | /// definition, assuming we don't care about analyzing its body or emitting |
2016 | /// code for that function. |
2017 | /// |
2018 | /// This will be \c false only if we may need the body of the function in |
2019 | /// order to parse the rest of the program (for instance, if it is |
2020 | /// \c constexpr in C++11 or has an 'auto' return type in C++14). |
2021 | bool canSkipFunctionBody(Decl *D); |
2022 | |
2023 | void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); |
2024 | Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); |
2025 | Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); |
2026 | Decl *ActOnSkippedFunctionBody(Decl *Decl); |
2027 | void ActOnFinishInlineFunctionDef(FunctionDecl *D); |
2028 | |
2029 | /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an |
2030 | /// attribute for which parsing is delayed. |
2031 | void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); |
2032 | |
2033 | /// \brief Diagnose any unused parameters in the given sequence of |
2034 | /// ParmVarDecl pointers. |
2035 | void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); |
2036 | |
2037 | /// \brief Diagnose whether the size of parameters or return value of a |
2038 | /// function or obj-c method definition is pass-by-value and larger than a |
2039 | /// specified threshold. |
2040 | void |
2041 | DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, |
2042 | QualType ReturnTy, NamedDecl *D); |
2043 | |
2044 | void DiagnoseInvalidJumps(Stmt *Body); |
2045 | Decl *ActOnFileScopeAsmDecl(Expr *expr, |
2046 | SourceLocation AsmLoc, |
2047 | SourceLocation RParenLoc); |
2048 | |
2049 | /// \brief Handle a C++11 empty-declaration and attribute-declaration. |
2050 | Decl *ActOnEmptyDeclaration(Scope *S, |
2051 | AttributeList *AttrList, |
2052 | SourceLocation SemiLoc); |
2053 | |
2054 | enum class ModuleDeclKind { |
2055 | Interface, ///< 'export module X;' |
2056 | Implementation, ///< 'module X;' |
2057 | Partition, ///< 'module partition X;' |
2058 | }; |
2059 | |
2060 | /// The parser has processed a module-declaration that begins the definition |
2061 | /// of a module interface or implementation. |
2062 | DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, |
2063 | SourceLocation ModuleLoc, ModuleDeclKind MDK, |
2064 | ModuleIdPath Path); |
2065 | |
2066 | /// \brief The parser has processed a module import declaration. |
2067 | /// |
2068 | /// \param AtLoc The location of the '@' symbol, if any. |
2069 | /// |
2070 | /// \param ImportLoc The location of the 'import' keyword. |
2071 | /// |
2072 | /// \param Path The module access path. |
2073 | DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, |
2074 | ModuleIdPath Path); |
2075 | |
2076 | /// \brief The parser has processed a module import translated from a |
2077 | /// #include or similar preprocessing directive. |
2078 | void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); |
2079 | void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); |
2080 | |
2081 | /// \brief The parsed has entered a submodule. |
2082 | void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); |
2083 | /// \brief The parser has left a submodule. |
2084 | void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); |
2085 | |
2086 | /// \brief Create an implicit import of the given module at the given |
2087 | /// source location, for error recovery, if possible. |
2088 | /// |
2089 | /// This routine is typically used when an entity found by name lookup |
2090 | /// is actually hidden within a module that we know about but the user |
2091 | /// has forgotten to import. |
2092 | void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, |
2093 | Module *Mod); |
2094 | |
2095 | /// Kinds of missing import. Note, the values of these enumerators correspond |
2096 | /// to %select values in diagnostics. |
2097 | enum class MissingImportKind { |
2098 | Declaration, |
2099 | Definition, |
2100 | DefaultArgument, |
2101 | ExplicitSpecialization, |
2102 | PartialSpecialization |
2103 | }; |
2104 | |
2105 | /// \brief Diagnose that the specified declaration needs to be visible but |
2106 | /// isn't, and suggest a module import that would resolve the problem. |
2107 | void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, |
2108 | MissingImportKind MIK, bool Recover = true); |
2109 | void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, |
2110 | SourceLocation DeclLoc, ArrayRef<Module *> Modules, |
2111 | MissingImportKind MIK, bool Recover); |
2112 | |
2113 | Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, |
2114 | SourceLocation LBraceLoc); |
2115 | Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, |
2116 | SourceLocation RBraceLoc); |
2117 | |
2118 | /// \brief We've found a use of a templated declaration that would trigger an |
2119 | /// implicit instantiation. Check that any relevant explicit specializations |
2120 | /// and partial specializations are visible, and diagnose if not. |
2121 | void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); |
2122 | |
2123 | /// \brief We've found a use of a template specialization that would select a |
2124 | /// partial specialization. Check that the partial specialization is visible, |
2125 | /// and diagnose if not. |
2126 | void checkPartialSpecializationVisibility(SourceLocation Loc, |
2127 | NamedDecl *Spec); |
2128 | |
2129 | /// \brief Retrieve a suitable printing policy. |
2130 | PrintingPolicy getPrintingPolicy() const { |
2131 | return getPrintingPolicy(Context, PP); |
2132 | } |
2133 | |
2134 | /// \brief Retrieve a suitable printing policy. |
2135 | static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, |
2136 | const Preprocessor &PP); |
2137 | |
2138 | /// Scope actions. |
2139 | void ActOnPopScope(SourceLocation Loc, Scope *S); |
2140 | void ActOnTranslationUnitScope(Scope *S); |
2141 | |
2142 | Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
2143 | RecordDecl *&AnonRecord); |
2144 | Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
2145 | MultiTemplateParamsArg TemplateParams, |
2146 | bool IsExplicitInstantiation, |
2147 | RecordDecl *&AnonRecord); |
2148 | |
2149 | Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, |
2150 | AccessSpecifier AS, |
2151 | RecordDecl *Record, |
2152 | const PrintingPolicy &Policy); |
2153 | |
2154 | Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, |
2155 | RecordDecl *Record); |
2156 | |
2157 | /// Common ways to introduce type names without a tag for use in diagnostics. |
2158 | /// Keep in sync with err_tag_reference_non_tag. |
2159 | enum NonTagKind { |
2160 | NTK_NonStruct, |
2161 | NTK_NonClass, |
2162 | NTK_NonUnion, |
2163 | NTK_NonEnum, |
2164 | NTK_Typedef, |
2165 | NTK_TypeAlias, |
2166 | NTK_Template, |
2167 | NTK_TypeAliasTemplate, |
2168 | NTK_TemplateTemplateArgument, |
2169 | }; |
2170 | |
2171 | /// Given a non-tag type declaration, returns an enum useful for indicating |
2172 | /// what kind of non-tag type this is. |
2173 | NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); |
2174 | |
2175 | bool isAcceptableTagRedeclaration(const TagDecl *Previous, |
2176 | TagTypeKind NewTag, bool isDefinition, |
2177 | SourceLocation NewTagLoc, |
2178 | const IdentifierInfo *Name); |
2179 | |
2180 | enum TagUseKind { |
2181 | TUK_Reference, // Reference to a tag: 'struct foo *X;' |
2182 | TUK_Declaration, // Fwd decl of a tag: 'struct foo;' |
2183 | TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' |
2184 | TUK_Friend // Friend declaration: 'friend struct foo;' |
2185 | }; |
2186 | |
2187 | Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, |
2188 | SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, |
2189 | SourceLocation NameLoc, AttributeList *Attr, |
2190 | AccessSpecifier AS, SourceLocation ModulePrivateLoc, |
2191 | MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, |
2192 | bool &IsDependent, SourceLocation ScopedEnumKWLoc, |
2193 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, |
2194 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, |
2195 | SkipBodyInfo *SkipBody = nullptr); |
2196 | |
2197 | Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, |
2198 | unsigned TagSpec, SourceLocation TagLoc, |
2199 | CXXScopeSpec &SS, |
2200 | IdentifierInfo *Name, SourceLocation NameLoc, |
2201 | AttributeList *Attr, |
2202 | MultiTemplateParamsArg TempParamLists); |
2203 | |
2204 | TypeResult ActOnDependentTag(Scope *S, |
2205 | unsigned TagSpec, |
2206 | TagUseKind TUK, |
2207 | const CXXScopeSpec &SS, |
2208 | IdentifierInfo *Name, |
2209 | SourceLocation TagLoc, |
2210 | SourceLocation NameLoc); |
2211 | |
2212 | void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, |
2213 | IdentifierInfo *ClassName, |
2214 | SmallVectorImpl<Decl *> &Decls); |
2215 | Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, |
2216 | Declarator &D, Expr *BitfieldWidth); |
2217 | |
2218 | FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, |
2219 | Declarator &D, Expr *BitfieldWidth, |
2220 | InClassInitStyle InitStyle, |
2221 | AccessSpecifier AS); |
2222 | MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, |
2223 | SourceLocation DeclStart, |
2224 | Declarator &D, Expr *BitfieldWidth, |
2225 | InClassInitStyle InitStyle, |
2226 | AccessSpecifier AS, |
2227 | AttributeList *MSPropertyAttr); |
2228 | |
2229 | FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, |
2230 | TypeSourceInfo *TInfo, |
2231 | RecordDecl *Record, SourceLocation Loc, |
2232 | bool Mutable, Expr *BitfieldWidth, |
2233 | InClassInitStyle InitStyle, |
2234 | SourceLocation TSSL, |
2235 | AccessSpecifier AS, NamedDecl *PrevDecl, |
2236 | Declarator *D = nullptr); |
2237 | |
2238 | bool CheckNontrivialField(FieldDecl *FD); |
2239 | void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); |
2240 | |
2241 | enum TrivialABIHandling { |
2242 | /// The triviality of a method unaffected by "trivial_abi". |
2243 | TAH_IgnoreTrivialABI, |
2244 | |
2245 | /// The triviality of a method affected by "trivial_abi". |
2246 | TAH_ConsiderTrivialABI |
2247 | }; |
2248 | |
2249 | bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, |
2250 | TrivialABIHandling TAH = TAH_IgnoreTrivialABI, |
2251 | bool Diagnose = false); |
2252 | CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); |
2253 | void ActOnLastBitfield(SourceLocation DeclStart, |
2254 | SmallVectorImpl<Decl *> &AllIvarDecls); |
2255 | Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, |
2256 | Declarator &D, Expr *BitfieldWidth, |
2257 | tok::ObjCKeywordKind visibility); |
2258 | |
2259 | // This is used for both record definitions and ObjC interface declarations. |
2260 | void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl, |
2261 | ArrayRef<Decl *> Fields, |
2262 | SourceLocation LBrac, SourceLocation RBrac, |
2263 | AttributeList *AttrList); |
2264 | |
2265 | /// ActOnTagStartDefinition - Invoked when we have entered the |
2266 | /// scope of a tag's definition (e.g., for an enumeration, class, |
2267 | /// struct, or union). |
2268 | void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); |
2269 | |
2270 | /// Perform ODR-like check for C/ObjC when merging tag types from modules. |
2271 | /// Differently from C++, actually parse the body and reject / error out |
2272 | /// in case of a structural mismatch. |
2273 | bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, |
2274 | SkipBodyInfo &SkipBody); |
2275 | |
2276 | typedef void *SkippedDefinitionContext; |
2277 | |
2278 | /// \brief Invoked when we enter a tag definition that we're skipping. |
2279 | SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); |
2280 | |
2281 | Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); |
2282 | |
2283 | /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a |
2284 | /// C++ record definition's base-specifiers clause and are starting its |
2285 | /// member declarations. |
2286 | void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, |
2287 | SourceLocation FinalLoc, |
2288 | bool IsFinalSpelledSealed, |
2289 | SourceLocation LBraceLoc); |
2290 | |
2291 | /// ActOnTagFinishDefinition - Invoked once we have finished parsing |
2292 | /// the definition of a tag (enumeration, class, struct, or union). |
2293 | void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, |
2294 | SourceRange BraceRange); |
2295 | |
2296 | void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); |
2297 | |
2298 | void ActOnObjCContainerFinishDefinition(); |
2299 | |
2300 | /// \brief Invoked when we must temporarily exit the objective-c container |
2301 | /// scope for parsing/looking-up C constructs. |
2302 | /// |
2303 | /// Must be followed by a call to \see ActOnObjCReenterContainerContext |
2304 | void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); |
2305 | void ActOnObjCReenterContainerContext(DeclContext *DC); |
2306 | |
2307 | /// ActOnTagDefinitionError - Invoked when there was an unrecoverable |
2308 | /// error parsing the definition of a tag. |
2309 | void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); |
2310 | |
2311 | EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, |
2312 | EnumConstantDecl *LastEnumConst, |
2313 | SourceLocation IdLoc, |
2314 | IdentifierInfo *Id, |
2315 | Expr *val); |
2316 | bool CheckEnumUnderlyingType(TypeSourceInfo *TI); |
2317 | bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, |
2318 | QualType EnumUnderlyingTy, bool IsFixed, |
2319 | const EnumDecl *Prev); |
2320 | |
2321 | /// Determine whether the body of an anonymous enumeration should be skipped. |
2322 | /// \param II The name of the first enumerator. |
2323 | SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, |
2324 | SourceLocation IILoc); |
2325 | |
2326 | Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, |
2327 | SourceLocation IdLoc, IdentifierInfo *Id, |
2328 | AttributeList *Attrs, SourceLocation EqualLoc, |
2329 | Expr *Val); |
2330 | void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, |
2331 | Decl *EnumDecl, |
2332 | ArrayRef<Decl *> Elements, |
2333 | Scope *S, AttributeList *Attr); |
2334 | |
2335 | DeclContext *getContainingDC(DeclContext *DC); |
2336 | |
2337 | /// Set the current declaration context until it gets popped. |
2338 | void PushDeclContext(Scope *S, DeclContext *DC); |
2339 | void PopDeclContext(); |
2340 | |
2341 | /// EnterDeclaratorContext - Used when we must lookup names in the context |
2342 | /// of a declarator's nested name specifier. |
2343 | void EnterDeclaratorContext(Scope *S, DeclContext *DC); |
2344 | void ExitDeclaratorContext(Scope *S); |
2345 | |
2346 | /// Push the parameters of D, which must be a function, into scope. |
2347 | void ActOnReenterFunctionContext(Scope* S, Decl* D); |
2348 | void ActOnExitFunctionContext(); |
2349 | |
2350 | DeclContext *getFunctionLevelDeclContext(); |
2351 | |
2352 | /// getCurFunctionDecl - If inside of a function body, this returns a pointer |
2353 | /// to the function decl for the function being parsed. If we're currently |
2354 | /// in a 'block', this returns the containing context. |
2355 | FunctionDecl *getCurFunctionDecl(); |
2356 | |
2357 | /// getCurMethodDecl - If inside of a method body, this returns a pointer to |
2358 | /// the method decl for the method being parsed. If we're currently |
2359 | /// in a 'block', this returns the containing context. |
2360 | ObjCMethodDecl *getCurMethodDecl(); |
2361 | |
2362 | /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method |
2363 | /// or C function we're in, otherwise return null. If we're currently |
2364 | /// in a 'block', this returns the containing context. |
2365 | NamedDecl *getCurFunctionOrMethodDecl(); |
2366 | |
2367 | /// Add this decl to the scope shadowed decl chains. |
2368 | void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); |
2369 | |
2370 | /// \brief Make the given externally-produced declaration visible at the |
2371 | /// top level scope. |
2372 | /// |
2373 | /// \param D The externally-produced declaration to push. |
2374 | /// |
2375 | /// \param Name The name of the externally-produced declaration. |
2376 | void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name); |
2377 | |
2378 | /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true |
2379 | /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns |
2380 | /// true if 'D' belongs to the given declaration context. |
2381 | /// |
2382 | /// \param AllowInlineNamespace If \c true, allow the declaration to be in the |
2383 | /// enclosing namespace set of the context, rather than contained |
2384 | /// directly within it. |
2385 | bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, |
2386 | bool AllowInlineNamespace = false); |
2387 | |
2388 | /// Finds the scope corresponding to the given decl context, if it |
2389 | /// happens to be an enclosing scope. Otherwise return NULL. |
2390 | static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); |
2391 | |
2392 | /// Subroutines of ActOnDeclarator(). |
2393 | TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, |
2394 | TypeSourceInfo *TInfo); |
2395 | bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); |
2396 | |
2397 | /// \brief Describes the kind of merge to perform for availability |
2398 | /// attributes (including "deprecated", "unavailable", and "availability"). |
2399 | enum AvailabilityMergeKind { |
2400 | /// \brief Don't merge availability attributes at all. |
2401 | AMK_None, |
2402 | /// \brief Merge availability attributes for a redeclaration, which requires |
2403 | /// an exact match. |
2404 | AMK_Redeclaration, |
2405 | /// \brief Merge availability attributes for an override, which requires |
2406 | /// an exact match or a weakening of constraints. |
2407 | AMK_Override, |
2408 | /// \brief Merge availability attributes for an implementation of |
2409 | /// a protocol requirement. |
2410 | AMK_ProtocolImplementation, |
2411 | }; |
2412 | |
2413 | /// Attribute merging methods. Return true if a new attribute was added. |
2414 | AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, |
2415 | IdentifierInfo *Platform, |
2416 | bool Implicit, |
2417 | VersionTuple Introduced, |
2418 | VersionTuple Deprecated, |
2419 | VersionTuple Obsoleted, |
2420 | bool IsUnavailable, |
2421 | StringRef Message, |
2422 | bool IsStrict, StringRef Replacement, |
2423 | AvailabilityMergeKind AMK, |
2424 | unsigned AttrSpellingListIndex); |
2425 | TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, |
2426 | TypeVisibilityAttr::VisibilityType Vis, |
2427 | unsigned AttrSpellingListIndex); |
2428 | VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, |
2429 | VisibilityAttr::VisibilityType Vis, |
2430 | unsigned AttrSpellingListIndex); |
2431 | UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range, |
2432 | unsigned AttrSpellingListIndex, StringRef Uuid); |
2433 | DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range, |
2434 | unsigned AttrSpellingListIndex); |
2435 | DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range, |
2436 | unsigned AttrSpellingListIndex); |
2437 | MSInheritanceAttr * |
2438 | mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, |
2439 | unsigned AttrSpellingListIndex, |
2440 | MSInheritanceAttr::Spelling SemanticSpelling); |
2441 | FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, |
2442 | IdentifierInfo *Format, int FormatIdx, |
2443 | int FirstArg, unsigned AttrSpellingListIndex); |
2444 | SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, |
2445 | unsigned AttrSpellingListIndex); |
2446 | AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range, |
2447 | IdentifierInfo *Ident, |
2448 | unsigned AttrSpellingListIndex); |
2449 | MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range, |
2450 | unsigned AttrSpellingListIndex); |
2451 | OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range, |
2452 | unsigned AttrSpellingListIndex); |
2453 | InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range, |
2454 | IdentifierInfo *Ident, |
2455 | unsigned AttrSpellingListIndex); |
2456 | CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, |
2457 | unsigned AttrSpellingListIndex); |
2458 | |
2459 | void mergeDeclAttributes(NamedDecl *New, Decl *Old, |
2460 | AvailabilityMergeKind AMK = AMK_Redeclaration); |
2461 | void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, |
2462 | LookupResult &OldDecls); |
2463 | bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, |
2464 | bool MergeTypeWithOld); |
2465 | bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, |
2466 | Scope *S, bool MergeTypeWithOld); |
2467 | void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); |
2468 | void MergeVarDecl(VarDecl *New, LookupResult &Previous); |
2469 | void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); |
2470 | void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); |
2471 | bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); |
2472 | void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); |
2473 | bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); |
2474 | |
2475 | // AssignmentAction - This is used by all the assignment diagnostic functions |
2476 | // to represent what is actually causing the operation |
2477 | enum AssignmentAction { |
2478 | AA_Assigning, |
2479 | AA_Passing, |
2480 | AA_Returning, |
2481 | AA_Converting, |
2482 | AA_Initializing, |
2483 | AA_Sending, |
2484 | AA_Casting, |
2485 | AA_Passing_CFAudited |
2486 | }; |
2487 | |
2488 | /// C++ Overloading. |
2489 | enum OverloadKind { |
2490 | /// This is a legitimate overload: the existing declarations are |
2491 | /// functions or function templates with different signatures. |
2492 | Ovl_Overload, |
2493 | |
2494 | /// This is not an overload because the signature exactly matches |
2495 | /// an existing declaration. |
2496 | Ovl_Match, |
2497 | |
2498 | /// This is not an overload because the lookup results contain a |
2499 | /// non-function. |
2500 | Ovl_NonFunction |
2501 | }; |
2502 | OverloadKind CheckOverload(Scope *S, |
2503 | FunctionDecl *New, |
2504 | const LookupResult &OldDecls, |
2505 | NamedDecl *&OldDecl, |
2506 | bool IsForUsingDecl); |
2507 | bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, |
2508 | bool ConsiderCudaAttrs = true); |
2509 | |
2510 | /// \brief Checks availability of the function depending on the current |
2511 | /// function context.Inside an unavailable function,unavailability is ignored. |
2512 | /// |
2513 | /// \returns true if \p FD is unavailable and current context is inside |
2514 | /// an available function, false otherwise. |
2515 | bool isFunctionConsideredUnavailable(FunctionDecl *FD); |
2516 | |
2517 | ImplicitConversionSequence |
2518 | TryImplicitConversion(Expr *From, QualType ToType, |
2519 | bool SuppressUserConversions, |
2520 | bool AllowExplicit, |
2521 | bool InOverloadResolution, |
2522 | bool CStyle, |
2523 | bool AllowObjCWritebackConversion); |
2524 | |
2525 | bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); |
2526 | bool IsFloatingPointPromotion(QualType FromType, QualType ToType); |
2527 | bool IsComplexPromotion(QualType FromType, QualType ToType); |
2528 | bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, |
2529 | bool InOverloadResolution, |
2530 | QualType& ConvertedType, bool &IncompatibleObjC); |
2531 | bool isObjCPointerConversion(QualType FromType, QualType ToType, |
2532 | QualType& ConvertedType, bool &IncompatibleObjC); |
2533 | bool isObjCWritebackConversion(QualType FromType, QualType ToType, |
2534 | QualType &ConvertedType); |
2535 | bool IsBlockPointerConversion(QualType FromType, QualType ToType, |
2536 | QualType& ConvertedType); |
2537 | bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, |
2538 | const FunctionProtoType *NewType, |
2539 | unsigned *ArgPos = nullptr); |
2540 | void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, |
2541 | QualType FromType, QualType ToType); |
2542 | |
2543 | void maybeExtendBlockObject(ExprResult &E); |
2544 | CastKind PrepareCastToObjCObjectPointer(ExprResult &E); |
2545 | bool CheckPointerConversion(Expr *From, QualType ToType, |
2546 | CastKind &Kind, |
2547 | CXXCastPath& BasePath, |
2548 | bool IgnoreBaseAccess, |
2549 | bool Diagnose = true); |
2550 | bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, |
2551 | bool InOverloadResolution, |
2552 | QualType &ConvertedType); |
2553 | bool CheckMemberPointerConversion(Expr *From, QualType ToType, |
2554 | CastKind &Kind, |
2555 | CXXCastPath &BasePath, |
2556 | bool IgnoreBaseAccess); |
2557 | bool IsQualificationConversion(QualType FromType, QualType ToType, |
2558 | bool CStyle, bool &ObjCLifetimeConversion); |
2559 | bool IsFunctionConversion(QualType FromType, QualType ToType, |
2560 | QualType &ResultTy); |
2561 | bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); |
2562 | bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); |
2563 | |
2564 | ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, |
2565 | const VarDecl *NRVOCandidate, |
2566 | QualType ResultType, |
2567 | Expr *Value, |
2568 | bool AllowNRVO = true); |
2569 | |
2570 | bool CanPerformCopyInitialization(const InitializedEntity &Entity, |
2571 | ExprResult Init); |
2572 | ExprResult PerformCopyInitialization(const InitializedEntity &Entity, |
2573 | SourceLocation EqualLoc, |
2574 | ExprResult Init, |
2575 | bool TopLevelOfInitList = false, |
2576 | bool AllowExplicit = false); |
2577 | ExprResult PerformObjectArgumentInitialization(Expr *From, |
2578 | NestedNameSpecifier *Qualifier, |
2579 | NamedDecl *FoundDecl, |
2580 | CXXMethodDecl *Method); |
2581 | |
2582 | ExprResult PerformContextuallyConvertToBool(Expr *From); |
2583 | ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); |
2584 | |
2585 | /// Contexts in which a converted constant expression is required. |
2586 | enum CCEKind { |
2587 | CCEK_CaseValue, ///< Expression in a case label. |
2588 | CCEK_Enumerator, ///< Enumerator value with fixed underlying type. |
2589 | CCEK_TemplateArg, ///< Value of a non-type template parameter. |
2590 | CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. |
2591 | CCEK_ConstexprIf ///< Condition in a constexpr if statement. |
2592 | }; |
2593 | ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, |
2594 | llvm::APSInt &Value, CCEKind CCE); |
2595 | ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, |
2596 | APValue &Value, CCEKind CCE); |
2597 | |
2598 | /// \brief Abstract base class used to perform a contextual implicit |
2599 | /// conversion from an expression to any type passing a filter. |
2600 | class ContextualImplicitConverter { |
2601 | public: |
2602 | bool Suppress; |
2603 | bool SuppressConversion; |
2604 | |
2605 | ContextualImplicitConverter(bool Suppress = false, |
2606 | bool SuppressConversion = false) |
2607 | : Suppress(Suppress), SuppressConversion(SuppressConversion) {} |
2608 | |
2609 | /// \brief Determine whether the specified type is a valid destination type |
2610 | /// for this conversion. |
2611 | virtual bool match(QualType T) = 0; |
2612 | |
2613 | /// \brief Emits a diagnostic complaining that the expression does not have |
2614 | /// integral or enumeration type. |
2615 | virtual SemaDiagnosticBuilder |
2616 | diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; |
2617 | |
2618 | /// \brief Emits a diagnostic when the expression has incomplete class type. |
2619 | virtual SemaDiagnosticBuilder |
2620 | diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; |
2621 | |
2622 | /// \brief Emits a diagnostic when the only matching conversion function |
2623 | /// is explicit. |
2624 | virtual SemaDiagnosticBuilder diagnoseExplicitConv( |
2625 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; |
2626 | |
2627 | /// \brief Emits a note for the explicit conversion function. |
2628 | virtual SemaDiagnosticBuilder |
2629 | noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; |
2630 | |
2631 | /// \brief Emits a diagnostic when there are multiple possible conversion |
2632 | /// functions. |
2633 | virtual SemaDiagnosticBuilder |
2634 | diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; |
2635 | |
2636 | /// \brief Emits a note for one of the candidate conversions. |
2637 | virtual SemaDiagnosticBuilder |
2638 | noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; |
2639 | |
2640 | /// \brief Emits a diagnostic when we picked a conversion function |
2641 | /// (for cases when we are not allowed to pick a conversion function). |
2642 | virtual SemaDiagnosticBuilder diagnoseConversion( |
2643 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; |
2644 | |
2645 | virtual ~ContextualImplicitConverter() {} |
2646 | }; |
2647 | |
2648 | class ICEConvertDiagnoser : public ContextualImplicitConverter { |
2649 | bool AllowScopedEnumerations; |
2650 | |
2651 | public: |
2652 | ICEConvertDiagnoser(bool AllowScopedEnumerations, |
2653 | bool Suppress, bool SuppressConversion) |
2654 | : ContextualImplicitConverter(Suppress, SuppressConversion), |
2655 | AllowScopedEnumerations(AllowScopedEnumerations) {} |
2656 | |
2657 | /// Match an integral or (possibly scoped) enumeration type. |
2658 | bool match(QualType T) override; |
2659 | |
2660 | SemaDiagnosticBuilder |
2661 | diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { |
2662 | return diagnoseNotInt(S, Loc, T); |
2663 | } |
2664 | |
2665 | /// \brief Emits a diagnostic complaining that the expression does not have |
2666 | /// integral or enumeration type. |
2667 | virtual SemaDiagnosticBuilder |
2668 | diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; |
2669 | }; |
2670 | |
2671 | /// Perform a contextual implicit conversion. |
2672 | ExprResult PerformContextualImplicitConversion( |
2673 | SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); |
2674 | |
2675 | |
2676 | enum ObjCSubscriptKind { |
2677 | OS_Array, |
2678 | OS_Dictionary, |
2679 | OS_Error |
2680 | }; |
2681 | ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); |
2682 | |
2683 | // Note that LK_String is intentionally after the other literals, as |
2684 | // this is used for diagnostics logic. |
2685 | enum ObjCLiteralKind { |
2686 | LK_Array, |
2687 | LK_Dictionary, |
2688 | LK_Numeric, |
2689 | LK_Boxed, |
2690 | LK_String, |
2691 | LK_Block, |
2692 | LK_None |
2693 | }; |
2694 | ObjCLiteralKind CheckLiteralKind(Expr *FromE); |
2695 | |
2696 | ExprResult PerformObjectMemberConversion(Expr *From, |
2697 | NestedNameSpecifier *Qualifier, |
2698 | NamedDecl *FoundDecl, |
2699 | NamedDecl *Member); |
2700 | |
2701 | // Members have to be NamespaceDecl* or TranslationUnitDecl*. |
2702 | // TODO: make this is a typesafe union. |
2703 | typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; |
2704 | typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; |
2705 | |
2706 | void AddOverloadCandidate(FunctionDecl *Function, |
2707 | DeclAccessPair FoundDecl, |
2708 | ArrayRef<Expr *> Args, |
2709 | OverloadCandidateSet &CandidateSet, |
2710 | bool SuppressUserConversions = false, |
2711 | bool PartialOverloading = false, |
2712 | bool AllowExplicit = false, |
2713 | ConversionSequenceList EarlyConversions = None); |
2714 | void AddFunctionCandidates(const UnresolvedSetImpl &Functions, |
2715 | ArrayRef<Expr *> Args, |
2716 | OverloadCandidateSet &CandidateSet, |
2717 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, |
2718 | bool SuppressUserConversions = false, |
2719 | bool PartialOverloading = false, |
2720 | bool FirstArgumentIsBase = false); |
2721 | void AddMethodCandidate(DeclAccessPair FoundDecl, |
2722 | QualType ObjectType, |
2723 | Expr::Classification ObjectClassification, |
2724 | ArrayRef<Expr *> Args, |
2725 | OverloadCandidateSet& CandidateSet, |
2726 | bool SuppressUserConversion = false); |
2727 | void AddMethodCandidate(CXXMethodDecl *Method, |
2728 | DeclAccessPair FoundDecl, |
2729 | CXXRecordDecl *ActingContext, QualType ObjectType, |
2730 | Expr::Classification ObjectClassification, |
2731 | ArrayRef<Expr *> Args, |
2732 | OverloadCandidateSet& CandidateSet, |
2733 | bool SuppressUserConversions = false, |
2734 | bool PartialOverloading = false, |
2735 | ConversionSequenceList EarlyConversions = None); |
2736 | void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, |
2737 | DeclAccessPair FoundDecl, |
2738 | CXXRecordDecl *ActingContext, |
2739 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
2740 | QualType ObjectType, |
2741 | Expr::Classification ObjectClassification, |
2742 | ArrayRef<Expr *> Args, |
2743 | OverloadCandidateSet& CandidateSet, |
2744 | bool SuppressUserConversions = false, |
2745 | bool PartialOverloading = false); |
2746 | void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, |
2747 | DeclAccessPair FoundDecl, |
2748 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
2749 | ArrayRef<Expr *> Args, |
2750 | OverloadCandidateSet& CandidateSet, |
2751 | bool SuppressUserConversions = false, |
2752 | bool PartialOverloading = false); |
2753 | bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, |
2754 | ArrayRef<QualType> ParamTypes, |
2755 | ArrayRef<Expr *> Args, |
2756 | OverloadCandidateSet &CandidateSet, |
2757 | ConversionSequenceList &Conversions, |
2758 | bool SuppressUserConversions, |
2759 | CXXRecordDecl *ActingContext = nullptr, |
2760 | QualType ObjectType = QualType(), |
2761 | Expr::Classification |
2762 | ObjectClassification = {}); |
2763 | void AddConversionCandidate(CXXConversionDecl *Conversion, |
2764 | DeclAccessPair FoundDecl, |
2765 | CXXRecordDecl *ActingContext, |
2766 | Expr *From, QualType ToType, |
2767 | OverloadCandidateSet& CandidateSet, |
2768 | bool AllowObjCConversionOnExplicit, |
2769 | bool AllowResultConversion = true); |
2770 | void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, |
2771 | DeclAccessPair FoundDecl, |
2772 | CXXRecordDecl *ActingContext, |
2773 | Expr *From, QualType ToType, |
2774 | OverloadCandidateSet &CandidateSet, |
2775 | bool AllowObjCConversionOnExplicit, |
2776 | bool AllowResultConversion = true); |
2777 | void AddSurrogateCandidate(CXXConversionDecl *Conversion, |
2778 | DeclAccessPair FoundDecl, |
2779 | CXXRecordDecl *ActingContext, |
2780 | const FunctionProtoType *Proto, |
2781 | Expr *Object, ArrayRef<Expr *> Args, |
2782 | OverloadCandidateSet& CandidateSet); |
2783 | void AddMemberOperatorCandidates(OverloadedOperatorKind Op, |
2784 | SourceLocation OpLoc, ArrayRef<Expr *> Args, |
2785 | OverloadCandidateSet& CandidateSet, |
2786 | SourceRange OpRange = SourceRange()); |
2787 | void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, |
2788 | OverloadCandidateSet& CandidateSet, |
2789 | bool IsAssignmentOperator = false, |
2790 | unsigned NumContextualBoolArguments = 0); |
2791 | void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, |
2792 | SourceLocation OpLoc, ArrayRef<Expr *> Args, |
2793 | OverloadCandidateSet& CandidateSet); |
2794 | void AddArgumentDependentLookupCandidates(DeclarationName Name, |
2795 | SourceLocation Loc, |
2796 | ArrayRef<Expr *> Args, |
2797 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
2798 | OverloadCandidateSet& CandidateSet, |
2799 | bool PartialOverloading = false); |
2800 | |
2801 | // Emit as a 'note' the specific overload candidate |
2802 | void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, |
2803 | QualType DestType = QualType(), |
2804 | bool TakingAddress = false); |
2805 | |
2806 | // Emit as a series of 'note's all template and non-templates identified by |
2807 | // the expression Expr |
2808 | void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), |
2809 | bool TakingAddress = false); |
2810 | |
2811 | /// Check the enable_if expressions on the given function. Returns the first |
2812 | /// failing attribute, or NULL if they were all successful. |
2813 | EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, |
2814 | bool MissingImplicitThis = false); |
2815 | |
2816 | /// Find the failed Boolean condition within a given Boolean |
2817 | /// constant expression, and describe it with a string. |
2818 | /// |
2819 | /// \param AllowTopLevelCond Whether to allow the result to be the |
2820 | /// complete top-level condition. |
2821 | std::pair<Expr *, std::string> |
2822 | findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond); |
2823 | |
2824 | /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any |
2825 | /// non-ArgDependent DiagnoseIfAttrs. |
2826 | /// |
2827 | /// Argument-dependent diagnose_if attributes should be checked each time a |
2828 | /// function is used as a direct callee of a function call. |
2829 | /// |
2830 | /// Returns true if any errors were emitted. |
2831 | bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, |
2832 | const Expr *ThisArg, |
2833 | ArrayRef<const Expr *> Args, |
2834 | SourceLocation Loc); |
2835 | |
2836 | /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any |
2837 | /// ArgDependent DiagnoseIfAttrs. |
2838 | /// |
2839 | /// Argument-independent diagnose_if attributes should be checked on every use |
2840 | /// of a function. |
2841 | /// |
2842 | /// Returns true if any errors were emitted. |
2843 | bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, |
2844 | SourceLocation Loc); |
2845 | |
2846 | /// Returns whether the given function's address can be taken or not, |
2847 | /// optionally emitting a diagnostic if the address can't be taken. |
2848 | /// |
2849 | /// Returns false if taking the address of the function is illegal. |
2850 | bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, |
2851 | bool Complain = false, |
2852 | SourceLocation Loc = SourceLocation()); |
2853 | |
2854 | // [PossiblyAFunctionType] --> [Return] |
2855 | // NonFunctionType --> NonFunctionType |
2856 | // R (A) --> R(A) |
2857 | // R (*)(A) --> R (A) |
2858 | // R (&)(A) --> R (A) |
2859 | // R (S::*)(A) --> R (A) |
2860 | QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); |
2861 | |
2862 | FunctionDecl * |
2863 | ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, |
2864 | QualType TargetType, |
2865 | bool Complain, |
2866 | DeclAccessPair &Found, |
2867 | bool *pHadMultipleCandidates = nullptr); |
2868 | |
2869 | FunctionDecl * |
2870 | resolveAddressOfOnlyViableOverloadCandidate(Expr *E, |
2871 | DeclAccessPair &FoundResult); |
2872 | |
2873 | bool resolveAndFixAddressOfOnlyViableOverloadCandidate( |
2874 | ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); |
2875 | |
2876 | FunctionDecl * |
2877 | ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, |
2878 | bool Complain = false, |
2879 | DeclAccessPair *Found = nullptr); |
2880 | |
2881 | bool ResolveAndFixSingleFunctionTemplateSpecialization( |
2882 | ExprResult &SrcExpr, |
2883 | bool DoFunctionPointerConverion = false, |
2884 | bool Complain = false, |
2885 | SourceRange OpRangeForComplaining = SourceRange(), |
2886 | QualType DestTypeForComplaining = QualType(), |
2887 | unsigned DiagIDForComplaining = 0); |
2888 | |
2889 | |
2890 | Expr *FixOverloadedFunctionReference(Expr *E, |
2891 | DeclAccessPair FoundDecl, |
2892 | FunctionDecl *Fn); |
2893 | ExprResult FixOverloadedFunctionReference(ExprResult, |
2894 | DeclAccessPair FoundDecl, |
2895 | FunctionDecl *Fn); |
2896 | |
2897 | void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, |
2898 | ArrayRef<Expr *> Args, |
2899 | OverloadCandidateSet &CandidateSet, |
2900 | bool PartialOverloading = false); |
2901 | |
2902 | // An enum used to represent the different possible results of building a |
2903 | // range-based for loop. |
2904 | enum ForRangeStatus { |
2905 | FRS_Success, |
2906 | FRS_NoViableFunction, |
2907 | FRS_DiagnosticIssued |
2908 | }; |
2909 | |
2910 | ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, |
2911 | SourceLocation RangeLoc, |
2912 | const DeclarationNameInfo &NameInfo, |
2913 | LookupResult &MemberLookup, |
2914 | OverloadCandidateSet *CandidateSet, |
2915 | Expr *Range, ExprResult *CallExpr); |
2916 | |
2917 | ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, |
2918 | UnresolvedLookupExpr *ULE, |
2919 | SourceLocation LParenLoc, |
2920 | MultiExprArg Args, |
2921 | SourceLocation RParenLoc, |
2922 | Expr *ExecConfig, |
2923 | bool AllowTypoCorrection=true, |
2924 | bool CalleesAddressIsTaken=false); |
2925 | |
2926 | bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, |
2927 | MultiExprArg Args, SourceLocation RParenLoc, |
2928 | OverloadCandidateSet *CandidateSet, |
2929 | ExprResult *Result); |
2930 | |
2931 | ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, |
2932 | UnaryOperatorKind Opc, |
2933 | const UnresolvedSetImpl &Fns, |
2934 | Expr *input, bool RequiresADL = true); |
2935 | |
2936 | ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, |
2937 | BinaryOperatorKind Opc, |
2938 | const UnresolvedSetImpl &Fns, |
2939 | Expr *LHS, Expr *RHS, |
2940 | bool RequiresADL = true); |
2941 | |
2942 | ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, |
2943 | SourceLocation RLoc, |
2944 | Expr *Base,Expr *Idx); |
2945 | |
2946 | ExprResult |
2947 | BuildCallToMemberFunction(Scope *S, Expr *MemExpr, |
2948 | SourceLocation LParenLoc, |
2949 | MultiExprArg Args, |
2950 | SourceLocation RParenLoc); |
2951 | ExprResult |
2952 | BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, |
2953 | MultiExprArg Args, |
2954 | SourceLocation RParenLoc); |
2955 | |
2956 | ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, |
2957 | SourceLocation OpLoc, |
2958 | bool *NoArrowOperatorFound = nullptr); |
2959 | |
2960 | /// CheckCallReturnType - Checks that a call expression's return type is |
2961 | /// complete. Returns true on failure. The location passed in is the location |
2962 | /// that best represents the call. |
2963 | bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, |
2964 | CallExpr *CE, FunctionDecl *FD); |
2965 | |
2966 | /// Helpers for dealing with blocks and functions. |
2967 | bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, |
2968 | bool CheckParameterNames); |
2969 | void CheckCXXDefaultArguments(FunctionDecl *FD); |
2970 | void CheckExtraCXXDefaultArguments(Declarator &D); |
2971 | Scope *getNonFieldDeclScope(Scope *S); |
2972 | |
2973 | /// \name Name lookup |
2974 | /// |
2975 | /// These routines provide name lookup that is used during semantic |
2976 | /// analysis to resolve the various kinds of names (identifiers, |
2977 | /// overloaded operator names, constructor names, etc.) into zero or |
2978 | /// more declarations within a particular scope. The major entry |
2979 | /// points are LookupName, which performs unqualified name lookup, |
2980 | /// and LookupQualifiedName, which performs qualified name lookup. |
2981 | /// |
2982 | /// All name lookup is performed based on some specific criteria, |
2983 | /// which specify what names will be visible to name lookup and how |
2984 | /// far name lookup should work. These criteria are important both |
2985 | /// for capturing language semantics (certain lookups will ignore |
2986 | /// certain names, for example) and for performance, since name |
2987 | /// lookup is often a bottleneck in the compilation of C++. Name |
2988 | /// lookup criteria is specified via the LookupCriteria enumeration. |
2989 | /// |
2990 | /// The results of name lookup can vary based on the kind of name |
2991 | /// lookup performed, the current language, and the translation |
2992 | /// unit. In C, for example, name lookup will either return nothing |
2993 | /// (no entity found) or a single declaration. In C++, name lookup |
2994 | /// can additionally refer to a set of overloaded functions or |
2995 | /// result in an ambiguity. All of the possible results of name |
2996 | /// lookup are captured by the LookupResult class, which provides |
2997 | /// the ability to distinguish among them. |
2998 | //@{ |
2999 | |
3000 | /// @brief Describes the kind of name lookup to perform. |
3001 | enum LookupNameKind { |
3002 | /// Ordinary name lookup, which finds ordinary names (functions, |
3003 | /// variables, typedefs, etc.) in C and most kinds of names |
3004 | /// (functions, variables, members, types, etc.) in C++. |
3005 | LookupOrdinaryName = 0, |
3006 | /// Tag name lookup, which finds the names of enums, classes, |
3007 | /// structs, and unions. |
3008 | LookupTagName, |
3009 | /// Label name lookup. |
3010 | LookupLabel, |
3011 | /// Member name lookup, which finds the names of |
3012 | /// class/struct/union members. |
3013 | LookupMemberName, |
3014 | /// Look up of an operator name (e.g., operator+) for use with |
3015 | /// operator overloading. This lookup is similar to ordinary name |
3016 | /// lookup, but will ignore any declarations that are class members. |
3017 | LookupOperatorName, |
3018 | /// Look up of a name that precedes the '::' scope resolution |
3019 | /// operator in C++. This lookup completely ignores operator, object, |
3020 | /// function, and enumerator names (C++ [basic.lookup.qual]p1). |
3021 | LookupNestedNameSpecifierName, |
3022 | /// Look up a namespace name within a C++ using directive or |
3023 | /// namespace alias definition, ignoring non-namespace names (C++ |
3024 | /// [basic.lookup.udir]p1). |
3025 | LookupNamespaceName, |
3026 | /// Look up all declarations in a scope with the given name, |
3027 | /// including resolved using declarations. This is appropriate |
3028 | /// for checking redeclarations for a using declaration. |
3029 | LookupUsingDeclName, |
3030 | /// Look up an ordinary name that is going to be redeclared as a |
3031 | /// name with linkage. This lookup ignores any declarations that |
3032 | /// are outside of the current scope unless they have linkage. See |
3033 | /// C99 6.2.2p4-5 and C++ [basic.link]p6. |
3034 | LookupRedeclarationWithLinkage, |
3035 | /// Look up a friend of a local class. This lookup does not look |
3036 | /// outside the innermost non-class scope. See C++11 [class.friend]p11. |
3037 | LookupLocalFriendName, |
3038 | /// Look up the name of an Objective-C protocol. |
3039 | LookupObjCProtocolName, |
3040 | /// Look up implicit 'self' parameter of an objective-c method. |
3041 | LookupObjCImplicitSelfParam, |
3042 | /// \brief Look up the name of an OpenMP user-defined reduction operation. |
3043 | LookupOMPReductionName, |
3044 | /// \brief Look up any declaration with any name. |
3045 | LookupAnyName |
3046 | }; |
3047 | |
3048 | /// \brief Specifies whether (or how) name lookup is being performed for a |
3049 | /// redeclaration (vs. a reference). |
3050 | enum RedeclarationKind { |
3051 | /// \brief The lookup is a reference to this name that is not for the |
3052 | /// purpose of redeclaring the name. |
3053 | NotForRedeclaration = 0, |
3054 | /// \brief The lookup results will be used for redeclaration of a name, |
3055 | /// if an entity by that name already exists and is visible. |
3056 | ForVisibleRedeclaration, |
3057 | /// \brief The lookup results will be used for redeclaration of a name |
3058 | /// with external linkage; non-visible lookup results with external linkage |
3059 | /// may also be found. |
3060 | ForExternalRedeclaration |
3061 | }; |
3062 | |
3063 | RedeclarationKind forRedeclarationInCurContext() { |
3064 | // A declaration with an owning module for linkage can never link against |
3065 | // anything that is not visible. We don't need to check linkage here; if |
3066 | // the context has internal linkage, redeclaration lookup won't find things |
3067 | // from other TUs, and we can't safely compute linkage yet in general. |
3068 | if (cast<Decl>(CurContext) |
3069 | ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) |
3070 | return ForVisibleRedeclaration; |
3071 | return ForExternalRedeclaration; |
3072 | } |
3073 | |
3074 | /// \brief The possible outcomes of name lookup for a literal operator. |
3075 | enum LiteralOperatorLookupResult { |
3076 | /// \brief The lookup resulted in an error. |
3077 | LOLR_Error, |
3078 | /// \brief The lookup found no match but no diagnostic was issued. |
3079 | LOLR_ErrorNoDiagnostic, |
3080 | /// \brief The lookup found a single 'cooked' literal operator, which |
3081 | /// expects a normal literal to be built and passed to it. |
3082 | LOLR_Cooked, |
3083 | /// \brief The lookup found a single 'raw' literal operator, which expects |
3084 | /// a string literal containing the spelling of the literal token. |
3085 | LOLR_Raw, |
3086 | /// \brief The lookup found an overload set of literal operator templates, |
3087 | /// which expect the characters of the spelling of the literal token to be |
3088 | /// passed as a non-type template argument pack. |
3089 | LOLR_Template, |
3090 | /// \brief The lookup found an overload set of literal operator templates, |
3091 | /// which expect the character type and characters of the spelling of the |
3092 | /// string literal token to be passed as template arguments. |
3093 | LOLR_StringTemplate |
3094 | }; |
3095 | |
3096 | SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, |
3097 | CXXSpecialMember SM, |
3098 | bool ConstArg, |
3099 | bool VolatileArg, |
3100 | bool RValueThis, |
3101 | bool ConstThis, |
3102 | bool VolatileThis); |
3103 | |
3104 | typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; |
3105 | typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> |
3106 | TypoRecoveryCallback; |
3107 | |
3108 | private: |
3109 | bool CppLookupName(LookupResult &R, Scope *S); |
3110 | |
3111 | struct TypoExprState { |
3112 | std::unique_ptr<TypoCorrectionConsumer> Consumer; |
3113 | TypoDiagnosticGenerator DiagHandler; |
3114 | TypoRecoveryCallback RecoveryHandler; |
3115 | TypoExprState(); |
3116 | TypoExprState(TypoExprState &&other) noexcept; |
3117 | TypoExprState &operator=(TypoExprState &&other) noexcept; |
3118 | }; |
3119 | |
3120 | /// \brief The set of unhandled TypoExprs and their associated state. |
3121 | llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; |
3122 | |
3123 | /// \brief Creates a new TypoExpr AST node. |
3124 | TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, |
3125 | TypoDiagnosticGenerator TDG, |
3126 | TypoRecoveryCallback TRC); |
3127 | |
3128 | // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls. |
3129 | // |
3130 | // The boolean value will be true to indicate that the namespace was loaded |
3131 | // from an AST/PCH file, or false otherwise. |
3132 | llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; |
3133 | |
3134 | /// \brief Whether we have already loaded known namespaces from an extenal |
3135 | /// source. |
3136 | bool LoadedExternalKnownNamespaces; |
3137 | |
3138 | /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and |
3139 | /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction |
3140 | /// should be skipped entirely. |
3141 | std::unique_ptr<TypoCorrectionConsumer> |
3142 | makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, |
3143 | Sema::LookupNameKind LookupKind, Scope *S, |
3144 | CXXScopeSpec *SS, |
3145 | std::unique_ptr<CorrectionCandidateCallback> CCC, |
3146 | DeclContext *MemberContext, bool EnteringContext, |
3147 | const ObjCObjectPointerType *OPT, |
3148 | bool ErrorRecovery); |
3149 | |
3150 | public: |
3151 | const TypoExprState &getTypoExprState(TypoExpr *TE) const; |
3152 | |
3153 | /// \brief Clears the state of the given TypoExpr. |
3154 | void clearDelayedTypo(TypoExpr *TE); |
3155 | |
3156 | /// \brief Look up a name, looking for a single declaration. Return |
3157 | /// null if the results were absent, ambiguous, or overloaded. |
3158 | /// |
3159 | /// It is preferable to use the elaborated form and explicitly handle |
3160 | /// ambiguity and overloaded. |
3161 | NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, |
3162 | SourceLocation Loc, |
3163 | LookupNameKind NameKind, |
3164 | RedeclarationKind Redecl |
3165 | = NotForRedeclaration); |
3166 | bool LookupName(LookupResult &R, Scope *S, |
3167 | bool AllowBuiltinCreation = false); |
3168 | bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, |
3169 | bool InUnqualifiedLookup = false); |
3170 | bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, |
3171 | CXXScopeSpec &SS); |
3172 | bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, |
3173 | bool AllowBuiltinCreation = false, |
3174 | bool EnteringContext = false); |
3175 | ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, |
3176 | RedeclarationKind Redecl |
3177 | = NotForRedeclaration); |
3178 | bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); |
3179 | |
3180 | void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, |
3181 | QualType T1, QualType T2, |
3182 | UnresolvedSetImpl &Functions); |
3183 | |
3184 | LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, |
3185 | SourceLocation GnuLabelLoc = SourceLocation()); |
3186 | |
3187 | DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); |
3188 | CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); |
3189 | CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, |
3190 | unsigned Quals); |
3191 | CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, |
3192 | bool RValueThis, unsigned ThisQuals); |
3193 | CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, |
3194 | unsigned Quals); |
3195 | CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, |
3196 | bool RValueThis, unsigned ThisQuals); |
3197 | CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); |
3198 | |
3199 | bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); |
3200 | LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, |
3201 | ArrayRef<QualType> ArgTys, |
3202 | bool AllowRaw, |
3203 | bool AllowTemplate, |
3204 | bool AllowStringTemplate, |
3205 | bool DiagnoseMissing); |
3206 | bool isKnownName(StringRef name); |
3207 | |
3208 | void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, |
3209 | ArrayRef<Expr *> Args, ADLResult &Functions); |
3210 | |
3211 | void LookupVisibleDecls(Scope *S, LookupNameKind Kind, |
3212 | VisibleDeclConsumer &Consumer, |
3213 | bool IncludeGlobalScope = true, |
3214 | bool LoadExternal = true); |
3215 | void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, |
3216 | VisibleDeclConsumer &Consumer, |
3217 | bool IncludeGlobalScope = true, |
3218 | bool IncludeDependentBases = false, |
3219 | bool LoadExternal = true); |
3220 | |
3221 | enum CorrectTypoKind { |
3222 | CTK_NonError, // CorrectTypo used in a non error recovery situation. |
3223 | CTK_ErrorRecovery // CorrectTypo used in normal error recovery. |
3224 | }; |
3225 | |
3226 | TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, |
3227 | Sema::LookupNameKind LookupKind, |
3228 | Scope *S, CXXScopeSpec *SS, |
3229 | std::unique_ptr<CorrectionCandidateCallback> CCC, |
3230 | CorrectTypoKind Mode, |
3231 | DeclContext *MemberContext = nullptr, |
3232 | bool EnteringContext = false, |
3233 | const ObjCObjectPointerType *OPT = nullptr, |
3234 | bool RecordFailure = true); |
3235 | |
3236 | TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, |
3237 | Sema::LookupNameKind LookupKind, Scope *S, |
3238 | CXXScopeSpec *SS, |
3239 | std::unique_ptr<CorrectionCandidateCallback> CCC, |
3240 | TypoDiagnosticGenerator TDG, |
3241 | TypoRecoveryCallback TRC, CorrectTypoKind Mode, |
3242 | DeclContext *MemberContext = nullptr, |
3243 | bool EnteringContext = false, |
3244 | const ObjCObjectPointerType *OPT = nullptr); |
3245 | |
3246 | /// \brief Process any TypoExprs in the given Expr and its children, |
3247 | /// generating diagnostics as appropriate and returning a new Expr if there |
3248 | /// were typos that were all successfully corrected and ExprError if one or |
3249 | /// more typos could not be corrected. |
3250 | /// |
3251 | /// \param E The Expr to check for TypoExprs. |
3252 | /// |
3253 | /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its |
3254 | /// initializer. |
3255 | /// |
3256 | /// \param Filter A function applied to a newly rebuilt Expr to determine if |
3257 | /// it is an acceptable/usable result from a single combination of typo |
3258 | /// corrections. As long as the filter returns ExprError, different |
3259 | /// combinations of corrections will be tried until all are exhausted. |
3260 | ExprResult |
3261 | CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr, |
3262 | llvm::function_ref<ExprResult(Expr *)> Filter = |
3263 | [](Expr *E) -> ExprResult { return E; }); |
3264 | |
3265 | ExprResult |
3266 | CorrectDelayedTyposInExpr(Expr *E, |
3267 | llvm::function_ref<ExprResult(Expr *)> Filter) { |
3268 | return CorrectDelayedTyposInExpr(E, nullptr, Filter); |
3269 | } |
3270 | |
3271 | ExprResult |
3272 | CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr, |
3273 | llvm::function_ref<ExprResult(Expr *)> Filter = |
3274 | [](Expr *E) -> ExprResult { return E; }) { |
3275 | return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); |
3276 | } |
3277 | |
3278 | ExprResult |
3279 | CorrectDelayedTyposInExpr(ExprResult ER, |
3280 | llvm::function_ref<ExprResult(Expr *)> Filter) { |
3281 | return CorrectDelayedTyposInExpr(ER, nullptr, Filter); |
3282 | } |
3283 | |
3284 | void diagnoseTypo(const TypoCorrection &Correction, |
3285 | const PartialDiagnostic &TypoDiag, |
3286 | bool ErrorRecovery = true); |
3287 | |
3288 | void diagnoseTypo(const TypoCorrection &Correction, |
3289 | const PartialDiagnostic &TypoDiag, |
3290 | const PartialDiagnostic &PrevNote, |
3291 | bool ErrorRecovery = true); |
3292 | |
3293 | void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); |
3294 | |
3295 | void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, |
3296 | ArrayRef<Expr *> Args, |
3297 | AssociatedNamespaceSet &AssociatedNamespaces, |
3298 | AssociatedClassSet &AssociatedClasses); |
3299 | |
3300 | void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, |
3301 | bool ConsiderLinkage, bool AllowInlineNamespace); |
3302 | |
3303 | bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); |
3304 | |
3305 | void DiagnoseAmbiguousLookup(LookupResult &Result); |
3306 | //@} |
3307 | |
3308 | ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, |
3309 | SourceLocation IdLoc, |
3310 | bool TypoCorrection = false); |
3311 | NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, |
3312 | Scope *S, bool ForRedeclaration, |
3313 | SourceLocation Loc); |
3314 | NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, |
3315 | Scope *S); |
3316 | void AddKnownFunctionAttributes(FunctionDecl *FD); |
3317 | |
3318 | // More parsing and symbol table subroutines. |
3319 | |
3320 | void ProcessPragmaWeak(Scope *S, Decl *D); |
3321 | // Decl attributes - this routine is the top level dispatcher. |
3322 | void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); |
3323 | // Helper for delayed processing of attributes. |
3324 | void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList); |
3325 | void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, |
3326 | bool IncludeCXX11Attributes = true); |
3327 | bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, |
3328 | const AttributeList *AttrList); |
3329 | |
3330 | void checkUnusedDeclAttributes(Declarator &D); |
3331 | |
3332 | /// Determine if type T is a valid subject for a nonnull and similar |
3333 | /// attributes. By default, we look through references (the behavior used by |
3334 | /// nonnull), but if the second parameter is true, then we treat a reference |
3335 | /// type as valid. |
3336 | bool isValidPointerAttrType(QualType T, bool RefOkay = false); |
3337 | |
3338 | bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); |
3339 | bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, |
3340 | const FunctionDecl *FD = nullptr); |
3341 | bool CheckNoReturnAttr(const AttributeList &attr); |
3342 | bool CheckNoCallerSavedRegsAttr(const AttributeList &attr); |
3343 | bool checkStringLiteralArgumentAttr(const AttributeList &Attr, |
3344 | unsigned ArgNum, StringRef &Str, |
3345 | SourceLocation *ArgLocation = nullptr); |
3346 | bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); |
3347 | bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); |
3348 | bool checkMSInheritanceAttrOnDefinition( |
3349 | CXXRecordDecl *RD, SourceRange Range, bool BestCase, |
3350 | MSInheritanceAttr::Spelling SemanticSpelling); |
3351 | |
3352 | void CheckAlignasUnderalignment(Decl *D); |
3353 | |
3354 | /// Adjust the calling convention of a method to be the ABI default if it |
3355 | /// wasn't specified explicitly. This handles method types formed from |
3356 | /// function type typedefs and typename template arguments. |
3357 | void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, |
3358 | SourceLocation Loc); |
3359 | |
3360 | // Check if there is an explicit attribute, but only look through parens. |
3361 | // The intent is to look for an attribute on the current declarator, but not |
3362 | // one that came from a typedef. |
3363 | bool hasExplicitCallingConv(QualType &T); |
3364 | |
3365 | /// Get the outermost AttributedType node that sets a calling convention. |
3366 | /// Valid types should not have multiple attributes with different CCs. |
3367 | const AttributedType *getCallingConvAttributedType(QualType T) const; |
3368 | |
3369 | /// Check whether a nullability type specifier can be added to the given |
3370 | /// type. |
3371 | /// |
3372 | /// \param type The type to which the nullability specifier will be |
3373 | /// added. On success, this type will be updated appropriately. |
3374 | /// |
3375 | /// \param nullability The nullability specifier to add. |
3376 | /// |
3377 | /// \param nullabilityLoc The location of the nullability specifier. |
3378 | /// |
3379 | /// \param isContextSensitive Whether this nullability specifier was |
3380 | /// written as a context-sensitive keyword (in an Objective-C |
3381 | /// method) or an Objective-C property attribute, rather than as an |
3382 | /// underscored type specifier. |
3383 | /// |
3384 | /// \param allowArrayTypes Whether to accept nullability specifiers on an |
3385 | /// array type (e.g., because it will decay to a pointer). |
3386 | /// |
3387 | /// \returns true if nullability cannot be applied, false otherwise. |
3388 | bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability, |
3389 | SourceLocation nullabilityLoc, |
3390 | bool isContextSensitive, |
3391 | bool allowArrayTypes); |
3392 | |
3393 | /// \brief Stmt attributes - this routine is the top level dispatcher. |
3394 | StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs, |
3395 | SourceRange Range); |
3396 | |
3397 | void WarnConflictingTypedMethods(ObjCMethodDecl *Method, |
3398 | ObjCMethodDecl *MethodDecl, |
3399 | bool IsProtocolMethodDecl); |
3400 | |
3401 | void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, |
3402 | ObjCMethodDecl *Overridden, |
3403 | bool IsProtocolMethodDecl); |
3404 | |
3405 | /// WarnExactTypedMethods - This routine issues a warning if method |
3406 | /// implementation declaration matches exactly that of its declaration. |
3407 | void WarnExactTypedMethods(ObjCMethodDecl *Method, |
3408 | ObjCMethodDecl *MethodDecl, |
3409 | bool IsProtocolMethodDecl); |
3410 | |
3411 | typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; |
3412 | |
3413 | /// CheckImplementationIvars - This routine checks if the instance variables |
3414 | /// listed in the implelementation match those listed in the interface. |
3415 | void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, |
3416 | ObjCIvarDecl **Fields, unsigned nIvars, |
3417 | SourceLocation Loc); |
3418 | |
3419 | /// ImplMethodsVsClassMethods - This is main routine to warn if any method |
3420 | /// remains unimplemented in the class or category \@implementation. |
3421 | void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, |
3422 | ObjCContainerDecl* IDecl, |
3423 | bool IncompleteImpl = false); |
3424 | |
3425 | /// DiagnoseUnimplementedProperties - This routine warns on those properties |
3426 | /// which must be implemented by this implementation. |
3427 | void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, |
3428 | ObjCContainerDecl *CDecl, |
3429 | bool SynthesizeProperties); |
3430 | |
3431 | /// Diagnose any null-resettable synthesized setters. |
3432 | void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); |
3433 | |
3434 | /// DefaultSynthesizeProperties - This routine default synthesizes all |
3435 | /// properties which must be synthesized in the class's \@implementation. |
3436 | void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, |
3437 | ObjCInterfaceDecl *IDecl, |
3438 | SourceLocation AtEnd); |
3439 | void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); |
3440 | |
3441 | /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is |
3442 | /// an ivar synthesized for 'Method' and 'Method' is a property accessor |
3443 | /// declared in class 'IFace'. |
3444 | bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, |
3445 | ObjCMethodDecl *Method, ObjCIvarDecl *IV); |
3446 | |
3447 | /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which |
3448 | /// backs the property is not used in the property's accessor. |
3449 | void DiagnoseUnusedBackingIvarInAccessor(Scope *S, |
3450 | const ObjCImplementationDecl *ImplD); |
3451 | |
3452 | /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and |
3453 | /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. |
3454 | /// It also returns ivar's property on success. |
3455 | ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, |
3456 | const ObjCPropertyDecl *&PDecl) const; |
3457 | |
3458 | /// Called by ActOnProperty to handle \@property declarations in |
3459 | /// class extensions. |
3460 | ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, |
3461 | SourceLocation AtLoc, |
3462 | SourceLocation LParenLoc, |
3463 | FieldDeclarator &FD, |
3464 | Selector GetterSel, |
3465 | SourceLocation GetterNameLoc, |
3466 | Selector SetterSel, |
3467 | SourceLocation SetterNameLoc, |
3468 | const bool isReadWrite, |
3469 | unsigned &Attributes, |
3470 | const unsigned AttributesAsWritten, |
3471 | QualType T, |
3472 | TypeSourceInfo *TSI, |
3473 | tok::ObjCKeywordKind MethodImplKind); |
3474 | |
3475 | /// Called by ActOnProperty and HandlePropertyInClassExtension to |
3476 | /// handle creating the ObjcPropertyDecl for a category or \@interface. |
3477 | ObjCPropertyDecl *CreatePropertyDecl(Scope *S, |
3478 | ObjCContainerDecl *CDecl, |
3479 | SourceLocation AtLoc, |
3480 | SourceLocation LParenLoc, |
3481 | FieldDeclarator &FD, |
3482 | Selector GetterSel, |
3483 | SourceLocation GetterNameLoc, |
3484 | Selector SetterSel, |
3485 | SourceLocation SetterNameLoc, |
3486 | const bool isReadWrite, |
3487 | const unsigned Attributes, |
3488 | const unsigned AttributesAsWritten, |
3489 | QualType T, |
3490 | TypeSourceInfo *TSI, |
3491 | tok::ObjCKeywordKind MethodImplKind, |
3492 | DeclContext *lexicalDC = nullptr); |
3493 | |
3494 | /// AtomicPropertySetterGetterRules - This routine enforces the rule (via |
3495 | /// warning) when atomic property has one but not the other user-declared |
3496 | /// setter or getter. |
3497 | void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, |
3498 | ObjCInterfaceDecl* IDecl); |
3499 | |
3500 | void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); |
3501 | |
3502 | void DiagnoseMissingDesignatedInitOverrides( |
3503 | const ObjCImplementationDecl *ImplD, |
3504 | const ObjCInterfaceDecl *IFD); |
3505 | |
3506 | void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); |
3507 | |
3508 | enum MethodMatchStrategy { |
3509 | MMS_loose, |
3510 | MMS_strict |
3511 | }; |
3512 | |
3513 | /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns |
3514 | /// true, or false, accordingly. |
3515 | bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, |
3516 | const ObjCMethodDecl *PrevMethod, |
3517 | MethodMatchStrategy strategy = MMS_strict); |
3518 | |
3519 | /// MatchAllMethodDeclarations - Check methods declaraed in interface or |
3520 | /// or protocol against those declared in their implementations. |
3521 | void MatchAllMethodDeclarations(const SelectorSet &InsMap, |
3522 | const SelectorSet &ClsMap, |
3523 | SelectorSet &InsMapSeen, |
3524 | SelectorSet &ClsMapSeen, |
3525 | ObjCImplDecl* IMPDecl, |
3526 | ObjCContainerDecl* IDecl, |
3527 | bool &IncompleteImpl, |
3528 | bool ImmediateClass, |
3529 | bool WarnCategoryMethodImpl=false); |
3530 | |
3531 | /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in |
3532 | /// category matches with those implemented in its primary class and |
3533 | /// warns each time an exact match is found. |
3534 | void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); |
3535 | |
3536 | /// \brief Add the given method to the list of globally-known methods. |
3537 | void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); |
3538 | |
3539 | private: |
3540 | /// AddMethodToGlobalPool - Add an instance or factory method to the global |
3541 | /// pool. See descriptoin of AddInstanceMethodToGlobalPool. |
3542 | void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); |
3543 | |
3544 | /// LookupMethodInGlobalPool - Returns the instance or factory method and |
3545 | /// optionally warns if there are multiple signatures. |
3546 | ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, |
3547 | bool receiverIdOrClass, |
3548 | bool instance); |
3549 | |
3550 | public: |
3551 | /// \brief - Returns instance or factory methods in global method pool for |
3552 | /// given selector. It checks the desired kind first, if none is found, and |
3553 | /// parameter checkTheOther is set, it then checks the other kind. If no such |
3554 | /// method or only one method is found, function returns false; otherwise, it |
3555 | /// returns true. |
3556 | bool |
3557 | CollectMultipleMethodsInGlobalPool(Selector Sel, |
3558 | SmallVectorImpl<ObjCMethodDecl*>& Methods, |
3559 | bool InstanceFirst, bool CheckTheOther, |
3560 | const ObjCObjectType *TypeBound = nullptr); |
3561 | |
3562 | bool |
3563 | AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, |
3564 | SourceRange R, bool receiverIdOrClass, |
3565 | SmallVectorImpl<ObjCMethodDecl*>& Methods); |
3566 | |
3567 | void |
3568 | DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, |
3569 | Selector Sel, SourceRange R, |
3570 | bool receiverIdOrClass); |
3571 | |
3572 | private: |
3573 | /// \brief - Returns a selector which best matches given argument list or |
3574 | /// nullptr if none could be found |
3575 | ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, |
3576 | bool IsInstance, |
3577 | SmallVectorImpl<ObjCMethodDecl*>& Methods); |
3578 | |
3579 | |
3580 | /// \brief Record the typo correction failure and return an empty correction. |
3581 | TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, |
3582 | bool RecordFailure = true) { |
3583 | if (RecordFailure) |
3584 | TypoCorrectionFailures[Typo].insert(TypoLoc); |
3585 | return TypoCorrection(); |
3586 | } |
3587 | |
3588 | public: |
3589 | /// AddInstanceMethodToGlobalPool - All instance methods in a translation |
3590 | /// unit are added to a global pool. This allows us to efficiently associate |
3591 | /// a selector with a method declaraation for purposes of typechecking |
3592 | /// messages sent to "id" (where the class of the object is unknown). |
3593 | void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { |
3594 | AddMethodToGlobalPool(Method, impl, /*instance*/true); |
3595 | } |
3596 | |
3597 | /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. |
3598 | void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { |
3599 | AddMethodToGlobalPool(Method, impl, /*instance*/false); |
3600 | } |
3601 | |
3602 | /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global |
3603 | /// pool. |
3604 | void AddAnyMethodToGlobalPool(Decl *D); |
3605 | |
3606 | /// LookupInstanceMethodInGlobalPool - Returns the method and warns if |
3607 | /// there are multiple signatures. |
3608 | ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, |
3609 | bool receiverIdOrClass=false) { |
3610 | return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, |
3611 | /*instance*/true); |
3612 | } |
3613 | |
3614 | /// LookupFactoryMethodInGlobalPool - Returns the method and warns if |
3615 | /// there are multiple signatures. |
3616 | ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, |
3617 | bool receiverIdOrClass=false) { |
3618 | return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, |
3619 | /*instance*/false); |
3620 | } |
3621 | |
3622 | const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, |
3623 | QualType ObjectType=QualType()); |
3624 | /// LookupImplementedMethodInGlobalPool - Returns the method which has an |
3625 | /// implementation. |
3626 | ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); |
3627 | |
3628 | /// CollectIvarsToConstructOrDestruct - Collect those ivars which require |
3629 | /// initialization. |
3630 | void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, |
3631 | SmallVectorImpl<ObjCIvarDecl*> &Ivars); |
3632 | |
3633 | //===--------------------------------------------------------------------===// |
3634 | // Statement Parsing Callbacks: SemaStmt.cpp. |
3635 | public: |
3636 | class FullExprArg { |
3637 | public: |
3638 | FullExprArg() : E(nullptr) { } |
3639 | FullExprArg(Sema &actions) : E(nullptr) { } |
3640 | |
3641 | ExprResult release() { |
3642 | return E; |
3643 | } |
3644 | |
3645 | Expr *get() const { return E; } |
3646 | |
3647 | Expr *operator->() { |
3648 | return E; |
3649 | } |
3650 | |
3651 | private: |
3652 | // FIXME: No need to make the entire Sema class a friend when it's just |
3653 | // Sema::MakeFullExpr that needs access to the constructor below. |
3654 | friend class Sema; |
3655 | |
3656 | explicit FullExprArg(Expr *expr) : E(expr) {} |
3657 | |
3658 | Expr *E; |
3659 | }; |
3660 | |
3661 | FullExprArg MakeFullExpr(Expr *Arg) { |
3662 | return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); |
3663 | } |
3664 | FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { |
3665 | return FullExprArg(ActOnFinishFullExpr(Arg, CC).get()); |
3666 | } |
3667 | FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { |
3668 | ExprResult FE = |
3669 | ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), |
3670 | /*DiscardedValue*/ true); |
3671 | return FullExprArg(FE.get()); |
3672 | } |
3673 | |
3674 | StmtResult ActOnExprStmt(ExprResult Arg); |
3675 | StmtResult ActOnExprStmtError(); |
3676 | |
3677 | StmtResult ActOnNullStmt(SourceLocation SemiLoc, |
3678 | bool HasLeadingEmptyMacro = false); |
3679 | |
3680 | void ActOnStartOfCompoundStmt(bool IsStmtExpr); |
3681 | void ActOnFinishOfCompoundStmt(); |
3682 | StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, |
3683 | ArrayRef<Stmt *> Elts, bool isStmtExpr); |
3684 | |
3685 | /// \brief A RAII object to enter scope of a compound statement. |
3686 | class CompoundScopeRAII { |
3687 | public: |
3688 | CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { |
3689 | S.ActOnStartOfCompoundStmt(IsStmtExpr); |
3690 | } |
3691 | |
3692 | ~CompoundScopeRAII() { |
3693 | S.ActOnFinishOfCompoundStmt(); |
3694 | } |
3695 | |
3696 | private: |
3697 | Sema &S; |
3698 | }; |
3699 | |
3700 | /// An RAII helper that pops function a function scope on exit. |
3701 | struct FunctionScopeRAII { |
3702 | Sema &S; |
3703 | bool Active; |
3704 | FunctionScopeRAII(Sema &S) : S(S), Active(true) {} |
3705 | ~FunctionScopeRAII() { |
3706 | if (Active) |
3707 | S.PopFunctionScopeInfo(); |
3708 | } |
3709 | void disable() { Active = false; } |
3710 | }; |
3711 | |
3712 | StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, |
3713 | SourceLocation StartLoc, |
3714 | SourceLocation EndLoc); |
3715 | void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); |
3716 | StmtResult ActOnForEachLValueExpr(Expr *E); |
3717 | StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, |
3718 | SourceLocation DotDotDotLoc, Expr *RHSVal, |
3719 | SourceLocation ColonLoc); |
3720 | void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); |
3721 | |
3722 | StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, |
3723 | SourceLocation ColonLoc, |
3724 | Stmt *SubStmt, Scope *CurScope); |
3725 | StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, |
3726 | SourceLocation ColonLoc, Stmt *SubStmt); |
3727 | |
3728 | StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, |
3729 | ArrayRef<const Attr*> Attrs, |
3730 | Stmt *SubStmt); |
3731 | |
3732 | class ConditionResult; |
3733 | StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, |
3734 | Stmt *InitStmt, |
3735 | ConditionResult Cond, Stmt *ThenVal, |
3736 | SourceLocation ElseLoc, Stmt *ElseVal); |
3737 | StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, |
3738 | Stmt *InitStmt, |
3739 | ConditionResult Cond, Stmt *ThenVal, |
3740 | SourceLocation ElseLoc, Stmt *ElseVal); |
3741 | StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, |
3742 | Stmt *InitStmt, |
3743 | ConditionResult Cond); |
3744 | StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, |
3745 | Stmt *Switch, Stmt *Body); |
3746 | StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, |
3747 | Stmt *Body); |
3748 | StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, |
3749 | SourceLocation WhileLoc, SourceLocation CondLParen, |
3750 | Expr *Cond, SourceLocation CondRParen); |
3751 | |
3752 | StmtResult ActOnForStmt(SourceLocation ForLoc, |
3753 | SourceLocation LParenLoc, |
3754 | Stmt *First, |
3755 | ConditionResult Second, |
3756 | FullExprArg Third, |
3757 | SourceLocation RParenLoc, |
3758 | Stmt *Body); |
3759 | ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, |
3760 | Expr *collection); |
3761 | StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, |
3762 | Stmt *First, Expr *collection, |
3763 | SourceLocation RParenLoc); |
3764 | StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); |
3765 | |
3766 | enum BuildForRangeKind { |
3767 | /// Initial building of a for-range statement. |
3768 | BFRK_Build, |
3769 | /// Instantiation or recovery rebuild of a for-range statement. Don't |
3770 | /// attempt any typo-correction. |
3771 | BFRK_Rebuild, |
3772 | /// Determining whether a for-range statement could be built. Avoid any |
3773 | /// unnecessary or irreversible actions. |
3774 | BFRK_Check |
3775 | }; |
3776 | |
3777 | StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, |
3778 | SourceLocation CoawaitLoc, |
3779 | Stmt *LoopVar, |
3780 | SourceLocation ColonLoc, Expr *Collection, |
3781 | SourceLocation RParenLoc, |
3782 | BuildForRangeKind Kind); |
3783 | StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, |
3784 | SourceLocation CoawaitLoc, |
3785 | SourceLocation ColonLoc, |
3786 | Stmt *RangeDecl, Stmt *Begin, Stmt *End, |
3787 | Expr *Cond, Expr *Inc, |
3788 | Stmt *LoopVarDecl, |
3789 | SourceLocation RParenLoc, |
3790 | BuildForRangeKind Kind); |
3791 | StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); |
3792 | |
3793 | StmtResult ActOnGotoStmt(SourceLocation GotoLoc, |
3794 | SourceLocation LabelLoc, |
3795 | LabelDecl *TheDecl); |
3796 | StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, |
3797 | SourceLocation StarLoc, |
3798 | Expr *DestExp); |
3799 | StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); |
3800 | StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); |
3801 | |
3802 | void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, |
3803 | CapturedRegionKind Kind, unsigned NumParams); |
3804 | typedef std::pair<StringRef, QualType> CapturedParamNameType; |
3805 | void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, |
3806 | CapturedRegionKind Kind, |
3807 | ArrayRef<CapturedParamNameType> Params); |
3808 | StmtResult ActOnCapturedRegionEnd(Stmt *S); |
3809 | void ActOnCapturedRegionError(); |
3810 | RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, |
3811 | SourceLocation Loc, |
3812 | unsigned NumParams); |
3813 | VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, |
3814 | bool AllowParamOrMoveConstructible); |
3815 | bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, |
3816 | bool AllowParamOrMoveConstructible); |
3817 | |
3818 | StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, |
3819 | Scope *CurScope); |
3820 | StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); |
3821 | StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); |
3822 | |
3823 | StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, |
3824 | bool IsVolatile, unsigned NumOutputs, |
3825 | unsigned NumInputs, IdentifierInfo **Names, |
3826 | MultiExprArg Constraints, MultiExprArg Exprs, |
3827 | Expr *AsmString, MultiExprArg Clobbers, |
3828 | SourceLocation RParenLoc); |
3829 | |
3830 | void FillInlineAsmIdentifierInfo(Expr *Res, |
3831 | llvm::InlineAsmIdentifierInfo &Info); |
3832 | ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, |
3833 | SourceLocation TemplateKWLoc, |
3834 | UnqualifiedId &Id, |
3835 | bool IsUnevaluatedContext); |
3836 | bool LookupInlineAsmField(StringRef Base, StringRef Member, |
3837 | unsigned &Offset, SourceLocation AsmLoc); |
3838 | ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, |
3839 | SourceLocation AsmLoc); |
3840 | StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, |
3841 | ArrayRef<Token> AsmToks, |
3842 | StringRef AsmString, |
3843 | unsigned NumOutputs, unsigned NumInputs, |
3844 | ArrayRef<StringRef> Constraints, |
3845 | ArrayRef<StringRef> Clobbers, |
3846 | ArrayRef<Expr*> Exprs, |
3847 | SourceLocation EndLoc); |
3848 | LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, |
3849 | SourceLocation Location, |
3850 | bool AlwaysCreate); |
3851 | |
3852 | VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, |
3853 | SourceLocation StartLoc, |
3854 | SourceLocation IdLoc, IdentifierInfo *Id, |
3855 | bool Invalid = false); |
3856 | |
3857 | Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); |
3858 | |
3859 | StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, |
3860 | Decl *Parm, Stmt *Body); |
3861 | |
3862 | StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); |
3863 | |
3864 | StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, |
3865 | MultiStmtArg Catch, Stmt *Finally); |
3866 | |
3867 | StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); |
3868 | StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, |
3869 | Scope *CurScope); |
3870 | ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, |
3871 | Expr *operand); |
3872 | StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, |
3873 | Expr *SynchExpr, |
3874 | Stmt *SynchBody); |
3875 | |
3876 | StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); |
3877 | |
3878 | VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, |
3879 | SourceLocation StartLoc, |
3880 | SourceLocation IdLoc, |
3881 | IdentifierInfo *Id); |
3882 | |
3883 | Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); |
3884 | |
3885 | StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, |
3886 | Decl *ExDecl, Stmt *HandlerBlock); |
3887 | StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, |
3888 | ArrayRef<Stmt *> Handlers); |
3889 | |
3890 | StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? |
3891 | SourceLocation TryLoc, Stmt *TryBlock, |
3892 | Stmt *Handler); |
3893 | StmtResult ActOnSEHExceptBlock(SourceLocation Loc, |
3894 | Expr *FilterExpr, |
3895 | Stmt *Block); |
3896 | void ActOnStartSEHFinallyBlock(); |
3897 | void ActOnAbortSEHFinallyBlock(); |
3898 | StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); |
3899 | StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); |
3900 | |
3901 | void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); |
3902 | |
3903 | bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; |
3904 | |
3905 | /// \brief If it's a file scoped decl that must warn if not used, keep track |
3906 | /// of it. |
3907 | void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); |
3908 | |
3909 | /// DiagnoseUnusedExprResult - If the statement passed in is an expression |
3910 | /// whose result is unused, warn. |
3911 | void DiagnoseUnusedExprResult(const Stmt *S); |
3912 | void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); |
3913 | void DiagnoseUnusedDecl(const NamedDecl *ND); |
3914 | |
3915 | /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null |
3916 | /// statement as a \p Body, and it is located on the same line. |
3917 | /// |
3918 | /// This helps prevent bugs due to typos, such as: |
3919 | /// if (condition); |
3920 | /// do_stuff(); |
3921 | void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, |
3922 | const Stmt *Body, |
3923 | unsigned DiagID); |
3924 | |
3925 | /// Warn if a for/while loop statement \p S, which is followed by |
3926 | /// \p PossibleBody, has a suspicious null statement as a body. |
3927 | void DiagnoseEmptyLoopBody(const Stmt *S, |
3928 | const Stmt *PossibleBody); |
3929 | |
3930 | /// Warn if a value is moved to itself. |
3931 | void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, |
3932 | SourceLocation OpLoc); |
3933 | |
3934 | /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a |
3935 | /// _Nonnull one. |
3936 | void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, |
3937 | SourceLocation Loc); |
3938 | |
3939 | /// Warn when implicitly casting 0 to nullptr. |
3940 | void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); |
3941 | |
3942 | ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { |
3943 | return DelayedDiagnostics.push(pool); |
3944 | } |
3945 | void PopParsingDeclaration(ParsingDeclState state, Decl *decl); |
3946 | |
3947 | typedef ProcessingContextState ParsingClassState; |
3948 | ParsingClassState PushParsingClass() { |
3949 | return DelayedDiagnostics.pushUndelayed(); |
3950 | } |
3951 | void PopParsingClass(ParsingClassState state) { |
3952 | DelayedDiagnostics.popUndelayed(state); |
3953 | } |
3954 | |
3955 | void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); |
3956 | |
3957 | void DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc, |
3958 | const ObjCInterfaceDecl *UnknownObjCClass, |
3959 | bool ObjCPropertyAccess, |
3960 | bool AvoidPartialAvailabilityChecks = false); |
3961 | |
3962 | bool makeUnavailableInSystemHeader(SourceLocation loc, |
3963 | UnavailableAttr::ImplicitReason reason); |
3964 | |
3965 | /// \brief Issue any -Wunguarded-availability warnings in \c FD |
3966 | void DiagnoseUnguardedAvailabilityViolations(Decl *FD); |
3967 | |
3968 | //===--------------------------------------------------------------------===// |
3969 | // Expression Parsing Callbacks: SemaExpr.cpp. |
3970 | |
3971 | bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); |
3972 | bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, |
3973 | const ObjCInterfaceDecl *UnknownObjCClass = nullptr, |
3974 | bool ObjCPropertyAccess = false, |
3975 | bool AvoidPartialAvailabilityChecks = false); |
3976 | void NoteDeletedFunction(FunctionDecl *FD); |
3977 | void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); |
3978 | std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); |
3979 | bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, |
3980 | ObjCMethodDecl *Getter, |
3981 | SourceLocation Loc); |
3982 | void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, |
3983 | ArrayRef<Expr *> Args); |
3984 | |
3985 | void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, |
3986 | Decl *LambdaContextDecl = nullptr, |
3987 | bool IsDecltype = false); |
3988 | enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; |
3989 | void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, |
3990 | ReuseLambdaContextDecl_t, |
3991 | bool IsDecltype = false); |
3992 | void PopExpressionEvaluationContext(); |
3993 | |
3994 | void DiscardCleanupsInEvaluationContext(); |
3995 | |
3996 | ExprResult TransformToPotentiallyEvaluated(Expr *E); |
3997 | ExprResult HandleExprEvaluationContextForTypeof(Expr *E); |
3998 | |
3999 | ExprResult ActOnConstantExpression(ExprResult Res); |
4000 | |
4001 | // Functions for marking a declaration referenced. These functions also |
4002 | // contain the relevant logic for marking if a reference to a function or |
4003 | // variable is an odr-use (in the C++11 sense). There are separate variants |
4004 | // for expressions referring to a decl; these exist because odr-use marking |
4005 | // needs to be delayed for some constant variables when we build one of the |
4006 | // named expressions. |
4007 | // |
4008 | // MightBeOdrUse indicates whether the use could possibly be an odr-use, and |
4009 | // should usually be true. This only needs to be set to false if the lack of |
4010 | // odr-use cannot be determined from the current context (for instance, |
4011 | // because the name denotes a virtual function and was written without an |
4012 | // explicit nested-name-specifier). |
4013 | void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); |
4014 | void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, |
4015 | bool MightBeOdrUse = true); |
4016 | void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); |
4017 | void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); |
4018 | void MarkMemberReferenced(MemberExpr *E); |
4019 | |
4020 | void UpdateMarkingForLValueToRValue(Expr *E); |
4021 | void CleanupVarDeclMarking(); |
4022 | |
4023 | enum TryCaptureKind { |
4024 | TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef |
4025 | }; |
4026 | |
4027 | /// \brief Try to capture the given variable. |
4028 | /// |
4029 | /// \param Var The variable to capture. |
4030 | /// |
4031 | /// \param Loc The location at which the capture occurs. |
4032 | /// |
4033 | /// \param Kind The kind of capture, which may be implicit (for either a |
4034 | /// block or a lambda), or explicit by-value or by-reference (for a lambda). |
4035 | /// |
4036 | /// \param EllipsisLoc The location of the ellipsis, if one is provided in |
4037 | /// an explicit lambda capture. |
4038 | /// |
4039 | /// \param BuildAndDiagnose Whether we are actually supposed to add the |
4040 | /// captures or diagnose errors. If false, this routine merely check whether |
4041 | /// the capture can occur without performing the capture itself or complaining |
4042 | /// if the variable cannot be captured. |
4043 | /// |
4044 | /// \param CaptureType Will be set to the type of the field used to capture |
4045 | /// this variable in the innermost block or lambda. Only valid when the |
4046 | /// variable can be captured. |
4047 | /// |
4048 | /// \param DeclRefType Will be set to the type of a reference to the capture |
4049 | /// from within the current scope. Only valid when the variable can be |
4050 | /// captured. |
4051 | /// |
4052 | /// \param FunctionScopeIndexToStopAt If non-null, it points to the index |
4053 | /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. |
4054 | /// This is useful when enclosing lambdas must speculatively capture |
4055 | /// variables that may or may not be used in certain specializations of |
4056 | /// a nested generic lambda. |
4057 | /// |
4058 | /// \returns true if an error occurred (i.e., the variable cannot be |
4059 | /// captured) and false if the capture succeeded. |
4060 | bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, |
4061 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, |
4062 | QualType &CaptureType, |
4063 | QualType &DeclRefType, |
4064 | const unsigned *const FunctionScopeIndexToStopAt); |
4065 | |
4066 | /// \brief Try to capture the given variable. |
4067 | bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, |
4068 | TryCaptureKind Kind = TryCapture_Implicit, |
4069 | SourceLocation EllipsisLoc = SourceLocation()); |
4070 | |
4071 | /// \brief Checks if the variable must be captured. |
4072 | bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); |
4073 | |
4074 | /// \brief Given a variable, determine the type that a reference to that |
4075 | /// variable will have in the given scope. |
4076 | QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); |
4077 | |
4078 | /// Mark all of the declarations referenced within a particular AST node as |
4079 | /// referenced. Used when template instantiation instantiates a non-dependent |
4080 | /// type -- entities referenced by the type are now referenced. |
4081 | void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); |
4082 | void MarkDeclarationsReferencedInExpr(Expr *E, |
4083 | bool SkipLocalVariables = false); |
4084 | |
4085 | /// \brief Try to recover by turning the given expression into a |
4086 | /// call. Returns true if recovery was attempted or an error was |
4087 | /// emitted; this may also leave the ExprResult invalid. |
4088 | bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, |
4089 | bool ForceComplain = false, |
4090 | bool (*IsPlausibleResult)(QualType) = nullptr); |
4091 | |
4092 | /// \brief Figure out if an expression could be turned into a call. |
4093 | bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, |
4094 | UnresolvedSetImpl &NonTemplateOverloads); |
4095 | |
4096 | /// \brief Conditionally issue a diagnostic based on the current |
4097 | /// evaluation context. |
4098 | /// |
4099 | /// \param Statement If Statement is non-null, delay reporting the |
4100 | /// diagnostic until the function body is parsed, and then do a basic |
4101 | /// reachability analysis to determine if the statement is reachable. |
4102 | /// If it is unreachable, the diagnostic will not be emitted. |
4103 | bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, |
4104 | const PartialDiagnostic &PD); |
4105 | |
4106 | // Primary Expressions. |
4107 | SourceRange getExprRange(Expr *E) const; |
4108 | |
4109 | ExprResult ActOnIdExpression( |
4110 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
4111 | UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, |
4112 | std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr, |
4113 | bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); |
4114 | |
4115 | void DecomposeUnqualifiedId(const UnqualifiedId &Id, |
4116 | TemplateArgumentListInfo &Buffer, |
4117 | DeclarationNameInfo &NameInfo, |
4118 | const TemplateArgumentListInfo *&TemplateArgs); |
4119 | |
4120 | bool |
4121 | DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, |
4122 | std::unique_ptr<CorrectionCandidateCallback> CCC, |
4123 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, |
4124 | ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); |
4125 | |
4126 | ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, |
4127 | IdentifierInfo *II, |
4128 | bool AllowBuiltinCreation=false); |
4129 | |
4130 | ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, |
4131 | SourceLocation TemplateKWLoc, |
4132 | const DeclarationNameInfo &NameInfo, |
4133 | bool isAddressOfOperand, |
4134 | const TemplateArgumentListInfo *TemplateArgs); |
4135 | |
4136 | ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, |
4137 | ExprValueKind VK, |
4138 | SourceLocation Loc, |
4139 | const CXXScopeSpec *SS = nullptr); |
4140 | ExprResult |
4141 | BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
4142 | const DeclarationNameInfo &NameInfo, |
4143 | const CXXScopeSpec *SS = nullptr, |
4144 | NamedDecl *FoundD = nullptr, |
4145 | const TemplateArgumentListInfo *TemplateArgs = nullptr); |
4146 | ExprResult |
4147 | BuildAnonymousStructUnionMemberReference( |
4148 | const CXXScopeSpec &SS, |
4149 | SourceLocation nameLoc, |
4150 | IndirectFieldDecl *indirectField, |
4151 | DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), |
4152 | Expr *baseObjectExpr = nullptr, |
4153 | SourceLocation opLoc = SourceLocation()); |
4154 | |
4155 | ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, |
4156 | SourceLocation TemplateKWLoc, |
4157 | LookupResult &R, |
4158 | const TemplateArgumentListInfo *TemplateArgs, |
4159 | const Scope *S); |
4160 | ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, |
4161 | SourceLocation TemplateKWLoc, |
4162 | LookupResult &R, |
4163 | const TemplateArgumentListInfo *TemplateArgs, |
4164 | bool IsDefiniteInstance, |
4165 | const Scope *S); |
4166 | bool UseArgumentDependentLookup(const CXXScopeSpec &SS, |
4167 | const LookupResult &R, |
4168 | bool HasTrailingLParen); |
4169 | |
4170 | ExprResult |
4171 | BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, |
4172 | const DeclarationNameInfo &NameInfo, |
4173 | bool IsAddressOfOperand, const Scope *S, |
4174 | TypeSourceInfo **RecoveryTSI = nullptr); |
4175 | |
4176 | ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, |
4177 | SourceLocation TemplateKWLoc, |
4178 | const DeclarationNameInfo &NameInfo, |
4179 | const TemplateArgumentListInfo *TemplateArgs); |
4180 | |
4181 | ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, |
4182 | LookupResult &R, |
4183 | bool NeedsADL, |
4184 | bool AcceptInvalidDecl = false); |
4185 | ExprResult BuildDeclarationNameExpr( |
4186 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, |
4187 | NamedDecl *FoundD = nullptr, |
4188 | const TemplateArgumentListInfo *TemplateArgs = nullptr, |
4189 | bool AcceptInvalidDecl = false); |
4190 | |
4191 | ExprResult BuildLiteralOperatorCall(LookupResult &R, |
4192 | DeclarationNameInfo &SuffixInfo, |
4193 | ArrayRef<Expr *> Args, |
4194 | SourceLocation LitEndLoc, |
4195 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); |
4196 | |
4197 | ExprResult BuildPredefinedExpr(SourceLocation Loc, |
4198 | PredefinedExpr::IdentType IT); |
4199 | ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); |
4200 | ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); |
4201 | |
4202 | bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); |
4203 | |
4204 | ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); |
4205 | ExprResult ActOnCharacterConstant(const Token &Tok, |
4206 | Scope *UDLScope = nullptr); |
4207 | ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); |
4208 | ExprResult ActOnParenListExpr(SourceLocation L, |
4209 | SourceLocation R, |
4210 | MultiExprArg Val); |
4211 | |
4212 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string |
4213 | /// fragments (e.g. "foo" "bar" L"baz"). |
4214 | ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, |
4215 | Scope *UDLScope = nullptr); |
4216 | |
4217 | ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, |
4218 | SourceLocation DefaultLoc, |
4219 | SourceLocation RParenLoc, |
4220 | Expr *ControllingExpr, |
4221 | ArrayRef<ParsedType> ArgTypes, |
4222 | ArrayRef<Expr *> ArgExprs); |
4223 | ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, |
4224 | SourceLocation DefaultLoc, |
4225 | SourceLocation RParenLoc, |
4226 | Expr *ControllingExpr, |
4227 | ArrayRef<TypeSourceInfo *> Types, |
4228 | ArrayRef<Expr *> Exprs); |
4229 | |
4230 | // Binary/Unary Operators. 'Tok' is the token for the operator. |
4231 | ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, |
4232 | Expr *InputExpr); |
4233 | ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, |
4234 | UnaryOperatorKind Opc, Expr *Input); |
4235 | ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, |
4236 | tok::TokenKind Op, Expr *Input); |
4237 | |
4238 | QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); |
4239 | |
4240 | ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, |
4241 | SourceLocation OpLoc, |
4242 | UnaryExprOrTypeTrait ExprKind, |
4243 | SourceRange R); |
4244 | ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, |
4245 | UnaryExprOrTypeTrait ExprKind); |
4246 | ExprResult |
4247 | ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, |
4248 | UnaryExprOrTypeTrait ExprKind, |
4249 | bool IsType, void *TyOrEx, |
4250 | SourceRange ArgRange); |
4251 | |
4252 | ExprResult CheckPlaceholderExpr(Expr *E); |
4253 | bool CheckVecStepExpr(Expr *E); |
4254 | |
4255 | bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); |
4256 | bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, |
4257 | SourceRange ExprRange, |
4258 | UnaryExprOrTypeTrait ExprKind); |
4259 | ExprResult ActOnSizeofParameterPackExpr(Scope *S, |
4260 | SourceLocation OpLoc, |
4261 | IdentifierInfo &Name, |
4262 | SourceLocation NameLoc, |
4263 | SourceLocation RParenLoc); |
4264 | ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, |
4265 | tok::TokenKind Kind, Expr *Input); |
4266 | |
4267 | ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, |
4268 | Expr *Idx, SourceLocation RLoc); |
4269 | ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, |
4270 | Expr *Idx, SourceLocation RLoc); |
4271 | ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, |
4272 | Expr *LowerBound, SourceLocation ColonLoc, |
4273 | Expr *Length, SourceLocation RBLoc); |
4274 | |
4275 | // This struct is for use by ActOnMemberAccess to allow |
4276 | // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after |
4277 | // changing the access operator from a '.' to a '->' (to see if that is the |
4278 | // change needed to fix an error about an unknown member, e.g. when the class |
4279 | // defines a custom operator->). |
4280 | struct ActOnMemberAccessExtraArgs { |
4281 | Scope *S; |
4282 | UnqualifiedId &Id; |
4283 | Decl *ObjCImpDecl; |
4284 | }; |
4285 | |
4286 | ExprResult BuildMemberReferenceExpr( |
4287 | Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, |
4288 | CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
4289 | NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, |
4290 | const TemplateArgumentListInfo *TemplateArgs, |
4291 | const Scope *S, |
4292 | ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); |
4293 | |
4294 | ExprResult |
4295 | BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, |
4296 | bool IsArrow, const CXXScopeSpec &SS, |
4297 | SourceLocation TemplateKWLoc, |
4298 | NamedDecl *FirstQualifierInScope, LookupResult &R, |
4299 | const TemplateArgumentListInfo *TemplateArgs, |
4300 | const Scope *S, |
4301 | bool SuppressQualifierCheck = false, |
4302 | ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); |
4303 | |
4304 | ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, |
4305 | SourceLocation OpLoc, |
4306 | const CXXScopeSpec &SS, FieldDecl *Field, |
4307 | DeclAccessPair FoundDecl, |
4308 | const DeclarationNameInfo &MemberNameInfo); |
4309 | |
4310 | ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); |
4311 | |
4312 | bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, |
4313 | const CXXScopeSpec &SS, |
4314 | const LookupResult &R); |
4315 | |
4316 | ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, |
4317 | bool IsArrow, SourceLocation OpLoc, |
4318 | const CXXScopeSpec &SS, |
4319 | SourceLocation TemplateKWLoc, |
4320 | NamedDecl *FirstQualifierInScope, |
4321 | const DeclarationNameInfo &NameInfo, |
4322 | const TemplateArgumentListInfo *TemplateArgs); |
4323 | |
4324 | ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, |
4325 | SourceLocation OpLoc, |
4326 | tok::TokenKind OpKind, |
4327 | CXXScopeSpec &SS, |
4328 | SourceLocation TemplateKWLoc, |
4329 | UnqualifiedId &Member, |
4330 | Decl *ObjCImpDecl); |
4331 | |
4332 | void ActOnDefaultCtorInitializers(Decl *CDtorDecl); |
4333 | bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, |
4334 | FunctionDecl *FDecl, |
4335 | const FunctionProtoType *Proto, |
4336 | ArrayRef<Expr *> Args, |
4337 | SourceLocation RParenLoc, |
4338 | bool ExecConfig = false); |
4339 | void CheckStaticArrayArgument(SourceLocation CallLoc, |
4340 | ParmVarDecl *Param, |
4341 | const Expr *ArgExpr); |
4342 | |
4343 | /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. |
4344 | /// This provides the location of the left/right parens and a list of comma |
4345 | /// locations. |
4346 | ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, |
4347 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
4348 | Expr *ExecConfig = nullptr, |
4349 | bool IsExecConfig = false); |
4350 | ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, |
4351 | SourceLocation LParenLoc, |
4352 | ArrayRef<Expr *> Arg, |
4353 | SourceLocation RParenLoc, |
4354 | Expr *Config = nullptr, |
4355 | bool IsExecConfig = false); |
4356 | |
4357 | ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, |
4358 | MultiExprArg ExecConfig, |
4359 | SourceLocation GGGLoc); |
4360 | |
4361 | ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, |
4362 | Declarator &D, ParsedType &Ty, |
4363 | SourceLocation RParenLoc, Expr *CastExpr); |
4364 | ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, |
4365 | TypeSourceInfo *Ty, |
4366 | SourceLocation RParenLoc, |
4367 | Expr *Op); |
4368 | CastKind PrepareScalarCast(ExprResult &src, QualType destType); |
4369 | |
4370 | /// \brief Build an altivec or OpenCL literal. |
4371 | ExprResult BuildVectorLiteral(SourceLocation LParenLoc, |
4372 | SourceLocation RParenLoc, Expr *E, |
4373 | TypeSourceInfo *TInfo); |
4374 | |
4375 | ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); |
4376 | |
4377 | ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, |
4378 | ParsedType Ty, |
4379 | SourceLocation RParenLoc, |
4380 | Expr *InitExpr); |
4381 | |
4382 | ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, |
4383 | TypeSourceInfo *TInfo, |
4384 | SourceLocation RParenLoc, |
4385 | Expr *LiteralExpr); |
4386 | |
4387 | ExprResult ActOnInitList(SourceLocation LBraceLoc, |
4388 | MultiExprArg InitArgList, |
4389 | SourceLocation RBraceLoc); |
4390 | |
4391 | ExprResult ActOnDesignatedInitializer(Designation &Desig, |
4392 | SourceLocation Loc, |
4393 | bool GNUSyntax, |
4394 | ExprResult Init); |
4395 | |
4396 | private: |
4397 | static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); |
4398 | |
4399 | public: |
4400 | ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, |
4401 | tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); |
4402 | ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, |
4403 | BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); |
4404 | ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, |
4405 | Expr *LHSExpr, Expr *RHSExpr); |
4406 | |
4407 | void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); |
4408 | |
4409 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null |
4410 | /// in the case of a the GNU conditional expr extension. |
4411 | ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, |
4412 | SourceLocation ColonLoc, |
4413 | Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); |
4414 | |
4415 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". |
4416 | ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, |
4417 | LabelDecl *TheDecl); |
4418 | |
4419 | void ActOnStartStmtExpr(); |
4420 | ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, |
4421 | SourceLocation RPLoc); // "({..})" |
4422 | void ActOnStmtExprError(); |
4423 | |
4424 | // __builtin_offsetof(type, identifier(.identifier|[expr])*) |
4425 | struct OffsetOfComponent { |
4426 | SourceLocation LocStart, LocEnd; |
4427 | bool isBrackets; // true if [expr], false if .ident |
4428 | union { |
4429 | IdentifierInfo *IdentInfo; |
4430 | Expr *E; |
4431 | } U; |
4432 | }; |
4433 | |
4434 | /// __builtin_offsetof(type, a.b[123][456].c) |
4435 | ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, |
4436 | TypeSourceInfo *TInfo, |
4437 | ArrayRef<OffsetOfComponent> Components, |
4438 | SourceLocation RParenLoc); |
4439 | ExprResult ActOnBuiltinOffsetOf(Scope *S, |
4440 | SourceLocation BuiltinLoc, |
4441 | SourceLocation TypeLoc, |
4442 | ParsedType ParsedArgTy, |
4443 | ArrayRef<OffsetOfComponent> Components, |
4444 | SourceLocation RParenLoc); |
4445 | |
4446 | // __builtin_choose_expr(constExpr, expr1, expr2) |
4447 | ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, |
4448 | Expr *CondExpr, Expr *LHSExpr, |
4449 | Expr *RHSExpr, SourceLocation RPLoc); |
4450 | |
4451 | // __builtin_va_arg(expr, type) |
4452 | ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, |
4453 | SourceLocation RPLoc); |
4454 | ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, |
4455 | TypeSourceInfo *TInfo, SourceLocation RPLoc); |
4456 | |
4457 | // __null |
4458 | ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); |
4459 | |
4460 | bool CheckCaseExpression(Expr *E); |
4461 | |
4462 | /// \brief Describes the result of an "if-exists" condition check. |
4463 | enum IfExistsResult { |
4464 | /// \brief The symbol exists. |
4465 | IER_Exists, |
4466 | |
4467 | /// \brief The symbol does not exist. |
4468 | IER_DoesNotExist, |
4469 | |
4470 | /// \brief The name is a dependent name, so the results will differ |
4471 | /// from one instantiation to the next. |
4472 | IER_Dependent, |
4473 | |
4474 | /// \brief An error occurred. |
4475 | IER_Error |
4476 | }; |
4477 | |
4478 | IfExistsResult |
4479 | CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, |
4480 | const DeclarationNameInfo &TargetNameInfo); |
4481 | |
4482 | IfExistsResult |
4483 | CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, |
4484 | bool IsIfExists, CXXScopeSpec &SS, |
4485 | UnqualifiedId &Name); |
4486 | |
4487 | StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, |
4488 | bool IsIfExists, |
4489 | NestedNameSpecifierLoc QualifierLoc, |
4490 | DeclarationNameInfo NameInfo, |
4491 | Stmt *Nested); |
4492 | StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, |
4493 | bool IsIfExists, |
4494 | CXXScopeSpec &SS, UnqualifiedId &Name, |
4495 | Stmt *Nested); |
4496 | |
4497 | //===------------------------- "Block" Extension ------------------------===// |
4498 | |
4499 | /// ActOnBlockStart - This callback is invoked when a block literal is |
4500 | /// started. |
4501 | void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); |
4502 | |
4503 | /// ActOnBlockArguments - This callback allows processing of block arguments. |
4504 | /// If there are no arguments, this is still invoked. |
4505 | void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, |
4506 | Scope *CurScope); |
4507 | |
4508 | /// ActOnBlockError - If there is an error parsing a block, this callback |
4509 | /// is invoked to pop the information about the block from the action impl. |
4510 | void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); |
4511 | |
4512 | /// ActOnBlockStmtExpr - This is called when the body of a block statement |
4513 | /// literal was successfully completed. ^(int x){...} |
4514 | ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, |
4515 | Scope *CurScope); |
4516 | |
4517 | //===---------------------------- Clang Extensions ----------------------===// |
4518 | |
4519 | /// __builtin_convertvector(...) |
4520 | ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, |
4521 | SourceLocation BuiltinLoc, |
4522 | SourceLocation RParenLoc); |
4523 | |
4524 | //===---------------------------- OpenCL Features -----------------------===// |
4525 | |
4526 | /// __builtin_astype(...) |
4527 | ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, |
4528 | SourceLocation BuiltinLoc, |
4529 | SourceLocation RParenLoc); |
4530 | |
4531 | //===---------------------------- C++ Features --------------------------===// |
4532 | |
4533 | // Act on C++ namespaces |
4534 | Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, |
4535 | SourceLocation NamespaceLoc, |
4536 | SourceLocation IdentLoc, |
4537 | IdentifierInfo *Ident, |
4538 | SourceLocation LBrace, |
4539 | AttributeList *AttrList, |
4540 | UsingDirectiveDecl * &UsingDecl); |
4541 | void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); |
4542 | |
4543 | NamespaceDecl *getStdNamespace() const; |
4544 | NamespaceDecl *getOrCreateStdNamespace(); |
4545 | |
4546 | NamespaceDecl *lookupStdExperimentalNamespace(); |
4547 | |
4548 | CXXRecordDecl *getStdBadAlloc() const; |
4549 | EnumDecl *getStdAlignValT() const; |
4550 | |
4551 | /// \brief Tests whether Ty is an instance of std::initializer_list and, if |
4552 | /// it is and Element is not NULL, assigns the element type to Element. |
4553 | bool isStdInitializerList(QualType Ty, QualType *Element); |
4554 | |
4555 | /// \brief Looks for the std::initializer_list template and instantiates it |
4556 | /// with Element, or emits an error if it's not found. |
4557 | /// |
4558 | /// \returns The instantiated template, or null on error. |
4559 | QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); |
4560 | |
4561 | /// \brief Determine whether Ctor is an initializer-list constructor, as |
4562 | /// defined in [dcl.init.list]p2. |
4563 | bool isInitListConstructor(const FunctionDecl *Ctor); |
4564 | |
4565 | Decl *ActOnUsingDirective(Scope *CurScope, |
4566 | SourceLocation UsingLoc, |
4567 | SourceLocation NamespcLoc, |
4568 | CXXScopeSpec &SS, |
4569 | SourceLocation IdentLoc, |
4570 | IdentifierInfo *NamespcName, |
4571 | AttributeList *AttrList); |
4572 | |
4573 | void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); |
4574 | |
4575 | Decl *ActOnNamespaceAliasDef(Scope *CurScope, |
4576 | SourceLocation NamespaceLoc, |
4577 | SourceLocation AliasLoc, |
4578 | IdentifierInfo *Alias, |
4579 | CXXScopeSpec &SS, |
4580 | SourceLocation IdentLoc, |
4581 | IdentifierInfo *Ident); |
4582 | |
4583 | void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); |
4584 | bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, |
4585 | const LookupResult &PreviousDecls, |
4586 | UsingShadowDecl *&PrevShadow); |
4587 | UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, |
4588 | NamedDecl *Target, |
4589 | UsingShadowDecl *PrevDecl); |
4590 | |
4591 | bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, |
4592 | bool HasTypenameKeyword, |
4593 | const CXXScopeSpec &SS, |
4594 | SourceLocation NameLoc, |
4595 | const LookupResult &Previous); |
4596 | bool CheckUsingDeclQualifier(SourceLocation UsingLoc, |
4597 | bool HasTypename, |
4598 | const CXXScopeSpec &SS, |
4599 | const DeclarationNameInfo &NameInfo, |
4600 | SourceLocation NameLoc); |
4601 | |
4602 | NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, |
4603 | SourceLocation UsingLoc, |
4604 | bool HasTypenameKeyword, |
4605 | SourceLocation TypenameLoc, |
4606 | CXXScopeSpec &SS, |
4607 | DeclarationNameInfo NameInfo, |
4608 | SourceLocation EllipsisLoc, |
4609 | AttributeList *AttrList, |
4610 | bool IsInstantiation); |
4611 | NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, |
4612 | ArrayRef<NamedDecl *> Expansions); |
4613 | |
4614 | bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); |
4615 | |
4616 | /// Given a derived-class using shadow declaration for a constructor and the |
4617 | /// correspnding base class constructor, find or create the implicit |
4618 | /// synthesized derived class constructor to use for this initialization. |
4619 | CXXConstructorDecl * |
4620 | findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, |
4621 | ConstructorUsingShadowDecl *DerivedShadow); |
4622 | |
4623 | Decl *ActOnUsingDeclaration(Scope *CurScope, |
4624 | AccessSpecifier AS, |
4625 | SourceLocation UsingLoc, |
4626 | SourceLocation TypenameLoc, |
4627 | CXXScopeSpec &SS, |
4628 | UnqualifiedId &Name, |
4629 | SourceLocation EllipsisLoc, |
4630 | AttributeList *AttrList); |
4631 | Decl *ActOnAliasDeclaration(Scope *CurScope, |
4632 | AccessSpecifier AS, |
4633 | MultiTemplateParamsArg TemplateParams, |
4634 | SourceLocation UsingLoc, |
4635 | UnqualifiedId &Name, |
4636 | AttributeList *AttrList, |
4637 | TypeResult Type, |
4638 | Decl *DeclFromDeclSpec); |
4639 | |
4640 | /// BuildCXXConstructExpr - Creates a complete call to a constructor, |
4641 | /// including handling of its default argument expressions. |
4642 | /// |
4643 | /// \param ConstructKind - a CXXConstructExpr::ConstructionKind |
4644 | ExprResult |
4645 | BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, |
4646 | NamedDecl *FoundDecl, |
4647 | CXXConstructorDecl *Constructor, MultiExprArg Exprs, |
4648 | bool HadMultipleCandidates, bool IsListInitialization, |
4649 | bool IsStdInitListInitialization, |
4650 | bool RequiresZeroInit, unsigned ConstructKind, |
4651 | SourceRange ParenRange); |
4652 | |
4653 | /// Build a CXXConstructExpr whose constructor has already been resolved if |
4654 | /// it denotes an inherited constructor. |
4655 | ExprResult |
4656 | BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, |
4657 | CXXConstructorDecl *Constructor, bool Elidable, |
4658 | MultiExprArg Exprs, |
4659 | bool HadMultipleCandidates, bool IsListInitialization, |
4660 | bool IsStdInitListInitialization, |
4661 | bool RequiresZeroInit, unsigned ConstructKind, |
4662 | SourceRange ParenRange); |
4663 | |
4664 | // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if |
4665 | // the constructor can be elidable? |
4666 | ExprResult |
4667 | BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, |
4668 | NamedDecl *FoundDecl, |
4669 | CXXConstructorDecl *Constructor, bool Elidable, |
4670 | MultiExprArg Exprs, bool HadMultipleCandidates, |
4671 | bool IsListInitialization, |
4672 | bool IsStdInitListInitialization, bool RequiresZeroInit, |
4673 | unsigned ConstructKind, SourceRange ParenRange); |
4674 | |
4675 | ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); |
4676 | |
4677 | |
4678 | /// Instantiate or parse a C++ default argument expression as necessary. |
4679 | /// Return true on error. |
4680 | bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, |
4681 | ParmVarDecl *Param); |
4682 | |
4683 | /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating |
4684 | /// the default expr if needed. |
4685 | ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, |
4686 | FunctionDecl *FD, |
4687 | ParmVarDecl *Param); |
4688 | |
4689 | /// FinalizeVarWithDestructor - Prepare for calling destructor on the |
4690 | /// constructed variable. |
4691 | void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); |
4692 | |
4693 | /// \brief Helper class that collects exception specifications for |
4694 | /// implicitly-declared special member functions. |
4695 | class ImplicitExceptionSpecification { |
4696 | // Pointer to allow copying |
4697 | Sema *Self; |
4698 | // We order exception specifications thus: |
4699 | // noexcept is the most restrictive, but is only used in C++11. |
4700 | // throw() comes next. |
4701 | // Then a throw(collected exceptions) |
4702 | // Finally no specification, which is expressed as noexcept(false). |
4703 | // throw(...) is used instead if any called function uses it. |
4704 | ExceptionSpecificationType ComputedEST; |
4705 | llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; |
4706 | SmallVector<QualType, 4> Exceptions; |
4707 | |
4708 | void ClearExceptions() { |
4709 | ExceptionsSeen.clear(); |
4710 | Exceptions.clear(); |
4711 | } |
4712 | |
4713 | public: |
4714 | explicit ImplicitExceptionSpecification(Sema &Self) |
4715 | : Self(&Self), ComputedEST(EST_BasicNoexcept) { |
4716 | if (!Self.getLangOpts().CPlusPlus11) |
4717 | ComputedEST = EST_DynamicNone; |
4718 | } |
4719 | |
4720 | /// \brief Get the computed exception specification type. |
4721 | ExceptionSpecificationType getExceptionSpecType() const { |
4722 | assert(ComputedEST != EST_ComputedNoexcept &&(static_cast <bool> (ComputedEST != EST_ComputedNoexcept && "noexcept(expr) should not be a possible result") ? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 4723, __extension__ __PRETTY_FUNCTION__)) |
4723 | "noexcept(expr) should not be a possible result")(static_cast <bool> (ComputedEST != EST_ComputedNoexcept && "noexcept(expr) should not be a possible result") ? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 4723, __extension__ __PRETTY_FUNCTION__)); |
4724 | return ComputedEST; |
4725 | } |
4726 | |
4727 | /// \brief The number of exceptions in the exception specification. |
4728 | unsigned size() const { return Exceptions.size(); } |
4729 | |
4730 | /// \brief The set of exceptions in the exception specification. |
4731 | const QualType *data() const { return Exceptions.data(); } |
4732 | |
4733 | /// \brief Integrate another called method into the collected data. |
4734 | void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); |
4735 | |
4736 | /// \brief Integrate an invoked expression into the collected data. |
4737 | void CalledExpr(Expr *E); |
4738 | |
4739 | /// \brief Overwrite an EPI's exception specification with this |
4740 | /// computed exception specification. |
4741 | FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { |
4742 | FunctionProtoType::ExceptionSpecInfo ESI; |
4743 | ESI.Type = getExceptionSpecType(); |
4744 | if (ESI.Type == EST_Dynamic) { |
4745 | ESI.Exceptions = Exceptions; |
4746 | } else if (ESI.Type == EST_None) { |
4747 | /// C++11 [except.spec]p14: |
4748 | /// The exception-specification is noexcept(false) if the set of |
4749 | /// potential exceptions of the special member function contains "any" |
4750 | ESI.Type = EST_ComputedNoexcept; |
4751 | ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), |
4752 | tok::kw_false).get(); |
4753 | } |
4754 | return ESI; |
4755 | } |
4756 | }; |
4757 | |
4758 | /// \brief Determine what sort of exception specification a defaulted |
4759 | /// copy constructor of a class will have. |
4760 | ImplicitExceptionSpecification |
4761 | ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, |
4762 | CXXMethodDecl *MD); |
4763 | |
4764 | /// \brief Determine what sort of exception specification a defaulted |
4765 | /// default constructor of a class will have, and whether the parameter |
4766 | /// will be const. |
4767 | ImplicitExceptionSpecification |
4768 | ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); |
4769 | |
4770 | /// \brief Determine what sort of exception specification a defautled |
4771 | /// copy assignment operator of a class will have, and whether the |
4772 | /// parameter will be const. |
4773 | ImplicitExceptionSpecification |
4774 | ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); |
4775 | |
4776 | /// \brief Determine what sort of exception specification a defaulted move |
4777 | /// constructor of a class will have. |
4778 | ImplicitExceptionSpecification |
4779 | ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); |
4780 | |
4781 | /// \brief Determine what sort of exception specification a defaulted move |
4782 | /// assignment operator of a class will have. |
4783 | ImplicitExceptionSpecification |
4784 | ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); |
4785 | |
4786 | /// \brief Determine what sort of exception specification a defaulted |
4787 | /// destructor of a class will have. |
4788 | ImplicitExceptionSpecification |
4789 | ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); |
4790 | |
4791 | /// \brief Determine what sort of exception specification an inheriting |
4792 | /// constructor of a class will have. |
4793 | ImplicitExceptionSpecification |
4794 | ComputeInheritingCtorExceptionSpec(SourceLocation Loc, |
4795 | CXXConstructorDecl *CD); |
4796 | |
4797 | /// \brief Evaluate the implicit exception specification for a defaulted |
4798 | /// special member function. |
4799 | void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); |
4800 | |
4801 | /// \brief Check the given exception-specification and update the |
4802 | /// exception specification information with the results. |
4803 | void checkExceptionSpecification(bool IsTopLevel, |
4804 | ExceptionSpecificationType EST, |
4805 | ArrayRef<ParsedType> DynamicExceptions, |
4806 | ArrayRef<SourceRange> DynamicExceptionRanges, |
4807 | Expr *NoexceptExpr, |
4808 | SmallVectorImpl<QualType> &Exceptions, |
4809 | FunctionProtoType::ExceptionSpecInfo &ESI); |
4810 | |
4811 | /// \brief Determine if we're in a case where we need to (incorrectly) eagerly |
4812 | /// parse an exception specification to work around a libstdc++ bug. |
4813 | bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); |
4814 | |
4815 | /// \brief Add an exception-specification to the given member function |
4816 | /// (or member function template). The exception-specification was parsed |
4817 | /// after the method itself was declared. |
4818 | void actOnDelayedExceptionSpecification(Decl *Method, |
4819 | ExceptionSpecificationType EST, |
4820 | SourceRange SpecificationRange, |
4821 | ArrayRef<ParsedType> DynamicExceptions, |
4822 | ArrayRef<SourceRange> DynamicExceptionRanges, |
4823 | Expr *NoexceptExpr); |
4824 | |
4825 | class InheritedConstructorInfo; |
4826 | |
4827 | /// \brief Determine if a special member function should have a deleted |
4828 | /// definition when it is defaulted. |
4829 | bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, |
4830 | InheritedConstructorInfo *ICI = nullptr, |
4831 | bool Diagnose = false); |
4832 | |
4833 | /// \brief Declare the implicit default constructor for the given class. |
4834 | /// |
4835 | /// \param ClassDecl The class declaration into which the implicit |
4836 | /// default constructor will be added. |
4837 | /// |
4838 | /// \returns The implicitly-declared default constructor. |
4839 | CXXConstructorDecl *DeclareImplicitDefaultConstructor( |
4840 | CXXRecordDecl *ClassDecl); |
4841 | |
4842 | /// DefineImplicitDefaultConstructor - Checks for feasibility of |
4843 | /// defining this constructor as the default constructor. |
4844 | void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, |
4845 | CXXConstructorDecl *Constructor); |
4846 | |
4847 | /// \brief Declare the implicit destructor for the given class. |
4848 | /// |
4849 | /// \param ClassDecl The class declaration into which the implicit |
4850 | /// destructor will be added. |
4851 | /// |
4852 | /// \returns The implicitly-declared destructor. |
4853 | CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); |
4854 | |
4855 | /// DefineImplicitDestructor - Checks for feasibility of |
4856 | /// defining this destructor as the default destructor. |
4857 | void DefineImplicitDestructor(SourceLocation CurrentLocation, |
4858 | CXXDestructorDecl *Destructor); |
4859 | |
4860 | /// \brief Build an exception spec for destructors that don't have one. |
4861 | /// |
4862 | /// C++11 says that user-defined destructors with no exception spec get one |
4863 | /// that looks as if the destructor was implicitly declared. |
4864 | void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, |
4865 | CXXDestructorDecl *Destructor); |
4866 | |
4867 | /// \brief Define the specified inheriting constructor. |
4868 | void DefineInheritingConstructor(SourceLocation UseLoc, |
4869 | CXXConstructorDecl *Constructor); |
4870 | |
4871 | /// \brief Declare the implicit copy constructor for the given class. |
4872 | /// |
4873 | /// \param ClassDecl The class declaration into which the implicit |
4874 | /// copy constructor will be added. |
4875 | /// |
4876 | /// \returns The implicitly-declared copy constructor. |
4877 | CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); |
4878 | |
4879 | /// DefineImplicitCopyConstructor - Checks for feasibility of |
4880 | /// defining this constructor as the copy constructor. |
4881 | void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, |
4882 | CXXConstructorDecl *Constructor); |
4883 | |
4884 | /// \brief Declare the implicit move constructor for the given class. |
4885 | /// |
4886 | /// \param ClassDecl The Class declaration into which the implicit |
4887 | /// move constructor will be added. |
4888 | /// |
4889 | /// \returns The implicitly-declared move constructor, or NULL if it wasn't |
4890 | /// declared. |
4891 | CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); |
4892 | |
4893 | /// DefineImplicitMoveConstructor - Checks for feasibility of |
4894 | /// defining this constructor as the move constructor. |
4895 | void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, |
4896 | CXXConstructorDecl *Constructor); |
4897 | |
4898 | /// \brief Declare the implicit copy assignment operator for the given class. |
4899 | /// |
4900 | /// \param ClassDecl The class declaration into which the implicit |
4901 | /// copy assignment operator will be added. |
4902 | /// |
4903 | /// \returns The implicitly-declared copy assignment operator. |
4904 | CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); |
4905 | |
4906 | /// \brief Defines an implicitly-declared copy assignment operator. |
4907 | void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, |
4908 | CXXMethodDecl *MethodDecl); |
4909 | |
4910 | /// \brief Declare the implicit move assignment operator for the given class. |
4911 | /// |
4912 | /// \param ClassDecl The Class declaration into which the implicit |
4913 | /// move assignment operator will be added. |
4914 | /// |
4915 | /// \returns The implicitly-declared move assignment operator, or NULL if it |
4916 | /// wasn't declared. |
4917 | CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); |
4918 | |
4919 | /// \brief Defines an implicitly-declared move assignment operator. |
4920 | void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, |
4921 | CXXMethodDecl *MethodDecl); |
4922 | |
4923 | /// \brief Force the declaration of any implicitly-declared members of this |
4924 | /// class. |
4925 | void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); |
4926 | |
4927 | /// \brief Check a completed declaration of an implicit special member. |
4928 | void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); |
4929 | |
4930 | /// \brief Determine whether the given function is an implicitly-deleted |
4931 | /// special member function. |
4932 | bool isImplicitlyDeleted(FunctionDecl *FD); |
4933 | |
4934 | /// \brief Check whether 'this' shows up in the type of a static member |
4935 | /// function after the (naturally empty) cv-qualifier-seq would be. |
4936 | /// |
4937 | /// \returns true if an error occurred. |
4938 | bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); |
4939 | |
4940 | /// \brief Whether this' shows up in the exception specification of a static |
4941 | /// member function. |
4942 | bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); |
4943 | |
4944 | /// \brief Check whether 'this' shows up in the attributes of the given |
4945 | /// static member function. |
4946 | /// |
4947 | /// \returns true if an error occurred. |
4948 | bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); |
4949 | |
4950 | /// MaybeBindToTemporary - If the passed in expression has a record type with |
4951 | /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise |
4952 | /// it simply returns the passed in expression. |
4953 | ExprResult MaybeBindToTemporary(Expr *E); |
4954 | |
4955 | bool CompleteConstructorCall(CXXConstructorDecl *Constructor, |
4956 | MultiExprArg ArgsPtr, |
4957 | SourceLocation Loc, |
4958 | SmallVectorImpl<Expr*> &ConvertedArgs, |
4959 | bool AllowExplicit = false, |
4960 | bool IsListInitialization = false); |
4961 | |
4962 | ParsedType getInheritingConstructorName(CXXScopeSpec &SS, |
4963 | SourceLocation NameLoc, |
4964 | IdentifierInfo &Name); |
4965 | |
4966 | ParsedType getDestructorName(SourceLocation TildeLoc, |
4967 | IdentifierInfo &II, SourceLocation NameLoc, |
4968 | Scope *S, CXXScopeSpec &SS, |
4969 | ParsedType ObjectType, |
4970 | bool EnteringContext); |
4971 | |
4972 | ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, |
4973 | ParsedType ObjectType); |
4974 | |
4975 | // Checks that reinterpret casts don't have undefined behavior. |
4976 | void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, |
4977 | bool IsDereference, SourceRange Range); |
4978 | |
4979 | /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. |
4980 | ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, |
4981 | tok::TokenKind Kind, |
4982 | SourceLocation LAngleBracketLoc, |
4983 | Declarator &D, |
4984 | SourceLocation RAngleBracketLoc, |
4985 | SourceLocation LParenLoc, |
4986 | Expr *E, |
4987 | SourceLocation RParenLoc); |
4988 | |
4989 | ExprResult BuildCXXNamedCast(SourceLocation OpLoc, |
4990 | tok::TokenKind Kind, |
4991 | TypeSourceInfo *Ty, |
4992 | Expr *E, |
4993 | SourceRange AngleBrackets, |
4994 | SourceRange Parens); |
4995 | |
4996 | ExprResult BuildCXXTypeId(QualType TypeInfoType, |
4997 | SourceLocation TypeidLoc, |
4998 | TypeSourceInfo *Operand, |
4999 | SourceLocation RParenLoc); |
5000 | ExprResult BuildCXXTypeId(QualType TypeInfoType, |
5001 | SourceLocation TypeidLoc, |
5002 | Expr *Operand, |
5003 | SourceLocation RParenLoc); |
5004 | |
5005 | /// ActOnCXXTypeid - Parse typeid( something ). |
5006 | ExprResult ActOnCXXTypeid(SourceLocation OpLoc, |
5007 | SourceLocation LParenLoc, bool isType, |
5008 | void *TyOrExpr, |
5009 | SourceLocation RParenLoc); |
5010 | |
5011 | ExprResult BuildCXXUuidof(QualType TypeInfoType, |
5012 | SourceLocation TypeidLoc, |
5013 | TypeSourceInfo *Operand, |
5014 | SourceLocation RParenLoc); |
5015 | ExprResult BuildCXXUuidof(QualType TypeInfoType, |
5016 | SourceLocation TypeidLoc, |
5017 | Expr *Operand, |
5018 | SourceLocation RParenLoc); |
5019 | |
5020 | /// ActOnCXXUuidof - Parse __uuidof( something ). |
5021 | ExprResult ActOnCXXUuidof(SourceLocation OpLoc, |
5022 | SourceLocation LParenLoc, bool isType, |
5023 | void *TyOrExpr, |
5024 | SourceLocation RParenLoc); |
5025 | |
5026 | /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ). |
5027 | ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, |
5028 | tok::TokenKind Operator, |
5029 | SourceLocation EllipsisLoc, Expr *RHS, |
5030 | SourceLocation RParenLoc); |
5031 | ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, |
5032 | BinaryOperatorKind Operator, |
5033 | SourceLocation EllipsisLoc, Expr *RHS, |
5034 | SourceLocation RParenLoc); |
5035 | ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, |
5036 | BinaryOperatorKind Operator); |
5037 | |
5038 | //// ActOnCXXThis - Parse 'this' pointer. |
5039 | ExprResult ActOnCXXThis(SourceLocation loc); |
5040 | |
5041 | /// \brief Try to retrieve the type of the 'this' pointer. |
5042 | /// |
5043 | /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. |
5044 | QualType getCurrentThisType(); |
5045 | |
5046 | /// \brief When non-NULL, the C++ 'this' expression is allowed despite the |
5047 | /// current context not being a non-static member function. In such cases, |
5048 | /// this provides the type used for 'this'. |
5049 | QualType CXXThisTypeOverride; |
5050 | |
5051 | /// \brief RAII object used to temporarily allow the C++ 'this' expression |
5052 | /// to be used, with the given qualifiers on the current class type. |
5053 | class CXXThisScopeRAII { |
5054 | Sema &S; |
5055 | QualType OldCXXThisTypeOverride; |
5056 | bool Enabled; |
5057 | |
5058 | public: |
5059 | /// \brief Introduce a new scope where 'this' may be allowed (when enabled), |
5060 | /// using the given declaration (which is either a class template or a |
5061 | /// class) along with the given qualifiers. |
5062 | /// along with the qualifiers placed on '*this'. |
5063 | CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals, |
5064 | bool Enabled = true); |
5065 | |
5066 | ~CXXThisScopeRAII(); |
5067 | }; |
5068 | |
5069 | /// \brief Make sure the value of 'this' is actually available in the current |
5070 | /// context, if it is a potentially evaluated context. |
5071 | /// |
5072 | /// \param Loc The location at which the capture of 'this' occurs. |
5073 | /// |
5074 | /// \param Explicit Whether 'this' is explicitly captured in a lambda |
5075 | /// capture list. |
5076 | /// |
5077 | /// \param FunctionScopeIndexToStopAt If non-null, it points to the index |
5078 | /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. |
5079 | /// This is useful when enclosing lambdas must speculatively capture |
5080 | /// 'this' that may or may not be used in certain specializations of |
5081 | /// a nested generic lambda (depending on whether the name resolves to |
5082 | /// a non-static member function or a static function). |
5083 | /// \return returns 'true' if failed, 'false' if success. |
5084 | bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, |
5085 | bool BuildAndDiagnose = true, |
5086 | const unsigned *const FunctionScopeIndexToStopAt = nullptr, |
5087 | bool ByCopy = false); |
5088 | |
5089 | /// \brief Determine whether the given type is the type of *this that is used |
5090 | /// outside of the body of a member function for a type that is currently |
5091 | /// being defined. |
5092 | bool isThisOutsideMemberFunctionBody(QualType BaseType); |
5093 | |
5094 | /// ActOnCXXBoolLiteral - Parse {true,false} literals. |
5095 | ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); |
5096 | |
5097 | |
5098 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. |
5099 | ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); |
5100 | |
5101 | ExprResult |
5102 | ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, |
5103 | SourceLocation AtLoc, SourceLocation RParen); |
5104 | |
5105 | /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. |
5106 | ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); |
5107 | |
5108 | //// ActOnCXXThrow - Parse throw expressions. |
5109 | ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); |
5110 | ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, |
5111 | bool IsThrownVarInScope); |
5112 | bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); |
5113 | |
5114 | /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. |
5115 | /// Can be interpreted either as function-style casting ("int(x)") |
5116 | /// or class type construction ("ClassType(x,y,z)") |
5117 | /// or creation of a value-initialized type ("int()"). |
5118 | ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, |
5119 | SourceLocation LParenOrBraceLoc, |
5120 | MultiExprArg Exprs, |
5121 | SourceLocation RParenOrBraceLoc, |
5122 | bool ListInitialization); |
5123 | |
5124 | ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, |
5125 | SourceLocation LParenLoc, |
5126 | MultiExprArg Exprs, |
5127 | SourceLocation RParenLoc, |
5128 | bool ListInitialization); |
5129 | |
5130 | /// ActOnCXXNew - Parsed a C++ 'new' expression. |
5131 | ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, |
5132 | SourceLocation PlacementLParen, |
5133 | MultiExprArg PlacementArgs, |
5134 | SourceLocation PlacementRParen, |
5135 | SourceRange TypeIdParens, Declarator &D, |
5136 | Expr *Initializer); |
5137 | ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, |
5138 | SourceLocation PlacementLParen, |
5139 | MultiExprArg PlacementArgs, |
5140 | SourceLocation PlacementRParen, |
5141 | SourceRange TypeIdParens, |
5142 | QualType AllocType, |
5143 | TypeSourceInfo *AllocTypeInfo, |
5144 | Expr *ArraySize, |
5145 | SourceRange DirectInitRange, |
5146 | Expr *Initializer); |
5147 | |
5148 | bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, |
5149 | SourceRange R); |
5150 | bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, |
5151 | bool UseGlobal, QualType AllocType, bool IsArray, |
5152 | bool &PassAlignment, MultiExprArg PlaceArgs, |
5153 | FunctionDecl *&OperatorNew, |
5154 | FunctionDecl *&OperatorDelete, |
5155 | bool Diagnose = true); |
5156 | void DeclareGlobalNewDelete(); |
5157 | void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, |
5158 | ArrayRef<QualType> Params); |
5159 | |
5160 | bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, |
5161 | DeclarationName Name, FunctionDecl* &Operator, |
5162 | bool Diagnose = true); |
5163 | FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, |
5164 | bool CanProvideSize, |
5165 | bool Overaligned, |
5166 | DeclarationName Name); |
5167 | FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, |
5168 | CXXRecordDecl *RD); |
5169 | |
5170 | /// ActOnCXXDelete - Parsed a C++ 'delete' expression |
5171 | ExprResult ActOnCXXDelete(SourceLocation StartLoc, |
5172 | bool UseGlobal, bool ArrayForm, |
5173 | Expr *Operand); |
5174 | void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, |
5175 | bool IsDelete, bool CallCanBeVirtual, |
5176 | bool WarnOnNonAbstractTypes, |
5177 | SourceLocation DtorLoc); |
5178 | |
5179 | ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, |
5180 | Expr *Operand, SourceLocation RParen); |
5181 | ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, |
5182 | SourceLocation RParen); |
5183 | |
5184 | /// \brief Parsed one of the type trait support pseudo-functions. |
5185 | ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, |
5186 | ArrayRef<ParsedType> Args, |
5187 | SourceLocation RParenLoc); |
5188 | ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, |
5189 | ArrayRef<TypeSourceInfo *> Args, |
5190 | SourceLocation RParenLoc); |
5191 | |
5192 | /// ActOnArrayTypeTrait - Parsed one of the binary type trait support |
5193 | /// pseudo-functions. |
5194 | ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, |
5195 | SourceLocation KWLoc, |
5196 | ParsedType LhsTy, |
5197 | Expr *DimExpr, |
5198 | SourceLocation RParen); |
5199 | |
5200 | ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, |
5201 | SourceLocation KWLoc, |
5202 | TypeSourceInfo *TSInfo, |
5203 | Expr *DimExpr, |
5204 | SourceLocation RParen); |
5205 | |
5206 | /// ActOnExpressionTrait - Parsed one of the unary type trait support |
5207 | /// pseudo-functions. |
5208 | ExprResult ActOnExpressionTrait(ExpressionTrait OET, |
5209 | SourceLocation KWLoc, |
5210 | Expr *Queried, |
5211 | SourceLocation RParen); |
5212 | |
5213 | ExprResult BuildExpressionTrait(ExpressionTrait OET, |
5214 | SourceLocation KWLoc, |
5215 | Expr *Queried, |
5216 | SourceLocation RParen); |
5217 | |
5218 | ExprResult ActOnStartCXXMemberReference(Scope *S, |
5219 | Expr *Base, |
5220 | SourceLocation OpLoc, |
5221 | tok::TokenKind OpKind, |
5222 | ParsedType &ObjectType, |
5223 | bool &MayBePseudoDestructor); |
5224 | |
5225 | ExprResult BuildPseudoDestructorExpr(Expr *Base, |
5226 | SourceLocation OpLoc, |
5227 | tok::TokenKind OpKind, |
5228 | const CXXScopeSpec &SS, |
5229 | TypeSourceInfo *ScopeType, |
5230 | SourceLocation CCLoc, |
5231 | SourceLocation TildeLoc, |
5232 | PseudoDestructorTypeStorage DestroyedType); |
5233 | |
5234 | ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
5235 | SourceLocation OpLoc, |
5236 | tok::TokenKind OpKind, |
5237 | CXXScopeSpec &SS, |
5238 | UnqualifiedId &FirstTypeName, |
5239 | SourceLocation CCLoc, |
5240 | SourceLocation TildeLoc, |
5241 | UnqualifiedId &SecondTypeName); |
5242 | |
5243 | ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
5244 | SourceLocation OpLoc, |
5245 | tok::TokenKind OpKind, |
5246 | SourceLocation TildeLoc, |
5247 | const DeclSpec& DS); |
5248 | |
5249 | /// MaybeCreateExprWithCleanups - If the current full-expression |
5250 | /// requires any cleanups, surround it with a ExprWithCleanups node. |
5251 | /// Otherwise, just returns the passed-in expression. |
5252 | Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); |
5253 | Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); |
5254 | ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); |
5255 | |
5256 | MaterializeTemporaryExpr * |
5257 | CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, |
5258 | bool BoundToLvalueReference); |
5259 | |
5260 | ExprResult ActOnFinishFullExpr(Expr *Expr) { |
5261 | return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc() |
5262 | : SourceLocation()); |
5263 | } |
5264 | ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, |
5265 | bool DiscardedValue = false, |
5266 | bool IsConstexpr = false, |
5267 | bool IsLambdaInitCaptureInitializer = false); |
5268 | StmtResult ActOnFinishFullStmt(Stmt *Stmt); |
5269 | |
5270 | // Marks SS invalid if it represents an incomplete type. |
5271 | bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); |
5272 | |
5273 | DeclContext *computeDeclContext(QualType T); |
5274 | DeclContext *computeDeclContext(const CXXScopeSpec &SS, |
5275 | bool EnteringContext = false); |
5276 | bool isDependentScopeSpecifier(const CXXScopeSpec &SS); |
5277 | CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); |
5278 | |
5279 | /// \brief The parser has parsed a global nested-name-specifier '::'. |
5280 | /// |
5281 | /// \param CCLoc The location of the '::'. |
5282 | /// |
5283 | /// \param SS The nested-name-specifier, which will be updated in-place |
5284 | /// to reflect the parsed nested-name-specifier. |
5285 | /// |
5286 | /// \returns true if an error occurred, false otherwise. |
5287 | bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); |
5288 | |
5289 | /// \brief The parser has parsed a '__super' nested-name-specifier. |
5290 | /// |
5291 | /// \param SuperLoc The location of the '__super' keyword. |
5292 | /// |
5293 | /// \param ColonColonLoc The location of the '::'. |
5294 | /// |
5295 | /// \param SS The nested-name-specifier, which will be updated in-place |
5296 | /// to reflect the parsed nested-name-specifier. |
5297 | /// |
5298 | /// \returns true if an error occurred, false otherwise. |
5299 | bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, |
5300 | SourceLocation ColonColonLoc, CXXScopeSpec &SS); |
5301 | |
5302 | bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, |
5303 | bool *CanCorrect = nullptr); |
5304 | NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); |
5305 | |
5306 | /// \brief Keeps information about an identifier in a nested-name-spec. |
5307 | /// |
5308 | struct NestedNameSpecInfo { |
5309 | /// \brief The type of the object, if we're parsing nested-name-specifier in |
5310 | /// a member access expression. |
5311 | ParsedType ObjectType; |
5312 | |
5313 | /// \brief The identifier preceding the '::'. |
5314 | IdentifierInfo *Identifier; |
5315 | |
5316 | /// \brief The location of the identifier. |
5317 | SourceLocation IdentifierLoc; |
5318 | |
5319 | /// \brief The location of the '::'. |
5320 | SourceLocation CCLoc; |
5321 | |
5322 | /// \brief Creates info object for the most typical case. |
5323 | NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, |
5324 | SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) |
5325 | : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), |
5326 | CCLoc(ColonColonLoc) { |
5327 | } |
5328 | |
5329 | NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, |
5330 | SourceLocation ColonColonLoc, QualType ObjectType) |
5331 | : ObjectType(ParsedType::make(ObjectType)), Identifier(II), |
5332 | IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { |
5333 | } |
5334 | }; |
5335 | |
5336 | bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, |
5337 | NestedNameSpecInfo &IdInfo); |
5338 | |
5339 | bool BuildCXXNestedNameSpecifier(Scope *S, |
5340 | NestedNameSpecInfo &IdInfo, |
5341 | bool EnteringContext, |
5342 | CXXScopeSpec &SS, |
5343 | NamedDecl *ScopeLookupResult, |
5344 | bool ErrorRecoveryLookup, |
5345 | bool *IsCorrectedToColon = nullptr, |
5346 | bool OnlyNamespace = false); |
5347 | |
5348 | /// \brief The parser has parsed a nested-name-specifier 'identifier::'. |
5349 | /// |
5350 | /// \param S The scope in which this nested-name-specifier occurs. |
5351 | /// |
5352 | /// \param IdInfo Parser information about an identifier in the |
5353 | /// nested-name-spec. |
5354 | /// |
5355 | /// \param EnteringContext Whether we're entering the context nominated by |
5356 | /// this nested-name-specifier. |
5357 | /// |
5358 | /// \param SS The nested-name-specifier, which is both an input |
5359 | /// parameter (the nested-name-specifier before this type) and an |
5360 | /// output parameter (containing the full nested-name-specifier, |
5361 | /// including this new type). |
5362 | /// |
5363 | /// \param ErrorRecoveryLookup If true, then this method is called to improve |
5364 | /// error recovery. In this case do not emit error message. |
5365 | /// |
5366 | /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' |
5367 | /// are allowed. The bool value pointed by this parameter is set to 'true' |
5368 | /// if the identifier is treated as if it was followed by ':', not '::'. |
5369 | /// |
5370 | /// \param OnlyNamespace If true, only considers namespaces in lookup. |
5371 | /// |
5372 | /// \returns true if an error occurred, false otherwise. |
5373 | bool ActOnCXXNestedNameSpecifier(Scope *S, |
5374 | NestedNameSpecInfo &IdInfo, |
5375 | bool EnteringContext, |
5376 | CXXScopeSpec &SS, |
5377 | bool ErrorRecoveryLookup = false, |
5378 | bool *IsCorrectedToColon = nullptr, |
5379 | bool OnlyNamespace = false); |
5380 | |
5381 | ExprResult ActOnDecltypeExpression(Expr *E); |
5382 | |
5383 | bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, |
5384 | const DeclSpec &DS, |
5385 | SourceLocation ColonColonLoc); |
5386 | |
5387 | bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, |
5388 | NestedNameSpecInfo &IdInfo, |
5389 | bool EnteringContext); |
5390 | |
5391 | /// \brief The parser has parsed a nested-name-specifier |
5392 | /// 'template[opt] template-name < template-args >::'. |
5393 | /// |
5394 | /// \param S The scope in which this nested-name-specifier occurs. |
5395 | /// |
5396 | /// \param SS The nested-name-specifier, which is both an input |
5397 | /// parameter (the nested-name-specifier before this type) and an |
5398 | /// output parameter (containing the full nested-name-specifier, |
5399 | /// including this new type). |
5400 | /// |
5401 | /// \param TemplateKWLoc the location of the 'template' keyword, if any. |
5402 | /// \param TemplateName the template name. |
5403 | /// \param TemplateNameLoc The location of the template name. |
5404 | /// \param LAngleLoc The location of the opening angle bracket ('<'). |
5405 | /// \param TemplateArgs The template arguments. |
5406 | /// \param RAngleLoc The location of the closing angle bracket ('>'). |
5407 | /// \param CCLoc The location of the '::'. |
5408 | /// |
5409 | /// \param EnteringContext Whether we're entering the context of the |
5410 | /// nested-name-specifier. |
5411 | /// |
5412 | /// |
5413 | /// \returns true if an error occurred, false otherwise. |
5414 | bool ActOnCXXNestedNameSpecifier(Scope *S, |
5415 | CXXScopeSpec &SS, |
5416 | SourceLocation TemplateKWLoc, |
5417 | TemplateTy TemplateName, |
5418 | SourceLocation TemplateNameLoc, |
5419 | SourceLocation LAngleLoc, |
5420 | ASTTemplateArgsPtr TemplateArgs, |
5421 | SourceLocation RAngleLoc, |
5422 | SourceLocation CCLoc, |
5423 | bool EnteringContext); |
5424 | |
5425 | /// \brief Given a C++ nested-name-specifier, produce an annotation value |
5426 | /// that the parser can use later to reconstruct the given |
5427 | /// nested-name-specifier. |
5428 | /// |
5429 | /// \param SS A nested-name-specifier. |
5430 | /// |
5431 | /// \returns A pointer containing all of the information in the |
5432 | /// nested-name-specifier \p SS. |
5433 | void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); |
5434 | |
5435 | /// \brief Given an annotation pointer for a nested-name-specifier, restore |
5436 | /// the nested-name-specifier structure. |
5437 | /// |
5438 | /// \param Annotation The annotation pointer, produced by |
5439 | /// \c SaveNestedNameSpecifierAnnotation(). |
5440 | /// |
5441 | /// \param AnnotationRange The source range corresponding to the annotation. |
5442 | /// |
5443 | /// \param SS The nested-name-specifier that will be updated with the contents |
5444 | /// of the annotation pointer. |
5445 | void RestoreNestedNameSpecifierAnnotation(void *Annotation, |
5446 | SourceRange AnnotationRange, |
5447 | CXXScopeSpec &SS); |
5448 | |
5449 | bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); |
5450 | |
5451 | /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global |
5452 | /// scope or nested-name-specifier) is parsed, part of a declarator-id. |
5453 | /// After this method is called, according to [C++ 3.4.3p3], names should be |
5454 | /// looked up in the declarator-id's scope, until the declarator is parsed and |
5455 | /// ActOnCXXExitDeclaratorScope is called. |
5456 | /// The 'SS' should be a non-empty valid CXXScopeSpec. |
5457 | bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); |
5458 | |
5459 | /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously |
5460 | /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same |
5461 | /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. |
5462 | /// Used to indicate that names should revert to being looked up in the |
5463 | /// defining scope. |
5464 | void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); |
5465 | |
5466 | /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an |
5467 | /// initializer for the declaration 'Dcl'. |
5468 | /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a |
5469 | /// static data member of class X, names should be looked up in the scope of |
5470 | /// class X. |
5471 | void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); |
5472 | |
5473 | /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an |
5474 | /// initializer for the declaration 'Dcl'. |
5475 | void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); |
5476 | |
5477 | /// \brief Create a new lambda closure type. |
5478 | CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, |
5479 | TypeSourceInfo *Info, |
5480 | bool KnownDependent, |
5481 | LambdaCaptureDefault CaptureDefault); |
5482 | |
5483 | /// \brief Start the definition of a lambda expression. |
5484 | CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, |
5485 | SourceRange IntroducerRange, |
5486 | TypeSourceInfo *MethodType, |
5487 | SourceLocation EndLoc, |
5488 | ArrayRef<ParmVarDecl *> Params, |
5489 | bool IsConstexprSpecified); |
5490 | |
5491 | /// \brief Endow the lambda scope info with the relevant properties. |
5492 | void buildLambdaScope(sema::LambdaScopeInfo *LSI, |
5493 | CXXMethodDecl *CallOperator, |
5494 | SourceRange IntroducerRange, |
5495 | LambdaCaptureDefault CaptureDefault, |
5496 | SourceLocation CaptureDefaultLoc, |
5497 | bool ExplicitParams, |
5498 | bool ExplicitResultType, |
5499 | bool Mutable); |
5500 | |
5501 | /// \brief Perform initialization analysis of the init-capture and perform |
5502 | /// any implicit conversions such as an lvalue-to-rvalue conversion if |
5503 | /// not being used to initialize a reference. |
5504 | ParsedType actOnLambdaInitCaptureInitialization( |
5505 | SourceLocation Loc, bool ByRef, IdentifierInfo *Id, |
5506 | LambdaCaptureInitKind InitKind, Expr *&Init) { |
5507 | return ParsedType::make(buildLambdaInitCaptureInitialization( |
5508 | Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); |
5509 | } |
5510 | QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, |
5511 | IdentifierInfo *Id, |
5512 | bool DirectInit, Expr *&Init); |
5513 | |
5514 | /// \brief Create a dummy variable within the declcontext of the lambda's |
5515 | /// call operator, for name lookup purposes for a lambda init capture. |
5516 | /// |
5517 | /// CodeGen handles emission of lambda captures, ignoring these dummy |
5518 | /// variables appropriately. |
5519 | VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, |
5520 | QualType InitCaptureType, |
5521 | IdentifierInfo *Id, |
5522 | unsigned InitStyle, Expr *Init); |
5523 | |
5524 | /// \brief Build the implicit field for an init-capture. |
5525 | FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var); |
5526 | |
5527 | /// \brief Note that we have finished the explicit captures for the |
5528 | /// given lambda. |
5529 | void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); |
5530 | |
5531 | /// \brief Introduce the lambda parameters into scope. |
5532 | void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope); |
5533 | |
5534 | /// \brief Deduce a block or lambda's return type based on the return |
5535 | /// statements present in the body. |
5536 | void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); |
5537 | |
5538 | /// ActOnStartOfLambdaDefinition - This is called just before we start |
5539 | /// parsing the body of a lambda; it analyzes the explicit captures and |
5540 | /// arguments, and sets up various data-structures for the body of the |
5541 | /// lambda. |
5542 | void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, |
5543 | Declarator &ParamInfo, Scope *CurScope); |
5544 | |
5545 | /// ActOnLambdaError - If there is an error parsing a lambda, this callback |
5546 | /// is invoked to pop the information about the lambda. |
5547 | void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, |
5548 | bool IsInstantiation = false); |
5549 | |
5550 | /// ActOnLambdaExpr - This is called when the body of a lambda expression |
5551 | /// was successfully completed. |
5552 | ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, |
5553 | Scope *CurScope); |
5554 | |
5555 | /// \brief Does copying/destroying the captured variable have side effects? |
5556 | bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From); |
5557 | |
5558 | /// \brief Diagnose if an explicit lambda capture is unused. |
5559 | void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From); |
5560 | |
5561 | /// \brief Complete a lambda-expression having processed and attached the |
5562 | /// lambda body. |
5563 | ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, |
5564 | sema::LambdaScopeInfo *LSI); |
5565 | |
5566 | /// Get the return type to use for a lambda's conversion function(s) to |
5567 | /// function pointer type, given the type of the call operator. |
5568 | QualType |
5569 | getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); |
5570 | |
5571 | /// \brief Define the "body" of the conversion from a lambda object to a |
5572 | /// function pointer. |
5573 | /// |
5574 | /// This routine doesn't actually define a sensible body; rather, it fills |
5575 | /// in the initialization expression needed to copy the lambda object into |
5576 | /// the block, and IR generation actually generates the real body of the |
5577 | /// block pointer conversion. |
5578 | void DefineImplicitLambdaToFunctionPointerConversion( |
5579 | SourceLocation CurrentLoc, CXXConversionDecl *Conv); |
5580 | |
5581 | /// \brief Define the "body" of the conversion from a lambda object to a |
5582 | /// block pointer. |
5583 | /// |
5584 | /// This routine doesn't actually define a sensible body; rather, it fills |
5585 | /// in the initialization expression needed to copy the lambda object into |
5586 | /// the block, and IR generation actually generates the real body of the |
5587 | /// block pointer conversion. |
5588 | void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, |
5589 | CXXConversionDecl *Conv); |
5590 | |
5591 | ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, |
5592 | SourceLocation ConvLocation, |
5593 | CXXConversionDecl *Conv, |
5594 | Expr *Src); |
5595 | |
5596 | // ParseObjCStringLiteral - Parse Objective-C string literals. |
5597 | ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, |
5598 | ArrayRef<Expr *> Strings); |
5599 | |
5600 | ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); |
5601 | |
5602 | /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the |
5603 | /// numeric literal expression. Type of the expression will be "NSNumber *" |
5604 | /// or "id" if NSNumber is unavailable. |
5605 | ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); |
5606 | ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, |
5607 | bool Value); |
5608 | ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); |
5609 | |
5610 | /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the |
5611 | /// '@' prefixed parenthesized expression. The type of the expression will |
5612 | /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type |
5613 | /// of ValueType, which is allowed to be a built-in numeric type, "char *", |
5614 | /// "const char *" or C structure with attribute 'objc_boxable'. |
5615 | ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); |
5616 | |
5617 | ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, |
5618 | Expr *IndexExpr, |
5619 | ObjCMethodDecl *getterMethod, |
5620 | ObjCMethodDecl *setterMethod); |
5621 | |
5622 | ExprResult BuildObjCDictionaryLiteral(SourceRange SR, |
5623 | MutableArrayRef<ObjCDictionaryElement> Elements); |
5624 | |
5625 | ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, |
5626 | TypeSourceInfo *EncodedTypeInfo, |
5627 | SourceLocation RParenLoc); |
5628 | ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, |
5629 | CXXConversionDecl *Method, |
5630 | bool HadMultipleCandidates); |
5631 | |
5632 | ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, |
5633 | SourceLocation EncodeLoc, |
5634 | SourceLocation LParenLoc, |
5635 | ParsedType Ty, |
5636 | SourceLocation RParenLoc); |
5637 | |
5638 | /// ParseObjCSelectorExpression - Build selector expression for \@selector |
5639 | ExprResult ParseObjCSelectorExpression(Selector Sel, |
5640 | SourceLocation AtLoc, |
5641 | SourceLocation SelLoc, |
5642 | SourceLocation LParenLoc, |
5643 | SourceLocation RParenLoc, |
5644 | bool WarnMultipleSelectors); |
5645 | |
5646 | /// ParseObjCProtocolExpression - Build protocol expression for \@protocol |
5647 | ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, |
5648 | SourceLocation AtLoc, |
5649 | SourceLocation ProtoLoc, |
5650 | SourceLocation LParenLoc, |
5651 | SourceLocation ProtoIdLoc, |
5652 | SourceLocation RParenLoc); |
5653 | |
5654 | //===--------------------------------------------------------------------===// |
5655 | // C++ Declarations |
5656 | // |
5657 | Decl *ActOnStartLinkageSpecification(Scope *S, |
5658 | SourceLocation ExternLoc, |
5659 | Expr *LangStr, |
5660 | SourceLocation LBraceLoc); |
5661 | Decl *ActOnFinishLinkageSpecification(Scope *S, |
5662 | Decl *LinkageSpec, |
5663 | SourceLocation RBraceLoc); |
5664 | |
5665 | |
5666 | //===--------------------------------------------------------------------===// |
5667 | // C++ Classes |
5668 | // |
5669 | bool isCurrentClassName(const IdentifierInfo &II, Scope *S, |
5670 | const CXXScopeSpec *SS = nullptr); |
5671 | bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); |
5672 | |
5673 | bool ActOnAccessSpecifier(AccessSpecifier Access, |
5674 | SourceLocation ASLoc, |
5675 | SourceLocation ColonLoc, |
5676 | AttributeList *Attrs = nullptr); |
5677 | |
5678 | NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, |
5679 | Declarator &D, |
5680 | MultiTemplateParamsArg TemplateParameterLists, |
5681 | Expr *BitfieldWidth, const VirtSpecifiers &VS, |
5682 | InClassInitStyle InitStyle); |
5683 | |
5684 | void ActOnStartCXXInClassMemberInitializer(); |
5685 | void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, |
5686 | SourceLocation EqualLoc, |
5687 | Expr *Init); |
5688 | |
5689 | MemInitResult ActOnMemInitializer(Decl *ConstructorD, |
5690 | Scope *S, |
5691 | CXXScopeSpec &SS, |
5692 | IdentifierInfo *MemberOrBase, |
5693 | ParsedType TemplateTypeTy, |
5694 | const DeclSpec &DS, |
5695 | SourceLocation IdLoc, |
5696 | SourceLocation LParenLoc, |
5697 | ArrayRef<Expr *> Args, |
5698 | SourceLocation RParenLoc, |
5699 | SourceLocation EllipsisLoc); |
5700 | |
5701 | MemInitResult ActOnMemInitializer(Decl *ConstructorD, |
5702 | Scope *S, |
5703 | CXXScopeSpec &SS, |
5704 | IdentifierInfo *MemberOrBase, |
5705 | ParsedType TemplateTypeTy, |
5706 | const DeclSpec &DS, |
5707 | SourceLocation IdLoc, |
5708 | Expr *InitList, |
5709 | SourceLocation EllipsisLoc); |
5710 | |
5711 | MemInitResult BuildMemInitializer(Decl *ConstructorD, |
5712 | Scope *S, |
5713 | CXXScopeSpec &SS, |
5714 | IdentifierInfo *MemberOrBase, |
5715 | ParsedType TemplateTypeTy, |
5716 | const DeclSpec &DS, |
5717 | SourceLocation IdLoc, |
5718 | Expr *Init, |
5719 | SourceLocation EllipsisLoc); |
5720 | |
5721 | MemInitResult BuildMemberInitializer(ValueDecl *Member, |
5722 | Expr *Init, |
5723 | SourceLocation IdLoc); |
5724 | |
5725 | MemInitResult BuildBaseInitializer(QualType BaseType, |
5726 | TypeSourceInfo *BaseTInfo, |
5727 | Expr *Init, |
5728 | CXXRecordDecl *ClassDecl, |
5729 | SourceLocation EllipsisLoc); |
5730 | |
5731 | MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, |
5732 | Expr *Init, |
5733 | CXXRecordDecl *ClassDecl); |
5734 | |
5735 | bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, |
5736 | CXXCtorInitializer *Initializer); |
5737 | |
5738 | bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, |
5739 | ArrayRef<CXXCtorInitializer *> Initializers = None); |
5740 | |
5741 | void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); |
5742 | |
5743 | |
5744 | /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, |
5745 | /// mark all the non-trivial destructors of its members and bases as |
5746 | /// referenced. |
5747 | void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, |
5748 | CXXRecordDecl *Record); |
5749 | |
5750 | /// \brief The list of classes whose vtables have been used within |
5751 | /// this translation unit, and the source locations at which the |
5752 | /// first use occurred. |
5753 | typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; |
5754 | |
5755 | /// \brief The list of vtables that are required but have not yet been |
5756 | /// materialized. |
5757 | SmallVector<VTableUse, 16> VTableUses; |
5758 | |
5759 | /// \brief The set of classes whose vtables have been used within |
5760 | /// this translation unit, and a bit that will be true if the vtable is |
5761 | /// required to be emitted (otherwise, it should be emitted only if needed |
5762 | /// by code generation). |
5763 | llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; |
5764 | |
5765 | /// \brief Load any externally-stored vtable uses. |
5766 | void LoadExternalVTableUses(); |
5767 | |
5768 | /// \brief Note that the vtable for the given class was used at the |
5769 | /// given location. |
5770 | void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, |
5771 | bool DefinitionRequired = false); |
5772 | |
5773 | /// \brief Mark the exception specifications of all virtual member functions |
5774 | /// in the given class as needed. |
5775 | void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, |
5776 | const CXXRecordDecl *RD); |
5777 | |
5778 | /// MarkVirtualMembersReferenced - Will mark all members of the given |
5779 | /// CXXRecordDecl referenced. |
5780 | void MarkVirtualMembersReferenced(SourceLocation Loc, |
5781 | const CXXRecordDecl *RD); |
5782 | |
5783 | /// \brief Define all of the vtables that have been used in this |
5784 | /// translation unit and reference any virtual members used by those |
5785 | /// vtables. |
5786 | /// |
5787 | /// \returns true if any work was done, false otherwise. |
5788 | bool DefineUsedVTables(); |
5789 | |
5790 | void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); |
5791 | |
5792 | void ActOnMemInitializers(Decl *ConstructorDecl, |
5793 | SourceLocation ColonLoc, |
5794 | ArrayRef<CXXCtorInitializer*> MemInits, |
5795 | bool AnyErrors); |
5796 | |
5797 | /// \brief Check class-level dllimport/dllexport attribute. The caller must |
5798 | /// ensure that referenceDLLExportedClassMethods is called some point later |
5799 | /// when all outer classes of Class are complete. |
5800 | void checkClassLevelDLLAttribute(CXXRecordDecl *Class); |
5801 | |
5802 | void referenceDLLExportedClassMethods(); |
5803 | |
5804 | void propagateDLLAttrToBaseClassTemplate( |
5805 | CXXRecordDecl *Class, Attr *ClassAttr, |
5806 | ClassTemplateSpecializationDecl *BaseTemplateSpec, |
5807 | SourceLocation BaseLoc); |
5808 | |
5809 | void CheckCompletedCXXClass(CXXRecordDecl *Record); |
5810 | |
5811 | /// Check that the C++ class annoated with "trivial_abi" satisfies all the |
5812 | /// conditions that are needed for the attribute to have an effect. |
5813 | void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); |
5814 | |
5815 | void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, |
5816 | Decl *TagDecl, |
5817 | SourceLocation LBrac, |
5818 | SourceLocation RBrac, |
5819 | AttributeList *AttrList); |
5820 | void ActOnFinishCXXMemberDecls(); |
5821 | void ActOnFinishCXXNonNestedClass(Decl *D); |
5822 | |
5823 | void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); |
5824 | unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); |
5825 | void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); |
5826 | void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); |
5827 | void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); |
5828 | void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); |
5829 | void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); |
5830 | void ActOnFinishDelayedMemberInitializers(Decl *Record); |
5831 | void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, |
5832 | CachedTokens &Toks); |
5833 | void UnmarkAsLateParsedTemplate(FunctionDecl *FD); |
5834 | bool IsInsideALocalClassWithinATemplateFunction(); |
5835 | |
5836 | Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, |
5837 | Expr *AssertExpr, |
5838 | Expr *AssertMessageExpr, |
5839 | SourceLocation RParenLoc); |
5840 | Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, |
5841 | Expr *AssertExpr, |
5842 | StringLiteral *AssertMessageExpr, |
5843 | SourceLocation RParenLoc, |
5844 | bool Failed); |
5845 | |
5846 | FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, |
5847 | SourceLocation FriendLoc, |
5848 | TypeSourceInfo *TSInfo); |
5849 | Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, |
5850 | MultiTemplateParamsArg TemplateParams); |
5851 | NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, |
5852 | MultiTemplateParamsArg TemplateParams); |
5853 | |
5854 | QualType CheckConstructorDeclarator(Declarator &D, QualType R, |
5855 | StorageClass& SC); |
5856 | void CheckConstructor(CXXConstructorDecl *Constructor); |
5857 | QualType CheckDestructorDeclarator(Declarator &D, QualType R, |
5858 | StorageClass& SC); |
5859 | bool CheckDestructor(CXXDestructorDecl *Destructor); |
5860 | void CheckConversionDeclarator(Declarator &D, QualType &R, |
5861 | StorageClass& SC); |
5862 | Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); |
5863 | void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, |
5864 | StorageClass &SC); |
5865 | void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); |
5866 | |
5867 | void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); |
5868 | void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD, |
5869 | const FunctionProtoType *T); |
5870 | void CheckDelayedMemberExceptionSpecs(); |
5871 | |
5872 | //===--------------------------------------------------------------------===// |
5873 | // C++ Derived Classes |
5874 | // |
5875 | |
5876 | /// ActOnBaseSpecifier - Parsed a base specifier |
5877 | CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, |
5878 | SourceRange SpecifierRange, |
5879 | bool Virtual, AccessSpecifier Access, |
5880 | TypeSourceInfo *TInfo, |
5881 | SourceLocation EllipsisLoc); |
5882 | |
5883 | BaseResult ActOnBaseSpecifier(Decl *classdecl, |
5884 | SourceRange SpecifierRange, |
5885 | ParsedAttributes &Attrs, |
5886 | bool Virtual, AccessSpecifier Access, |
5887 | ParsedType basetype, |
5888 | SourceLocation BaseLoc, |
5889 | SourceLocation EllipsisLoc); |
5890 | |
5891 | bool AttachBaseSpecifiers(CXXRecordDecl *Class, |
5892 | MutableArrayRef<CXXBaseSpecifier *> Bases); |
5893 | void ActOnBaseSpecifiers(Decl *ClassDecl, |
5894 | MutableArrayRef<CXXBaseSpecifier *> Bases); |
5895 | |
5896 | bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); |
5897 | bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, |
5898 | CXXBasePaths &Paths); |
5899 | |
5900 | // FIXME: I don't like this name. |
5901 | void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); |
5902 | |
5903 | bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
5904 | SourceLocation Loc, SourceRange Range, |
5905 | CXXCastPath *BasePath = nullptr, |
5906 | bool IgnoreAccess = false); |
5907 | bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
5908 | unsigned InaccessibleBaseID, |
5909 | unsigned AmbigiousBaseConvID, |
5910 | SourceLocation Loc, SourceRange Range, |
5911 | DeclarationName Name, |
5912 | CXXCastPath *BasePath, |
5913 | bool IgnoreAccess = false); |
5914 | |
5915 | std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); |
5916 | |
5917 | bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, |
5918 | const CXXMethodDecl *Old); |
5919 | |
5920 | /// CheckOverridingFunctionReturnType - Checks whether the return types are |
5921 | /// covariant, according to C++ [class.virtual]p5. |
5922 | bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, |
5923 | const CXXMethodDecl *Old); |
5924 | |
5925 | /// CheckOverridingFunctionExceptionSpec - Checks whether the exception |
5926 | /// spec is a subset of base spec. |
5927 | bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, |
5928 | const CXXMethodDecl *Old); |
5929 | |
5930 | bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); |
5931 | |
5932 | /// CheckOverrideControl - Check C++11 override control semantics. |
5933 | void CheckOverrideControl(NamedDecl *D); |
5934 | |
5935 | /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was |
5936 | /// not used in the declaration of an overriding method. |
5937 | void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); |
5938 | |
5939 | /// CheckForFunctionMarkedFinal - Checks whether a virtual member function |
5940 | /// overrides a virtual member function marked 'final', according to |
5941 | /// C++11 [class.virtual]p4. |
5942 | bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, |
5943 | const CXXMethodDecl *Old); |
5944 | |
5945 | |
5946 | //===--------------------------------------------------------------------===// |
5947 | // C++ Access Control |
5948 | // |
5949 | |
5950 | enum AccessResult { |
5951 | AR_accessible, |
5952 | AR_inaccessible, |
5953 | AR_dependent, |
5954 | AR_delayed |
5955 | }; |
5956 | |
5957 | bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, |
5958 | NamedDecl *PrevMemberDecl, |
5959 | AccessSpecifier LexicalAS); |
5960 | |
5961 | AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, |
5962 | DeclAccessPair FoundDecl); |
5963 | AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, |
5964 | DeclAccessPair FoundDecl); |
5965 | AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, |
5966 | SourceRange PlacementRange, |
5967 | CXXRecordDecl *NamingClass, |
5968 | DeclAccessPair FoundDecl, |
5969 | bool Diagnose = true); |
5970 | AccessResult CheckConstructorAccess(SourceLocation Loc, |
5971 | CXXConstructorDecl *D, |
5972 | DeclAccessPair FoundDecl, |
5973 | const InitializedEntity &Entity, |
5974 | bool IsCopyBindingRefToTemp = false); |
5975 | AccessResult CheckConstructorAccess(SourceLocation Loc, |
5976 | CXXConstructorDecl *D, |
5977 | DeclAccessPair FoundDecl, |
5978 | const InitializedEntity &Entity, |
5979 | const PartialDiagnostic &PDiag); |
5980 | AccessResult CheckDestructorAccess(SourceLocation Loc, |
5981 | CXXDestructorDecl *Dtor, |
5982 | const PartialDiagnostic &PDiag, |
5983 | QualType objectType = QualType()); |
5984 | AccessResult CheckFriendAccess(NamedDecl *D); |
5985 | AccessResult CheckMemberAccess(SourceLocation UseLoc, |
5986 | CXXRecordDecl *NamingClass, |
5987 | DeclAccessPair Found); |
5988 | AccessResult CheckMemberOperatorAccess(SourceLocation Loc, |
5989 | Expr *ObjectExpr, |
5990 | Expr *ArgExpr, |
5991 | DeclAccessPair FoundDecl); |
5992 | AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, |
5993 | DeclAccessPair FoundDecl); |
5994 | AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, |
5995 | QualType Base, QualType Derived, |
5996 | const CXXBasePath &Path, |
5997 | unsigned DiagID, |
5998 | bool ForceCheck = false, |
5999 | bool ForceUnprivileged = false); |
6000 | void CheckLookupAccess(const LookupResult &R); |
6001 | bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx); |
6002 | bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, |
6003 | AccessSpecifier access, |
6004 | QualType objectType); |
6005 | |
6006 | void HandleDependentAccessCheck(const DependentDiagnostic &DD, |
6007 | const MultiLevelTemplateArgumentList &TemplateArgs); |
6008 | void PerformDependentDiagnostics(const DeclContext *Pattern, |
6009 | const MultiLevelTemplateArgumentList &TemplateArgs); |
6010 | |
6011 | void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); |
6012 | |
6013 | /// \brief When true, access checking violations are treated as SFINAE |
6014 | /// failures rather than hard errors. |
6015 | bool AccessCheckingSFINAE; |
6016 | |
6017 | enum AbstractDiagSelID { |
6018 | AbstractNone = -1, |
6019 | AbstractReturnType, |
6020 | AbstractParamType, |
6021 | AbstractVariableType, |
6022 | AbstractFieldType, |
6023 | AbstractIvarType, |
6024 | AbstractSynthesizedIvarType, |
6025 | AbstractArrayType |
6026 | }; |
6027 | |
6028 | bool isAbstractType(SourceLocation Loc, QualType T); |
6029 | bool RequireNonAbstractType(SourceLocation Loc, QualType T, |
6030 | TypeDiagnoser &Diagnoser); |
6031 | template <typename... Ts> |
6032 | bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, |
6033 | const Ts &...Args) { |
6034 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); |
6035 | return RequireNonAbstractType(Loc, T, Diagnoser); |
6036 | } |
6037 | |
6038 | void DiagnoseAbstractType(const CXXRecordDecl *RD); |
6039 | |
6040 | //===--------------------------------------------------------------------===// |
6041 | // C++ Overloaded Operators [C++ 13.5] |
6042 | // |
6043 | |
6044 | bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); |
6045 | |
6046 | bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); |
6047 | |
6048 | //===--------------------------------------------------------------------===// |
6049 | // C++ Templates [C++ 14] |
6050 | // |
6051 | void FilterAcceptableTemplateNames(LookupResult &R, |
6052 | bool AllowFunctionTemplates = true); |
6053 | bool hasAnyAcceptableTemplateNames(LookupResult &R, |
6054 | bool AllowFunctionTemplates = true); |
6055 | |
6056 | void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, |
6057 | QualType ObjectType, bool EnteringContext, |
6058 | bool &MemberOfUnknownSpecialization); |
6059 | |
6060 | TemplateNameKind isTemplateName(Scope *S, |
6061 | CXXScopeSpec &SS, |
6062 | bool hasTemplateKeyword, |
6063 | UnqualifiedId &Name, |
6064 | ParsedType ObjectType, |
6065 | bool EnteringContext, |
6066 | TemplateTy &Template, |
6067 | bool &MemberOfUnknownSpecialization); |
6068 | |
6069 | /// Determine whether a particular identifier might be the name in a C++1z |
6070 | /// deduction-guide declaration. |
6071 | bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, |
6072 | SourceLocation NameLoc, |
6073 | ParsedTemplateTy *Template = nullptr); |
6074 | |
6075 | bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, |
6076 | SourceLocation IILoc, |
6077 | Scope *S, |
6078 | const CXXScopeSpec *SS, |
6079 | TemplateTy &SuggestedTemplate, |
6080 | TemplateNameKind &SuggestedKind); |
6081 | |
6082 | bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, |
6083 | NamedDecl *Instantiation, |
6084 | bool InstantiatedFromMember, |
6085 | const NamedDecl *Pattern, |
6086 | const NamedDecl *PatternDef, |
6087 | TemplateSpecializationKind TSK, |
6088 | bool Complain = true); |
6089 | |
6090 | void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); |
6091 | TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); |
6092 | |
6093 | NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, |
6094 | SourceLocation EllipsisLoc, |
6095 | SourceLocation KeyLoc, |
6096 | IdentifierInfo *ParamName, |
6097 | SourceLocation ParamNameLoc, |
6098 | unsigned Depth, unsigned Position, |
6099 | SourceLocation EqualLoc, |
6100 | ParsedType DefaultArg); |
6101 | |
6102 | QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, |
6103 | SourceLocation Loc); |
6104 | QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); |
6105 | |
6106 | NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, |
6107 | unsigned Depth, |
6108 | unsigned Position, |
6109 | SourceLocation EqualLoc, |
6110 | Expr *DefaultArg); |
6111 | NamedDecl *ActOnTemplateTemplateParameter(Scope *S, |
6112 | SourceLocation TmpLoc, |
6113 | TemplateParameterList *Params, |
6114 | SourceLocation EllipsisLoc, |
6115 | IdentifierInfo *ParamName, |
6116 | SourceLocation ParamNameLoc, |
6117 | unsigned Depth, |
6118 | unsigned Position, |
6119 | SourceLocation EqualLoc, |
6120 | ParsedTemplateArgument DefaultArg); |
6121 | |
6122 | TemplateParameterList * |
6123 | ActOnTemplateParameterList(unsigned Depth, |
6124 | SourceLocation ExportLoc, |
6125 | SourceLocation TemplateLoc, |
6126 | SourceLocation LAngleLoc, |
6127 | ArrayRef<NamedDecl *> Params, |
6128 | SourceLocation RAngleLoc, |
6129 | Expr *RequiresClause); |
6130 | |
6131 | /// \brief The context in which we are checking a template parameter list. |
6132 | enum TemplateParamListContext { |
6133 | TPC_ClassTemplate, |
6134 | TPC_VarTemplate, |
6135 | TPC_FunctionTemplate, |
6136 | TPC_ClassTemplateMember, |
6137 | TPC_FriendClassTemplate, |
6138 | TPC_FriendFunctionTemplate, |
6139 | TPC_FriendFunctionTemplateDefinition, |
6140 | TPC_TypeAliasTemplate |
6141 | }; |
6142 | |
6143 | bool CheckTemplateParameterList(TemplateParameterList *NewParams, |
6144 | TemplateParameterList *OldParams, |
6145 | TemplateParamListContext TPC); |
6146 | TemplateParameterList *MatchTemplateParametersToScopeSpecifier( |
6147 | SourceLocation DeclStartLoc, SourceLocation DeclLoc, |
6148 | const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, |
6149 | ArrayRef<TemplateParameterList *> ParamLists, |
6150 | bool IsFriend, bool &IsMemberSpecialization, bool &Invalid); |
6151 | |
6152 | DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, |
6153 | SourceLocation KWLoc, CXXScopeSpec &SS, |
6154 | IdentifierInfo *Name, SourceLocation NameLoc, |
6155 | AttributeList *Attr, |
6156 | TemplateParameterList *TemplateParams, |
6157 | AccessSpecifier AS, |
6158 | SourceLocation ModulePrivateLoc, |
6159 | SourceLocation FriendLoc, |
6160 | unsigned NumOuterTemplateParamLists, |
6161 | TemplateParameterList **OuterTemplateParamLists, |
6162 | SkipBodyInfo *SkipBody = nullptr); |
6163 | |
6164 | TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, |
6165 | QualType NTTPType, |
6166 | SourceLocation Loc); |
6167 | |
6168 | void translateTemplateArguments(const ASTTemplateArgsPtr &In, |
6169 | TemplateArgumentListInfo &Out); |
6170 | |
6171 | ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); |
6172 | |
6173 | void NoteAllFoundTemplates(TemplateName Name); |
6174 | |
6175 | QualType CheckTemplateIdType(TemplateName Template, |
6176 | SourceLocation TemplateLoc, |
6177 | TemplateArgumentListInfo &TemplateArgs); |
6178 | |
6179 | TypeResult |
6180 | ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
6181 | TemplateTy Template, IdentifierInfo *TemplateII, |
6182 | SourceLocation TemplateIILoc, |
6183 | SourceLocation LAngleLoc, |
6184 | ASTTemplateArgsPtr TemplateArgs, |
6185 | SourceLocation RAngleLoc, |
6186 | bool IsCtorOrDtorName = false, |
6187 | bool IsClassName = false); |
6188 | |
6189 | /// \brief Parsed an elaborated-type-specifier that refers to a template-id, |
6190 | /// such as \c class T::template apply<U>. |
6191 | TypeResult ActOnTagTemplateIdType(TagUseKind TUK, |
6192 | TypeSpecifierType TagSpec, |
6193 | SourceLocation TagLoc, |
6194 | CXXScopeSpec &SS, |
6195 | SourceLocation TemplateKWLoc, |
6196 | TemplateTy TemplateD, |
6197 | SourceLocation TemplateLoc, |
6198 | SourceLocation LAngleLoc, |
6199 | ASTTemplateArgsPtr TemplateArgsIn, |
6200 | SourceLocation RAngleLoc); |
6201 | |
6202 | DeclResult ActOnVarTemplateSpecialization( |
6203 | Scope *S, Declarator &D, TypeSourceInfo *DI, |
6204 | SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, |
6205 | StorageClass SC, bool IsPartialSpecialization); |
6206 | |
6207 | DeclResult CheckVarTemplateId(VarTemplateDecl *Template, |
6208 | SourceLocation TemplateLoc, |
6209 | SourceLocation TemplateNameLoc, |
6210 | const TemplateArgumentListInfo &TemplateArgs); |
6211 | |
6212 | ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, |
6213 | const DeclarationNameInfo &NameInfo, |
6214 | VarTemplateDecl *Template, |
6215 | SourceLocation TemplateLoc, |
6216 | const TemplateArgumentListInfo *TemplateArgs); |
6217 | |
6218 | ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, |
6219 | SourceLocation TemplateKWLoc, |
6220 | LookupResult &R, |
6221 | bool RequiresADL, |
6222 | const TemplateArgumentListInfo *TemplateArgs); |
6223 | |
6224 | ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, |
6225 | SourceLocation TemplateKWLoc, |
6226 | const DeclarationNameInfo &NameInfo, |
6227 | const TemplateArgumentListInfo *TemplateArgs); |
6228 | |
6229 | TemplateNameKind ActOnDependentTemplateName( |
6230 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
6231 | UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, |
6232 | TemplateTy &Template, bool AllowInjectedClassName = false); |
6233 | |
6234 | DeclResult |
6235 | ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, |
6236 | SourceLocation KWLoc, |
6237 | SourceLocation ModulePrivateLoc, |
6238 | TemplateIdAnnotation &TemplateId, |
6239 | AttributeList *Attr, |
6240 | MultiTemplateParamsArg TemplateParameterLists, |
6241 | SkipBodyInfo *SkipBody = nullptr); |
6242 | |
6243 | bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, |
6244 | TemplateDecl *PrimaryTemplate, |
6245 | unsigned NumExplicitArgs, |
6246 | ArrayRef<TemplateArgument> Args); |
6247 | void CheckTemplatePartialSpecialization( |
6248 | ClassTemplatePartialSpecializationDecl *Partial); |
6249 | void CheckTemplatePartialSpecialization( |
6250 | VarTemplatePartialSpecializationDecl *Partial); |
6251 | |
6252 | Decl *ActOnTemplateDeclarator(Scope *S, |
6253 | MultiTemplateParamsArg TemplateParameterLists, |
6254 | Declarator &D); |
6255 | |
6256 | bool |
6257 | CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, |
6258 | TemplateSpecializationKind NewTSK, |
6259 | NamedDecl *PrevDecl, |
6260 | TemplateSpecializationKind PrevTSK, |
6261 | SourceLocation PrevPtOfInstantiation, |
6262 | bool &SuppressNew); |
6263 | |
6264 | bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, |
6265 | const TemplateArgumentListInfo &ExplicitTemplateArgs, |
6266 | LookupResult &Previous); |
6267 | |
6268 | bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, |
6269 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
6270 | LookupResult &Previous); |
6271 | bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); |
6272 | void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); |
6273 | |
6274 | DeclResult |
6275 | ActOnExplicitInstantiation(Scope *S, |
6276 | SourceLocation ExternLoc, |
6277 | SourceLocation TemplateLoc, |
6278 | unsigned TagSpec, |
6279 | SourceLocation KWLoc, |
6280 | const CXXScopeSpec &SS, |
6281 | TemplateTy Template, |
6282 | SourceLocation TemplateNameLoc, |
6283 | SourceLocation LAngleLoc, |
6284 | ASTTemplateArgsPtr TemplateArgs, |
6285 | SourceLocation RAngleLoc, |
6286 | AttributeList *Attr); |
6287 | |
6288 | DeclResult |
6289 | ActOnExplicitInstantiation(Scope *S, |
6290 | SourceLocation ExternLoc, |
6291 | SourceLocation TemplateLoc, |
6292 | unsigned TagSpec, |
6293 | SourceLocation KWLoc, |
6294 | CXXScopeSpec &SS, |
6295 | IdentifierInfo *Name, |
6296 | SourceLocation NameLoc, |
6297 | AttributeList *Attr); |
6298 | |
6299 | DeclResult ActOnExplicitInstantiation(Scope *S, |
6300 | SourceLocation ExternLoc, |
6301 | SourceLocation TemplateLoc, |
6302 | Declarator &D); |
6303 | |
6304 | TemplateArgumentLoc |
6305 | SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, |
6306 | SourceLocation TemplateLoc, |
6307 | SourceLocation RAngleLoc, |
6308 | Decl *Param, |
6309 | SmallVectorImpl<TemplateArgument> |
6310 | &Converted, |
6311 | bool &HasDefaultArg); |
6312 | |
6313 | /// \brief Specifies the context in which a particular template |
6314 | /// argument is being checked. |
6315 | enum CheckTemplateArgumentKind { |
6316 | /// \brief The template argument was specified in the code or was |
6317 | /// instantiated with some deduced template arguments. |
6318 | CTAK_Specified, |
6319 | |
6320 | /// \brief The template argument was deduced via template argument |
6321 | /// deduction. |
6322 | CTAK_Deduced, |
6323 | |
6324 | /// \brief The template argument was deduced from an array bound |
6325 | /// via template argument deduction. |
6326 | CTAK_DeducedFromArrayBound |
6327 | }; |
6328 | |
6329 | bool CheckTemplateArgument(NamedDecl *Param, |
6330 | TemplateArgumentLoc &Arg, |
6331 | NamedDecl *Template, |
6332 | SourceLocation TemplateLoc, |
6333 | SourceLocation RAngleLoc, |
6334 | unsigned ArgumentPackIndex, |
6335 | SmallVectorImpl<TemplateArgument> &Converted, |
6336 | CheckTemplateArgumentKind CTAK = CTAK_Specified); |
6337 | |
6338 | /// \brief Check that the given template arguments can be be provided to |
6339 | /// the given template, converting the arguments along the way. |
6340 | /// |
6341 | /// \param Template The template to which the template arguments are being |
6342 | /// provided. |
6343 | /// |
6344 | /// \param TemplateLoc The location of the template name in the source. |
6345 | /// |
6346 | /// \param TemplateArgs The list of template arguments. If the template is |
6347 | /// a template template parameter, this function may extend the set of |
6348 | /// template arguments to also include substituted, defaulted template |
6349 | /// arguments. |
6350 | /// |
6351 | /// \param PartialTemplateArgs True if the list of template arguments is |
6352 | /// intentionally partial, e.g., because we're checking just the initial |
6353 | /// set of template arguments. |
6354 | /// |
6355 | /// \param Converted Will receive the converted, canonicalized template |
6356 | /// arguments. |
6357 | /// |
6358 | /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to |
6359 | /// contain the converted forms of the template arguments as written. |
6360 | /// Otherwise, \p TemplateArgs will not be modified. |
6361 | /// |
6362 | /// \returns true if an error occurred, false otherwise. |
6363 | bool CheckTemplateArgumentList(TemplateDecl *Template, |
6364 | SourceLocation TemplateLoc, |
6365 | TemplateArgumentListInfo &TemplateArgs, |
6366 | bool PartialTemplateArgs, |
6367 | SmallVectorImpl<TemplateArgument> &Converted, |
6368 | bool UpdateArgsWithConversions = true); |
6369 | |
6370 | bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, |
6371 | TemplateArgumentLoc &Arg, |
6372 | SmallVectorImpl<TemplateArgument> &Converted); |
6373 | |
6374 | bool CheckTemplateArgument(TemplateTypeParmDecl *Param, |
6375 | TypeSourceInfo *Arg); |
6376 | ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, |
6377 | QualType InstantiatedParamType, Expr *Arg, |
6378 | TemplateArgument &Converted, |
6379 | CheckTemplateArgumentKind CTAK = CTAK_Specified); |
6380 | bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, |
6381 | TemplateArgumentLoc &Arg, |
6382 | unsigned ArgumentPackIndex); |
6383 | |
6384 | ExprResult |
6385 | BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, |
6386 | QualType ParamType, |
6387 | SourceLocation Loc); |
6388 | ExprResult |
6389 | BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, |
6390 | SourceLocation Loc); |
6391 | |
6392 | /// \brief Enumeration describing how template parameter lists are compared |
6393 | /// for equality. |
6394 | enum TemplateParameterListEqualKind { |
6395 | /// \brief We are matching the template parameter lists of two templates |
6396 | /// that might be redeclarations. |
6397 | /// |
6398 | /// \code |
6399 | /// template<typename T> struct X; |
6400 | /// template<typename T> struct X; |
6401 | /// \endcode |
6402 | TPL_TemplateMatch, |
6403 | |
6404 | /// \brief We are matching the template parameter lists of two template |
6405 | /// template parameters as part of matching the template parameter lists |
6406 | /// of two templates that might be redeclarations. |
6407 | /// |
6408 | /// \code |
6409 | /// template<template<int I> class TT> struct X; |
6410 | /// template<template<int Value> class Other> struct X; |
6411 | /// \endcode |
6412 | TPL_TemplateTemplateParmMatch, |
6413 | |
6414 | /// \brief We are matching the template parameter lists of a template |
6415 | /// template argument against the template parameter lists of a template |
6416 | /// template parameter. |
6417 | /// |
6418 | /// \code |
6419 | /// template<template<int Value> class Metafun> struct X; |
6420 | /// template<int Value> struct integer_c; |
6421 | /// X<integer_c> xic; |
6422 | /// \endcode |
6423 | TPL_TemplateTemplateArgumentMatch |
6424 | }; |
6425 | |
6426 | bool TemplateParameterListsAreEqual(TemplateParameterList *New, |
6427 | TemplateParameterList *Old, |
6428 | bool Complain, |
6429 | TemplateParameterListEqualKind Kind, |
6430 | SourceLocation TemplateArgLoc |
6431 | = SourceLocation()); |
6432 | |
6433 | bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); |
6434 | |
6435 | /// \brief Called when the parser has parsed a C++ typename |
6436 | /// specifier, e.g., "typename T::type". |
6437 | /// |
6438 | /// \param S The scope in which this typename type occurs. |
6439 | /// \param TypenameLoc the location of the 'typename' keyword |
6440 | /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). |
6441 | /// \param II the identifier we're retrieving (e.g., 'type' in the example). |
6442 | /// \param IdLoc the location of the identifier. |
6443 | TypeResult |
6444 | ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, |
6445 | const CXXScopeSpec &SS, const IdentifierInfo &II, |
6446 | SourceLocation IdLoc); |
6447 | |
6448 | /// \brief Called when the parser has parsed a C++ typename |
6449 | /// specifier that ends in a template-id, e.g., |
6450 | /// "typename MetaFun::template apply<T1, T2>". |
6451 | /// |
6452 | /// \param S The scope in which this typename type occurs. |
6453 | /// \param TypenameLoc the location of the 'typename' keyword |
6454 | /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). |
6455 | /// \param TemplateLoc the location of the 'template' keyword, if any. |
6456 | /// \param TemplateName The template name. |
6457 | /// \param TemplateII The identifier used to name the template. |
6458 | /// \param TemplateIILoc The location of the template name. |
6459 | /// \param LAngleLoc The location of the opening angle bracket ('<'). |
6460 | /// \param TemplateArgs The template arguments. |
6461 | /// \param RAngleLoc The location of the closing angle bracket ('>'). |
6462 | TypeResult |
6463 | ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, |
6464 | const CXXScopeSpec &SS, |
6465 | SourceLocation TemplateLoc, |
6466 | TemplateTy TemplateName, |
6467 | IdentifierInfo *TemplateII, |
6468 | SourceLocation TemplateIILoc, |
6469 | SourceLocation LAngleLoc, |
6470 | ASTTemplateArgsPtr TemplateArgs, |
6471 | SourceLocation RAngleLoc); |
6472 | |
6473 | QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, |
6474 | SourceLocation KeywordLoc, |
6475 | NestedNameSpecifierLoc QualifierLoc, |
6476 | const IdentifierInfo &II, |
6477 | SourceLocation IILoc); |
6478 | |
6479 | TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, |
6480 | SourceLocation Loc, |
6481 | DeclarationName Name); |
6482 | bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); |
6483 | |
6484 | ExprResult RebuildExprInCurrentInstantiation(Expr *E); |
6485 | bool RebuildTemplateParamsInCurrentInstantiation( |
6486 | TemplateParameterList *Params); |
6487 | |
6488 | std::string |
6489 | getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
6490 | const TemplateArgumentList &Args); |
6491 | |
6492 | std::string |
6493 | getTemplateArgumentBindingsText(const TemplateParameterList *Params, |
6494 | const TemplateArgument *Args, |
6495 | unsigned NumArgs); |
6496 | |
6497 | //===--------------------------------------------------------------------===// |
6498 | // C++ Variadic Templates (C++0x [temp.variadic]) |
6499 | //===--------------------------------------------------------------------===// |
6500 | |
6501 | /// Determine whether an unexpanded parameter pack might be permitted in this |
6502 | /// location. Useful for error recovery. |
6503 | bool isUnexpandedParameterPackPermitted(); |
6504 | |
6505 | /// \brief The context in which an unexpanded parameter pack is |
6506 | /// being diagnosed. |
6507 | /// |
6508 | /// Note that the values of this enumeration line up with the first |
6509 | /// argument to the \c err_unexpanded_parameter_pack diagnostic. |
6510 | enum UnexpandedParameterPackContext { |
6511 | /// \brief An arbitrary expression. |
6512 | UPPC_Expression = 0, |
6513 | |
6514 | /// \brief The base type of a class type. |
6515 | UPPC_BaseType, |
6516 | |
6517 | /// \brief The type of an arbitrary declaration. |
6518 | UPPC_DeclarationType, |
6519 | |
6520 | /// \brief The type of a data member. |
6521 | UPPC_DataMemberType, |
6522 | |
6523 | /// \brief The size of a bit-field. |
6524 | UPPC_BitFieldWidth, |
6525 | |
6526 | /// \brief The expression in a static assertion. |
6527 | UPPC_StaticAssertExpression, |
6528 | |
6529 | /// \brief The fixed underlying type of an enumeration. |
6530 | UPPC_FixedUnderlyingType, |
6531 | |
6532 | /// \brief The enumerator value. |
6533 | UPPC_EnumeratorValue, |
6534 | |
6535 | /// \brief A using declaration. |
6536 | UPPC_UsingDeclaration, |
6537 | |
6538 | /// \brief A friend declaration. |
6539 | UPPC_FriendDeclaration, |
6540 | |
6541 | /// \brief A declaration qualifier. |
6542 | UPPC_DeclarationQualifier, |
6543 | |
6544 | /// \brief An initializer. |
6545 | UPPC_Initializer, |
6546 | |
6547 | /// \brief A default argument. |
6548 | UPPC_DefaultArgument, |
6549 | |
6550 | /// \brief The type of a non-type template parameter. |
6551 | UPPC_NonTypeTemplateParameterType, |
6552 | |
6553 | /// \brief The type of an exception. |
6554 | UPPC_ExceptionType, |
6555 | |
6556 | /// \brief Partial specialization. |
6557 | UPPC_PartialSpecialization, |
6558 | |
6559 | /// \brief Microsoft __if_exists. |
6560 | UPPC_IfExists, |
6561 | |
6562 | /// \brief Microsoft __if_not_exists. |
6563 | UPPC_IfNotExists, |
6564 | |
6565 | /// \brief Lambda expression. |
6566 | UPPC_Lambda, |
6567 | |
6568 | /// \brief Block expression, |
6569 | UPPC_Block |
6570 | }; |
6571 | |
6572 | /// \brief Diagnose unexpanded parameter packs. |
6573 | /// |
6574 | /// \param Loc The location at which we should emit the diagnostic. |
6575 | /// |
6576 | /// \param UPPC The context in which we are diagnosing unexpanded |
6577 | /// parameter packs. |
6578 | /// |
6579 | /// \param Unexpanded the set of unexpanded parameter packs. |
6580 | /// |
6581 | /// \returns true if an error occurred, false otherwise. |
6582 | bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, |
6583 | UnexpandedParameterPackContext UPPC, |
6584 | ArrayRef<UnexpandedParameterPack> Unexpanded); |
6585 | |
6586 | /// \brief If the given type contains an unexpanded parameter pack, |
6587 | /// diagnose the error. |
6588 | /// |
6589 | /// \param Loc The source location where a diagnostc should be emitted. |
6590 | /// |
6591 | /// \param T The type that is being checked for unexpanded parameter |
6592 | /// packs. |
6593 | /// |
6594 | /// \returns true if an error occurred, false otherwise. |
6595 | bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, |
6596 | UnexpandedParameterPackContext UPPC); |
6597 | |
6598 | /// \brief If the given expression contains an unexpanded parameter |
6599 | /// pack, diagnose the error. |
6600 | /// |
6601 | /// \param E The expression that is being checked for unexpanded |
6602 | /// parameter packs. |
6603 | /// |
6604 | /// \returns true if an error occurred, false otherwise. |
6605 | bool DiagnoseUnexpandedParameterPack(Expr *E, |
6606 | UnexpandedParameterPackContext UPPC = UPPC_Expression); |
6607 | |
6608 | /// \brief If the given nested-name-specifier contains an unexpanded |
6609 | /// parameter pack, diagnose the error. |
6610 | /// |
6611 | /// \param SS The nested-name-specifier that is being checked for |
6612 | /// unexpanded parameter packs. |
6613 | /// |
6614 | /// \returns true if an error occurred, false otherwise. |
6615 | bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, |
6616 | UnexpandedParameterPackContext UPPC); |
6617 | |
6618 | /// \brief If the given name contains an unexpanded parameter pack, |
6619 | /// diagnose the error. |
6620 | /// |
6621 | /// \param NameInfo The name (with source location information) that |
6622 | /// is being checked for unexpanded parameter packs. |
6623 | /// |
6624 | /// \returns true if an error occurred, false otherwise. |
6625 | bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, |
6626 | UnexpandedParameterPackContext UPPC); |
6627 | |
6628 | /// \brief If the given template name contains an unexpanded parameter pack, |
6629 | /// diagnose the error. |
6630 | /// |
6631 | /// \param Loc The location of the template name. |
6632 | /// |
6633 | /// \param Template The template name that is being checked for unexpanded |
6634 | /// parameter packs. |
6635 | /// |
6636 | /// \returns true if an error occurred, false otherwise. |
6637 | bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, |
6638 | TemplateName Template, |
6639 | UnexpandedParameterPackContext UPPC); |
6640 | |
6641 | /// \brief If the given template argument contains an unexpanded parameter |
6642 | /// pack, diagnose the error. |
6643 | /// |
6644 | /// \param Arg The template argument that is being checked for unexpanded |
6645 | /// parameter packs. |
6646 | /// |
6647 | /// \returns true if an error occurred, false otherwise. |
6648 | bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, |
6649 | UnexpandedParameterPackContext UPPC); |
6650 | |
6651 | /// \brief Collect the set of unexpanded parameter packs within the given |
6652 | /// template argument. |
6653 | /// |
6654 | /// \param Arg The template argument that will be traversed to find |
6655 | /// unexpanded parameter packs. |
6656 | void collectUnexpandedParameterPacks(TemplateArgument Arg, |
6657 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6658 | |
6659 | /// \brief Collect the set of unexpanded parameter packs within the given |
6660 | /// template argument. |
6661 | /// |
6662 | /// \param Arg The template argument that will be traversed to find |
6663 | /// unexpanded parameter packs. |
6664 | void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, |
6665 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6666 | |
6667 | /// \brief Collect the set of unexpanded parameter packs within the given |
6668 | /// type. |
6669 | /// |
6670 | /// \param T The type that will be traversed to find |
6671 | /// unexpanded parameter packs. |
6672 | void collectUnexpandedParameterPacks(QualType T, |
6673 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6674 | |
6675 | /// \brief Collect the set of unexpanded parameter packs within the given |
6676 | /// type. |
6677 | /// |
6678 | /// \param TL The type that will be traversed to find |
6679 | /// unexpanded parameter packs. |
6680 | void collectUnexpandedParameterPacks(TypeLoc TL, |
6681 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6682 | |
6683 | /// \brief Collect the set of unexpanded parameter packs within the given |
6684 | /// nested-name-specifier. |
6685 | /// |
6686 | /// \param NNS The nested-name-specifier that will be traversed to find |
6687 | /// unexpanded parameter packs. |
6688 | void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, |
6689 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6690 | |
6691 | /// \brief Collect the set of unexpanded parameter packs within the given |
6692 | /// name. |
6693 | /// |
6694 | /// \param NameInfo The name that will be traversed to find |
6695 | /// unexpanded parameter packs. |
6696 | void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, |
6697 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); |
6698 | |
6699 | /// \brief Invoked when parsing a template argument followed by an |
6700 | /// ellipsis, which creates a pack expansion. |
6701 | /// |
6702 | /// \param Arg The template argument preceding the ellipsis, which |
6703 | /// may already be invalid. |
6704 | /// |
6705 | /// \param EllipsisLoc The location of the ellipsis. |
6706 | ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, |
6707 | SourceLocation EllipsisLoc); |
6708 | |
6709 | /// \brief Invoked when parsing a type followed by an ellipsis, which |
6710 | /// creates a pack expansion. |
6711 | /// |
6712 | /// \param Type The type preceding the ellipsis, which will become |
6713 | /// the pattern of the pack expansion. |
6714 | /// |
6715 | /// \param EllipsisLoc The location of the ellipsis. |
6716 | TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); |
6717 | |
6718 | /// \brief Construct a pack expansion type from the pattern of the pack |
6719 | /// expansion. |
6720 | TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, |
6721 | SourceLocation EllipsisLoc, |
6722 | Optional<unsigned> NumExpansions); |
6723 | |
6724 | /// \brief Construct a pack expansion type from the pattern of the pack |
6725 | /// expansion. |
6726 | QualType CheckPackExpansion(QualType Pattern, |
6727 | SourceRange PatternRange, |
6728 | SourceLocation EllipsisLoc, |
6729 | Optional<unsigned> NumExpansions); |
6730 | |
6731 | /// \brief Invoked when parsing an expression followed by an ellipsis, which |
6732 | /// creates a pack expansion. |
6733 | /// |
6734 | /// \param Pattern The expression preceding the ellipsis, which will become |
6735 | /// the pattern of the pack expansion. |
6736 | /// |
6737 | /// \param EllipsisLoc The location of the ellipsis. |
6738 | ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); |
6739 | |
6740 | /// \brief Invoked when parsing an expression followed by an ellipsis, which |
6741 | /// creates a pack expansion. |
6742 | /// |
6743 | /// \param Pattern The expression preceding the ellipsis, which will become |
6744 | /// the pattern of the pack expansion. |
6745 | /// |
6746 | /// \param EllipsisLoc The location of the ellipsis. |
6747 | ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, |
6748 | Optional<unsigned> NumExpansions); |
6749 | |
6750 | /// \brief Determine whether we could expand a pack expansion with the |
6751 | /// given set of parameter packs into separate arguments by repeatedly |
6752 | /// transforming the pattern. |
6753 | /// |
6754 | /// \param EllipsisLoc The location of the ellipsis that identifies the |
6755 | /// pack expansion. |
6756 | /// |
6757 | /// \param PatternRange The source range that covers the entire pattern of |
6758 | /// the pack expansion. |
6759 | /// |
6760 | /// \param Unexpanded The set of unexpanded parameter packs within the |
6761 | /// pattern. |
6762 | /// |
6763 | /// \param ShouldExpand Will be set to \c true if the transformer should |
6764 | /// expand the corresponding pack expansions into separate arguments. When |
6765 | /// set, \c NumExpansions must also be set. |
6766 | /// |
6767 | /// \param RetainExpansion Whether the caller should add an unexpanded |
6768 | /// pack expansion after all of the expanded arguments. This is used |
6769 | /// when extending explicitly-specified template argument packs per |
6770 | /// C++0x [temp.arg.explicit]p9. |
6771 | /// |
6772 | /// \param NumExpansions The number of separate arguments that will be in |
6773 | /// the expanded form of the corresponding pack expansion. This is both an |
6774 | /// input and an output parameter, which can be set by the caller if the |
6775 | /// number of expansions is known a priori (e.g., due to a prior substitution) |
6776 | /// and will be set by the callee when the number of expansions is known. |
6777 | /// The callee must set this value when \c ShouldExpand is \c true; it may |
6778 | /// set this value in other cases. |
6779 | /// |
6780 | /// \returns true if an error occurred (e.g., because the parameter packs |
6781 | /// are to be instantiated with arguments of different lengths), false |
6782 | /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) |
6783 | /// must be set. |
6784 | bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, |
6785 | SourceRange PatternRange, |
6786 | ArrayRef<UnexpandedParameterPack> Unexpanded, |
6787 | const MultiLevelTemplateArgumentList &TemplateArgs, |
6788 | bool &ShouldExpand, |
6789 | bool &RetainExpansion, |
6790 | Optional<unsigned> &NumExpansions); |
6791 | |
6792 | /// \brief Determine the number of arguments in the given pack expansion |
6793 | /// type. |
6794 | /// |
6795 | /// This routine assumes that the number of arguments in the expansion is |
6796 | /// consistent across all of the unexpanded parameter packs in its pattern. |
6797 | /// |
6798 | /// Returns an empty Optional if the type can't be expanded. |
6799 | Optional<unsigned> getNumArgumentsInExpansion(QualType T, |
6800 | const MultiLevelTemplateArgumentList &TemplateArgs); |
6801 | |
6802 | /// \brief Determine whether the given declarator contains any unexpanded |
6803 | /// parameter packs. |
6804 | /// |
6805 | /// This routine is used by the parser to disambiguate function declarators |
6806 | /// with an ellipsis prior to the ')', e.g., |
6807 | /// |
6808 | /// \code |
6809 | /// void f(T...); |
6810 | /// \endcode |
6811 | /// |
6812 | /// To determine whether we have an (unnamed) function parameter pack or |
6813 | /// a variadic function. |
6814 | /// |
6815 | /// \returns true if the declarator contains any unexpanded parameter packs, |
6816 | /// false otherwise. |
6817 | bool containsUnexpandedParameterPacks(Declarator &D); |
6818 | |
6819 | /// \brief Returns the pattern of the pack expansion for a template argument. |
6820 | /// |
6821 | /// \param OrigLoc The template argument to expand. |
6822 | /// |
6823 | /// \param Ellipsis Will be set to the location of the ellipsis. |
6824 | /// |
6825 | /// \param NumExpansions Will be set to the number of expansions that will |
6826 | /// be generated from this pack expansion, if known a priori. |
6827 | TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( |
6828 | TemplateArgumentLoc OrigLoc, |
6829 | SourceLocation &Ellipsis, |
6830 | Optional<unsigned> &NumExpansions) const; |
6831 | |
6832 | /// Given a template argument that contains an unexpanded parameter pack, but |
6833 | /// which has already been substituted, attempt to determine the number of |
6834 | /// elements that will be produced once this argument is fully-expanded. |
6835 | /// |
6836 | /// This is intended for use when transforming 'sizeof...(Arg)' in order to |
6837 | /// avoid actually expanding the pack where possible. |
6838 | Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); |
6839 | |
6840 | //===--------------------------------------------------------------------===// |
6841 | // C++ Template Argument Deduction (C++ [temp.deduct]) |
6842 | //===--------------------------------------------------------------------===// |
6843 | |
6844 | /// Adjust the type \p ArgFunctionType to match the calling convention, |
6845 | /// noreturn, and optionally the exception specification of \p FunctionType. |
6846 | /// Deduction often wants to ignore these properties when matching function |
6847 | /// types. |
6848 | QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, |
6849 | bool AdjustExceptionSpec = false); |
6850 | |
6851 | /// \brief Describes the result of template argument deduction. |
6852 | /// |
6853 | /// The TemplateDeductionResult enumeration describes the result of |
6854 | /// template argument deduction, as returned from |
6855 | /// DeduceTemplateArguments(). The separate TemplateDeductionInfo |
6856 | /// structure provides additional information about the results of |
6857 | /// template argument deduction, e.g., the deduced template argument |
6858 | /// list (if successful) or the specific template parameters or |
6859 | /// deduced arguments that were involved in the failure. |
6860 | enum TemplateDeductionResult { |
6861 | /// \brief Template argument deduction was successful. |
6862 | TDK_Success = 0, |
6863 | /// \brief The declaration was invalid; do nothing. |
6864 | TDK_Invalid, |
6865 | /// \brief Template argument deduction exceeded the maximum template |
6866 | /// instantiation depth (which has already been diagnosed). |
6867 | TDK_InstantiationDepth, |
6868 | /// \brief Template argument deduction did not deduce a value |
6869 | /// for every template parameter. |
6870 | TDK_Incomplete, |
6871 | /// \brief Template argument deduction produced inconsistent |
6872 | /// deduced values for the given template parameter. |
6873 | TDK_Inconsistent, |
6874 | /// \brief Template argument deduction failed due to inconsistent |
6875 | /// cv-qualifiers on a template parameter type that would |
6876 | /// otherwise be deduced, e.g., we tried to deduce T in "const T" |
6877 | /// but were given a non-const "X". |
6878 | TDK_Underqualified, |
6879 | /// \brief Substitution of the deduced template argument values |
6880 | /// resulted in an error. |
6881 | TDK_SubstitutionFailure, |
6882 | /// \brief After substituting deduced template arguments, a dependent |
6883 | /// parameter type did not match the corresponding argument. |
6884 | TDK_DeducedMismatch, |
6885 | /// \brief After substituting deduced template arguments, an element of |
6886 | /// a dependent parameter type did not match the corresponding element |
6887 | /// of the corresponding argument (when deducing from an initializer list). |
6888 | TDK_DeducedMismatchNested, |
6889 | /// \brief A non-depnedent component of the parameter did not match the |
6890 | /// corresponding component of the argument. |
6891 | TDK_NonDeducedMismatch, |
6892 | /// \brief When performing template argument deduction for a function |
6893 | /// template, there were too many call arguments. |
6894 | TDK_TooManyArguments, |
6895 | /// \brief When performing template argument deduction for a function |
6896 | /// template, there were too few call arguments. |
6897 | TDK_TooFewArguments, |
6898 | /// \brief The explicitly-specified template arguments were not valid |
6899 | /// template arguments for the given template. |
6900 | TDK_InvalidExplicitArguments, |
6901 | /// \brief Checking non-dependent argument conversions failed. |
6902 | TDK_NonDependentConversionFailure, |
6903 | /// \brief Deduction failed; that's all we know. |
6904 | TDK_MiscellaneousDeductionFailure, |
6905 | /// \brief CUDA Target attributes do not match. |
6906 | TDK_CUDATargetMismatch |
6907 | }; |
6908 | |
6909 | TemplateDeductionResult |
6910 | DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, |
6911 | const TemplateArgumentList &TemplateArgs, |
6912 | sema::TemplateDeductionInfo &Info); |
6913 | |
6914 | TemplateDeductionResult |
6915 | DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, |
6916 | const TemplateArgumentList &TemplateArgs, |
6917 | sema::TemplateDeductionInfo &Info); |
6918 | |
6919 | TemplateDeductionResult SubstituteExplicitTemplateArguments( |
6920 | FunctionTemplateDecl *FunctionTemplate, |
6921 | TemplateArgumentListInfo &ExplicitTemplateArgs, |
6922 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
6923 | SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, |
6924 | sema::TemplateDeductionInfo &Info); |
6925 | |
6926 | /// brief A function argument from which we performed template argument |
6927 | // deduction for a call. |
6928 | struct OriginalCallArg { |
6929 | OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, |
6930 | unsigned ArgIdx, QualType OriginalArgType) |
6931 | : OriginalParamType(OriginalParamType), |
6932 | DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), |
6933 | OriginalArgType(OriginalArgType) {} |
6934 | |
6935 | QualType OriginalParamType; |
6936 | bool DecomposedParam; |
6937 | unsigned ArgIdx; |
6938 | QualType OriginalArgType; |
6939 | }; |
6940 | |
6941 | TemplateDeductionResult FinishTemplateArgumentDeduction( |
6942 | FunctionTemplateDecl *FunctionTemplate, |
6943 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, |
6944 | unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, |
6945 | sema::TemplateDeductionInfo &Info, |
6946 | SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, |
6947 | bool PartialOverloading = false, |
6948 | llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); |
6949 | |
6950 | TemplateDeductionResult DeduceTemplateArguments( |
6951 | FunctionTemplateDecl *FunctionTemplate, |
6952 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, |
6953 | FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, |
6954 | bool PartialOverloading, |
6955 | llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); |
6956 | |
6957 | TemplateDeductionResult |
6958 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, |
6959 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
6960 | QualType ArgFunctionType, |
6961 | FunctionDecl *&Specialization, |
6962 | sema::TemplateDeductionInfo &Info, |
6963 | bool IsAddressOfFunction = false); |
6964 | |
6965 | TemplateDeductionResult |
6966 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, |
6967 | QualType ToType, |
6968 | CXXConversionDecl *&Specialization, |
6969 | sema::TemplateDeductionInfo &Info); |
6970 | |
6971 | TemplateDeductionResult |
6972 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, |
6973 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
6974 | FunctionDecl *&Specialization, |
6975 | sema::TemplateDeductionInfo &Info, |
6976 | bool IsAddressOfFunction = false); |
6977 | |
6978 | /// \brief Substitute Replacement for \p auto in \p TypeWithAuto |
6979 | QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); |
6980 | /// \brief Substitute Replacement for auto in TypeWithAuto |
6981 | TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, |
6982 | QualType Replacement); |
6983 | /// \brief Completely replace the \c auto in \p TypeWithAuto by |
6984 | /// \p Replacement. This does not retain any \c auto type sugar. |
6985 | QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); |
6986 | |
6987 | /// \brief Result type of DeduceAutoType. |
6988 | enum DeduceAutoResult { |
6989 | DAR_Succeeded, |
6990 | DAR_Failed, |
6991 | DAR_FailedAlreadyDiagnosed |
6992 | }; |
6993 | |
6994 | DeduceAutoResult |
6995 | DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, |
6996 | Optional<unsigned> DependentDeductionDepth = None); |
6997 | DeduceAutoResult |
6998 | DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, |
6999 | Optional<unsigned> DependentDeductionDepth = None); |
7000 | void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); |
7001 | bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, |
7002 | bool Diagnose = true); |
7003 | |
7004 | /// \brief Declare implicit deduction guides for a class template if we've |
7005 | /// not already done so. |
7006 | void DeclareImplicitDeductionGuides(TemplateDecl *Template, |
7007 | SourceLocation Loc); |
7008 | |
7009 | QualType DeduceTemplateSpecializationFromInitializer( |
7010 | TypeSourceInfo *TInfo, const InitializedEntity &Entity, |
7011 | const InitializationKind &Kind, MultiExprArg Init); |
7012 | |
7013 | QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, |
7014 | QualType Type, TypeSourceInfo *TSI, |
7015 | SourceRange Range, bool DirectInit, |
7016 | Expr *Init); |
7017 | |
7018 | TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; |
7019 | |
7020 | bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, |
7021 | SourceLocation ReturnLoc, |
7022 | Expr *&RetExpr, AutoType *AT); |
7023 | |
7024 | FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, |
7025 | FunctionTemplateDecl *FT2, |
7026 | SourceLocation Loc, |
7027 | TemplatePartialOrderingContext TPOC, |
7028 | unsigned NumCallArguments1, |
7029 | unsigned NumCallArguments2); |
7030 | UnresolvedSetIterator |
7031 | getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, |
7032 | TemplateSpecCandidateSet &FailedCandidates, |
7033 | SourceLocation Loc, |
7034 | const PartialDiagnostic &NoneDiag, |
7035 | const PartialDiagnostic &AmbigDiag, |
7036 | const PartialDiagnostic &CandidateDiag, |
7037 | bool Complain = true, QualType TargetType = QualType()); |
7038 | |
7039 | ClassTemplatePartialSpecializationDecl * |
7040 | getMoreSpecializedPartialSpecialization( |
7041 | ClassTemplatePartialSpecializationDecl *PS1, |
7042 | ClassTemplatePartialSpecializationDecl *PS2, |
7043 | SourceLocation Loc); |
7044 | |
7045 | bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, |
7046 | sema::TemplateDeductionInfo &Info); |
7047 | |
7048 | VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( |
7049 | VarTemplatePartialSpecializationDecl *PS1, |
7050 | VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); |
7051 | |
7052 | bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, |
7053 | sema::TemplateDeductionInfo &Info); |
7054 | |
7055 | bool isTemplateTemplateParameterAtLeastAsSpecializedAs( |
7056 | TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc); |
7057 | |
7058 | void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, |
7059 | bool OnlyDeduced, |
7060 | unsigned Depth, |
7061 | llvm::SmallBitVector &Used); |
7062 | void MarkDeducedTemplateParameters( |
7063 | const FunctionTemplateDecl *FunctionTemplate, |
7064 | llvm::SmallBitVector &Deduced) { |
7065 | return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); |
7066 | } |
7067 | static void MarkDeducedTemplateParameters(ASTContext &Ctx, |
7068 | const FunctionTemplateDecl *FunctionTemplate, |
7069 | llvm::SmallBitVector &Deduced); |
7070 | |
7071 | //===--------------------------------------------------------------------===// |
7072 | // C++ Template Instantiation |
7073 | // |
7074 | |
7075 | MultiLevelTemplateArgumentList |
7076 | getTemplateInstantiationArgs(NamedDecl *D, |
7077 | const TemplateArgumentList *Innermost = nullptr, |
7078 | bool RelativeToPrimary = false, |
7079 | const FunctionDecl *Pattern = nullptr); |
7080 | |
7081 | /// A context in which code is being synthesized (where a source location |
7082 | /// alone is not sufficient to identify the context). This covers template |
7083 | /// instantiation and various forms of implicitly-generated functions. |
7084 | struct CodeSynthesisContext { |
7085 | /// \brief The kind of template instantiation we are performing |
7086 | enum SynthesisKind { |
7087 | /// We are instantiating a template declaration. The entity is |
7088 | /// the declaration we're instantiating (e.g., a CXXRecordDecl). |
7089 | TemplateInstantiation, |
7090 | |
7091 | /// We are instantiating a default argument for a template |
7092 | /// parameter. The Entity is the template parameter whose argument is |
7093 | /// being instantiated, the Template is the template, and the |
7094 | /// TemplateArgs/NumTemplateArguments provide the template arguments as |
7095 | /// specified. |
7096 | DefaultTemplateArgumentInstantiation, |
7097 | |
7098 | /// We are instantiating a default argument for a function. |
7099 | /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs |
7100 | /// provides the template arguments as specified. |
7101 | DefaultFunctionArgumentInstantiation, |
7102 | |
7103 | /// We are substituting explicit template arguments provided for |
7104 | /// a function template. The entity is a FunctionTemplateDecl. |
7105 | ExplicitTemplateArgumentSubstitution, |
7106 | |
7107 | /// We are substituting template argument determined as part of |
7108 | /// template argument deduction for either a class template |
7109 | /// partial specialization or a function template. The |
7110 | /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or |
7111 | /// a TemplateDecl. |
7112 | DeducedTemplateArgumentSubstitution, |
7113 | |
7114 | /// We are substituting prior template arguments into a new |
7115 | /// template parameter. The template parameter itself is either a |
7116 | /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. |
7117 | PriorTemplateArgumentSubstitution, |
7118 | |
7119 | /// We are checking the validity of a default template argument that |
7120 | /// has been used when naming a template-id. |
7121 | DefaultTemplateArgumentChecking, |
7122 | |
7123 | /// We are instantiating the exception specification for a function |
7124 | /// template which was deferred until it was needed. |
7125 | ExceptionSpecInstantiation, |
7126 | |
7127 | /// We are declaring an implicit special member function. |
7128 | DeclaringSpecialMember, |
7129 | |
7130 | /// We are defining a synthesized function (such as a defaulted special |
7131 | /// member). |
7132 | DefiningSynthesizedFunction, |
7133 | |
7134 | /// Added for Template instantiation observation. |
7135 | /// Memoization means we are _not_ instantiating a template because |
7136 | /// it is already instantiated (but we entered a context where we |
7137 | /// would have had to if it was not already instantiated). |
7138 | Memoization |
7139 | } Kind; |
7140 | |
7141 | /// \brief Was the enclosing context a non-instantiation SFINAE context? |
7142 | bool SavedInNonInstantiationSFINAEContext; |
7143 | |
7144 | /// \brief The point of instantiation or synthesis within the source code. |
7145 | SourceLocation PointOfInstantiation; |
7146 | |
7147 | /// \brief The entity that is being synthesized. |
7148 | Decl *Entity; |
7149 | |
7150 | /// \brief The template (or partial specialization) in which we are |
7151 | /// performing the instantiation, for substitutions of prior template |
7152 | /// arguments. |
7153 | NamedDecl *Template; |
7154 | |
7155 | /// \brief The list of template arguments we are substituting, if they |
7156 | /// are not part of the entity. |
7157 | const TemplateArgument *TemplateArgs; |
7158 | |
7159 | // FIXME: Wrap this union around more members, or perhaps store the |
7160 | // kind-specific members in the RAII object owning the context. |
7161 | union { |
7162 | /// \brief The number of template arguments in TemplateArgs. |
7163 | unsigned NumTemplateArgs; |
7164 | |
7165 | /// \brief The special member being declared or defined. |
7166 | CXXSpecialMember SpecialMember; |
7167 | }; |
7168 | |
7169 | ArrayRef<TemplateArgument> template_arguments() const { |
7170 | assert(Kind != DeclaringSpecialMember)(static_cast <bool> (Kind != DeclaringSpecialMember) ? void (0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7170, __extension__ __PRETTY_FUNCTION__)); |
7171 | return {TemplateArgs, NumTemplateArgs}; |
7172 | } |
7173 | |
7174 | /// \brief The template deduction info object associated with the |
7175 | /// substitution or checking of explicit or deduced template arguments. |
7176 | sema::TemplateDeductionInfo *DeductionInfo; |
7177 | |
7178 | /// \brief The source range that covers the construct that cause |
7179 | /// the instantiation, e.g., the template-id that causes a class |
7180 | /// template instantiation. |
7181 | SourceRange InstantiationRange; |
7182 | |
7183 | CodeSynthesisContext() |
7184 | : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr), |
7185 | TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} |
7186 | |
7187 | /// \brief Determines whether this template is an actual instantiation |
7188 | /// that should be counted toward the maximum instantiation depth. |
7189 | bool isInstantiationRecord() const; |
7190 | }; |
7191 | |
7192 | /// \brief List of active code synthesis contexts. |
7193 | /// |
7194 | /// This vector is treated as a stack. As synthesis of one entity requires |
7195 | /// synthesis of another, additional contexts are pushed onto the stack. |
7196 | SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; |
7197 | |
7198 | /// Specializations whose definitions are currently being instantiated. |
7199 | llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; |
7200 | |
7201 | /// Non-dependent types used in templates that have already been instantiated |
7202 | /// by some template instantiation. |
7203 | llvm::DenseSet<QualType> InstantiatedNonDependentTypes; |
7204 | |
7205 | /// \brief Extra modules inspected when performing a lookup during a template |
7206 | /// instantiation. Computed lazily. |
7207 | SmallVector<Module*, 16> CodeSynthesisContextLookupModules; |
7208 | |
7209 | /// \brief Cache of additional modules that should be used for name lookup |
7210 | /// within the current template instantiation. Computed lazily; use |
7211 | /// getLookupModules() to get a complete set. |
7212 | llvm::DenseSet<Module*> LookupModulesCache; |
7213 | |
7214 | /// \brief Get the set of additional modules that should be checked during |
7215 | /// name lookup. A module and its imports become visible when instanting a |
7216 | /// template defined within it. |
7217 | llvm::DenseSet<Module*> &getLookupModules(); |
7218 | |
7219 | /// \brief Map from the most recent declaration of a namespace to the most |
7220 | /// recent visible declaration of that namespace. |
7221 | llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; |
7222 | |
7223 | /// \brief Whether we are in a SFINAE context that is not associated with |
7224 | /// template instantiation. |
7225 | /// |
7226 | /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside |
7227 | /// of a template instantiation or template argument deduction. |
7228 | bool InNonInstantiationSFINAEContext; |
7229 | |
7230 | /// \brief The number of \p CodeSynthesisContexts that are not template |
7231 | /// instantiations and, therefore, should not be counted as part of the |
7232 | /// instantiation depth. |
7233 | /// |
7234 | /// When the instantiation depth reaches the user-configurable limit |
7235 | /// \p LangOptions::InstantiationDepth we will abort instantiation. |
7236 | // FIXME: Should we have a similar limit for other forms of synthesis? |
7237 | unsigned NonInstantiationEntries; |
7238 | |
7239 | /// \brief The depth of the context stack at the point when the most recent |
7240 | /// error or warning was produced. |
7241 | /// |
7242 | /// This value is used to suppress printing of redundant context stacks |
7243 | /// when there are multiple errors or warnings in the same instantiation. |
7244 | // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. |
7245 | unsigned LastEmittedCodeSynthesisContextDepth = 0; |
7246 | |
7247 | /// \brief The template instantiation callbacks to trace or track |
7248 | /// instantiations (objects can be chained). |
7249 | /// |
7250 | /// This callbacks is used to print, trace or track template |
7251 | /// instantiations as they are being constructed. |
7252 | std::vector<std::unique_ptr<TemplateInstantiationCallback>> |
7253 | TemplateInstCallbacks; |
7254 | |
7255 | /// \brief The current index into pack expansion arguments that will be |
7256 | /// used for substitution of parameter packs. |
7257 | /// |
7258 | /// The pack expansion index will be -1 to indicate that parameter packs |
7259 | /// should be instantiated as themselves. Otherwise, the index specifies |
7260 | /// which argument within the parameter pack will be used for substitution. |
7261 | int ArgumentPackSubstitutionIndex; |
7262 | |
7263 | /// \brief RAII object used to change the argument pack substitution index |
7264 | /// within a \c Sema object. |
7265 | /// |
7266 | /// See \c ArgumentPackSubstitutionIndex for more information. |
7267 | class ArgumentPackSubstitutionIndexRAII { |
7268 | Sema &Self; |
7269 | int OldSubstitutionIndex; |
7270 | |
7271 | public: |
7272 | ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) |
7273 | : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { |
7274 | Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; |
7275 | } |
7276 | |
7277 | ~ArgumentPackSubstitutionIndexRAII() { |
7278 | Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; |
7279 | } |
7280 | }; |
7281 | |
7282 | friend class ArgumentPackSubstitutionRAII; |
7283 | |
7284 | /// \brief For each declaration that involved template argument deduction, the |
7285 | /// set of diagnostics that were suppressed during that template argument |
7286 | /// deduction. |
7287 | /// |
7288 | /// FIXME: Serialize this structure to the AST file. |
7289 | typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > |
7290 | SuppressedDiagnosticsMap; |
7291 | SuppressedDiagnosticsMap SuppressedDiagnostics; |
7292 | |
7293 | /// \brief A stack object to be created when performing template |
7294 | /// instantiation. |
7295 | /// |
7296 | /// Construction of an object of type \c InstantiatingTemplate |
7297 | /// pushes the current instantiation onto the stack of active |
7298 | /// instantiations. If the size of this stack exceeds the maximum |
7299 | /// number of recursive template instantiations, construction |
7300 | /// produces an error and evaluates true. |
7301 | /// |
7302 | /// Destruction of this object will pop the named instantiation off |
7303 | /// the stack. |
7304 | struct InstantiatingTemplate { |
7305 | /// \brief Note that we are instantiating a class template, |
7306 | /// function template, variable template, alias template, |
7307 | /// or a member thereof. |
7308 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7309 | Decl *Entity, |
7310 | SourceRange InstantiationRange = SourceRange()); |
7311 | |
7312 | struct ExceptionSpecification {}; |
7313 | /// \brief Note that we are instantiating an exception specification |
7314 | /// of a function template. |
7315 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7316 | FunctionDecl *Entity, ExceptionSpecification, |
7317 | SourceRange InstantiationRange = SourceRange()); |
7318 | |
7319 | /// \brief Note that we are instantiating a default argument in a |
7320 | /// template-id. |
7321 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7322 | TemplateParameter Param, TemplateDecl *Template, |
7323 | ArrayRef<TemplateArgument> TemplateArgs, |
7324 | SourceRange InstantiationRange = SourceRange()); |
7325 | |
7326 | /// \brief Note that we are substituting either explicitly-specified or |
7327 | /// deduced template arguments during function template argument deduction. |
7328 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7329 | FunctionTemplateDecl *FunctionTemplate, |
7330 | ArrayRef<TemplateArgument> TemplateArgs, |
7331 | CodeSynthesisContext::SynthesisKind Kind, |
7332 | sema::TemplateDeductionInfo &DeductionInfo, |
7333 | SourceRange InstantiationRange = SourceRange()); |
7334 | |
7335 | /// \brief Note that we are instantiating as part of template |
7336 | /// argument deduction for a class template declaration. |
7337 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7338 | TemplateDecl *Template, |
7339 | ArrayRef<TemplateArgument> TemplateArgs, |
7340 | sema::TemplateDeductionInfo &DeductionInfo, |
7341 | SourceRange InstantiationRange = SourceRange()); |
7342 | |
7343 | /// \brief Note that we are instantiating as part of template |
7344 | /// argument deduction for a class template partial |
7345 | /// specialization. |
7346 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7347 | ClassTemplatePartialSpecializationDecl *PartialSpec, |
7348 | ArrayRef<TemplateArgument> TemplateArgs, |
7349 | sema::TemplateDeductionInfo &DeductionInfo, |
7350 | SourceRange InstantiationRange = SourceRange()); |
7351 | |
7352 | /// \brief Note that we are instantiating as part of template |
7353 | /// argument deduction for a variable template partial |
7354 | /// specialization. |
7355 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7356 | VarTemplatePartialSpecializationDecl *PartialSpec, |
7357 | ArrayRef<TemplateArgument> TemplateArgs, |
7358 | sema::TemplateDeductionInfo &DeductionInfo, |
7359 | SourceRange InstantiationRange = SourceRange()); |
7360 | |
7361 | /// \brief Note that we are instantiating a default argument for a function |
7362 | /// parameter. |
7363 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7364 | ParmVarDecl *Param, |
7365 | ArrayRef<TemplateArgument> TemplateArgs, |
7366 | SourceRange InstantiationRange = SourceRange()); |
7367 | |
7368 | /// \brief Note that we are substituting prior template arguments into a |
7369 | /// non-type parameter. |
7370 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7371 | NamedDecl *Template, |
7372 | NonTypeTemplateParmDecl *Param, |
7373 | ArrayRef<TemplateArgument> TemplateArgs, |
7374 | SourceRange InstantiationRange); |
7375 | |
7376 | /// \brief Note that we are substituting prior template arguments into a |
7377 | /// template template parameter. |
7378 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7379 | NamedDecl *Template, |
7380 | TemplateTemplateParmDecl *Param, |
7381 | ArrayRef<TemplateArgument> TemplateArgs, |
7382 | SourceRange InstantiationRange); |
7383 | |
7384 | /// \brief Note that we are checking the default template argument |
7385 | /// against the template parameter for a given template-id. |
7386 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, |
7387 | TemplateDecl *Template, |
7388 | NamedDecl *Param, |
7389 | ArrayRef<TemplateArgument> TemplateArgs, |
7390 | SourceRange InstantiationRange); |
7391 | |
7392 | |
7393 | /// \brief Note that we have finished instantiating this template. |
7394 | void Clear(); |
7395 | |
7396 | ~InstantiatingTemplate() { Clear(); } |
7397 | |
7398 | /// \brief Determines whether we have exceeded the maximum |
7399 | /// recursive template instantiations. |
7400 | bool isInvalid() const { return Invalid; } |
7401 | |
7402 | /// \brief Determine whether we are already instantiating this |
7403 | /// specialization in some surrounding active instantiation. |
7404 | bool isAlreadyInstantiating() const { return AlreadyInstantiating; } |
7405 | |
7406 | private: |
7407 | Sema &SemaRef; |
7408 | bool Invalid; |
7409 | bool AlreadyInstantiating; |
7410 | bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, |
7411 | SourceRange InstantiationRange); |
7412 | |
7413 | InstantiatingTemplate( |
7414 | Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, |
7415 | SourceLocation PointOfInstantiation, SourceRange InstantiationRange, |
7416 | Decl *Entity, NamedDecl *Template = nullptr, |
7417 | ArrayRef<TemplateArgument> TemplateArgs = None, |
7418 | sema::TemplateDeductionInfo *DeductionInfo = nullptr); |
7419 | |
7420 | InstantiatingTemplate(const InstantiatingTemplate&) = delete; |
7421 | |
7422 | InstantiatingTemplate& |
7423 | operator=(const InstantiatingTemplate&) = delete; |
7424 | }; |
7425 | |
7426 | void pushCodeSynthesisContext(CodeSynthesisContext Ctx); |
7427 | void popCodeSynthesisContext(); |
7428 | |
7429 | /// Determine whether we are currently performing template instantiation. |
7430 | bool inTemplateInstantiation() const { |
7431 | return CodeSynthesisContexts.size() > NonInstantiationEntries; |
7432 | } |
7433 | |
7434 | void PrintContextStack() { |
7435 | if (!CodeSynthesisContexts.empty() && |
7436 | CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { |
7437 | PrintInstantiationStack(); |
7438 | LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); |
7439 | } |
7440 | if (PragmaAttributeCurrentTargetDecl) |
7441 | PrintPragmaAttributeInstantiationPoint(); |
7442 | } |
7443 | void PrintInstantiationStack(); |
7444 | |
7445 | void PrintPragmaAttributeInstantiationPoint(); |
7446 | |
7447 | /// \brief Determines whether we are currently in a context where |
7448 | /// template argument substitution failures are not considered |
7449 | /// errors. |
7450 | /// |
7451 | /// \returns An empty \c Optional if we're not in a SFINAE context. |
7452 | /// Otherwise, contains a pointer that, if non-NULL, contains the nearest |
7453 | /// template-deduction context object, which can be used to capture |
7454 | /// diagnostics that will be suppressed. |
7455 | Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; |
7456 | |
7457 | /// \brief Determines whether we are currently in a context that |
7458 | /// is not evaluated as per C++ [expr] p5. |
7459 | bool isUnevaluatedContext() const { |
7460 | assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() && "Must be in an expression evaluation context") ? void (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7461, __extension__ __PRETTY_FUNCTION__)) |
7461 | "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() && "Must be in an expression evaluation context") ? void (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7461, __extension__ __PRETTY_FUNCTION__)); |
7462 | return ExprEvalContexts.back().isUnevaluated(); |
7463 | } |
7464 | |
7465 | /// \brief RAII class used to determine whether SFINAE has |
7466 | /// trapped any errors that occur during template argument |
7467 | /// deduction. |
7468 | class SFINAETrap { |
7469 | Sema &SemaRef; |
7470 | unsigned PrevSFINAEErrors; |
7471 | bool PrevInNonInstantiationSFINAEContext; |
7472 | bool PrevAccessCheckingSFINAE; |
7473 | bool PrevLastDiagnosticIgnored; |
7474 | |
7475 | public: |
7476 | explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) |
7477 | : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), |
7478 | PrevInNonInstantiationSFINAEContext( |
7479 | SemaRef.InNonInstantiationSFINAEContext), |
7480 | PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), |
7481 | PrevLastDiagnosticIgnored( |
7482 | SemaRef.getDiagnostics().isLastDiagnosticIgnored()) |
7483 | { |
7484 | if (!SemaRef.isSFINAEContext()) |
7485 | SemaRef.InNonInstantiationSFINAEContext = true; |
7486 | SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; |
7487 | } |
7488 | |
7489 | ~SFINAETrap() { |
7490 | SemaRef.NumSFINAEErrors = PrevSFINAEErrors; |
7491 | SemaRef.InNonInstantiationSFINAEContext |
7492 | = PrevInNonInstantiationSFINAEContext; |
7493 | SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; |
7494 | SemaRef.getDiagnostics().setLastDiagnosticIgnored( |
7495 | PrevLastDiagnosticIgnored); |
7496 | } |
7497 | |
7498 | /// \brief Determine whether any SFINAE errors have been trapped. |
7499 | bool hasErrorOccurred() const { |
7500 | return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; |
7501 | } |
7502 | }; |
7503 | |
7504 | /// \brief RAII class used to indicate that we are performing provisional |
7505 | /// semantic analysis to determine the validity of a construct, so |
7506 | /// typo-correction and diagnostics in the immediate context (not within |
7507 | /// implicitly-instantiated templates) should be suppressed. |
7508 | class TentativeAnalysisScope { |
7509 | Sema &SemaRef; |
7510 | // FIXME: Using a SFINAETrap for this is a hack. |
7511 | SFINAETrap Trap; |
7512 | bool PrevDisableTypoCorrection; |
7513 | public: |
7514 | explicit TentativeAnalysisScope(Sema &SemaRef) |
7515 | : SemaRef(SemaRef), Trap(SemaRef, true), |
7516 | PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { |
7517 | SemaRef.DisableTypoCorrection = true; |
7518 | } |
7519 | ~TentativeAnalysisScope() { |
7520 | SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; |
7521 | } |
7522 | }; |
7523 | |
7524 | /// \brief The current instantiation scope used to store local |
7525 | /// variables. |
7526 | LocalInstantiationScope *CurrentInstantiationScope; |
7527 | |
7528 | /// \brief Tracks whether we are in a context where typo correction is |
7529 | /// disabled. |
7530 | bool DisableTypoCorrection; |
7531 | |
7532 | /// \brief The number of typos corrected by CorrectTypo. |
7533 | unsigned TyposCorrected; |
7534 | |
7535 | typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; |
7536 | typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; |
7537 | |
7538 | /// \brief A cache containing identifiers for which typo correction failed and |
7539 | /// their locations, so that repeated attempts to correct an identifier in a |
7540 | /// given location are ignored if typo correction already failed for it. |
7541 | IdentifierSourceLocations TypoCorrectionFailures; |
7542 | |
7543 | /// \brief Worker object for performing CFG-based warnings. |
7544 | sema::AnalysisBasedWarnings AnalysisWarnings; |
7545 | threadSafety::BeforeSet *ThreadSafetyDeclCache; |
7546 | |
7547 | /// \brief An entity for which implicit template instantiation is required. |
7548 | /// |
7549 | /// The source location associated with the declaration is the first place in |
7550 | /// the source code where the declaration was "used". It is not necessarily |
7551 | /// the point of instantiation (which will be either before or after the |
7552 | /// namespace-scope declaration that triggered this implicit instantiation), |
7553 | /// However, it is the location that diagnostics should generally refer to, |
7554 | /// because users will need to know what code triggered the instantiation. |
7555 | typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; |
7556 | |
7557 | /// \brief The queue of implicit template instantiations that are required |
7558 | /// but have not yet been performed. |
7559 | std::deque<PendingImplicitInstantiation> PendingInstantiations; |
7560 | |
7561 | class GlobalEagerInstantiationScope { |
7562 | public: |
7563 | GlobalEagerInstantiationScope(Sema &S, bool Enabled) |
7564 | : S(S), Enabled(Enabled) { |
7565 | if (!Enabled) return; |
7566 | |
7567 | SavedPendingInstantiations.swap(S.PendingInstantiations); |
7568 | SavedVTableUses.swap(S.VTableUses); |
7569 | } |
7570 | |
7571 | void perform() { |
7572 | if (Enabled) { |
7573 | S.DefineUsedVTables(); |
7574 | S.PerformPendingInstantiations(); |
7575 | } |
7576 | } |
7577 | |
7578 | ~GlobalEagerInstantiationScope() { |
7579 | if (!Enabled) return; |
7580 | |
7581 | // Restore the set of pending vtables. |
7582 | assert(S.VTableUses.empty() &&(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded." ) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7583, __extension__ __PRETTY_FUNCTION__)) |
7583 | "VTableUses should be empty before it is discarded.")(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded." ) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7583, __extension__ __PRETTY_FUNCTION__)); |
7584 | S.VTableUses.swap(SavedVTableUses); |
7585 | |
7586 | // Restore the set of pending implicit instantiations. |
7587 | assert(S.PendingInstantiations.empty() &&(static_cast <bool> (S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded." ) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7588, __extension__ __PRETTY_FUNCTION__)) |
7588 | "PendingInstantiations should be empty before it is discarded.")(static_cast <bool> (S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded." ) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7588, __extension__ __PRETTY_FUNCTION__)); |
7589 | S.PendingInstantiations.swap(SavedPendingInstantiations); |
7590 | } |
7591 | |
7592 | private: |
7593 | Sema &S; |
7594 | SmallVector<VTableUse, 16> SavedVTableUses; |
7595 | std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; |
7596 | bool Enabled; |
7597 | }; |
7598 | |
7599 | /// \brief The queue of implicit template instantiations that are required |
7600 | /// and must be performed within the current local scope. |
7601 | /// |
7602 | /// This queue is only used for member functions of local classes in |
7603 | /// templates, which must be instantiated in the same scope as their |
7604 | /// enclosing function, so that they can reference function-local |
7605 | /// types, static variables, enumerators, etc. |
7606 | std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; |
7607 | |
7608 | class LocalEagerInstantiationScope { |
7609 | public: |
7610 | LocalEagerInstantiationScope(Sema &S) : S(S) { |
7611 | SavedPendingLocalImplicitInstantiations.swap( |
7612 | S.PendingLocalImplicitInstantiations); |
7613 | } |
7614 | |
7615 | void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } |
7616 | |
7617 | ~LocalEagerInstantiationScope() { |
7618 | assert(S.PendingLocalImplicitInstantiations.empty() &&(static_cast <bool> (S.PendingLocalImplicitInstantiations .empty() && "there shouldn't be any pending local implicit instantiations" ) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7619, __extension__ __PRETTY_FUNCTION__)) |
7619 | "there shouldn't be any pending local implicit instantiations")(static_cast <bool> (S.PendingLocalImplicitInstantiations .empty() && "there shouldn't be any pending local implicit instantiations" ) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7619, __extension__ __PRETTY_FUNCTION__)); |
7620 | SavedPendingLocalImplicitInstantiations.swap( |
7621 | S.PendingLocalImplicitInstantiations); |
7622 | } |
7623 | |
7624 | private: |
7625 | Sema &S; |
7626 | std::deque<PendingImplicitInstantiation> |
7627 | SavedPendingLocalImplicitInstantiations; |
7628 | }; |
7629 | |
7630 | /// A helper class for building up ExtParameterInfos. |
7631 | class ExtParameterInfoBuilder { |
7632 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; |
7633 | bool HasInteresting = false; |
7634 | |
7635 | public: |
7636 | /// Set the ExtParameterInfo for the parameter at the given index, |
7637 | /// |
7638 | void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { |
7639 | assert(Infos.size() <= index)(static_cast <bool> (Infos.size() <= index) ? void ( 0) : __assert_fail ("Infos.size() <= index", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 7639, __extension__ __PRETTY_FUNCTION__)); |
7640 | Infos.resize(index); |
7641 | Infos.push_back(info); |
7642 | |
7643 | if (!HasInteresting) |
7644 | HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); |
7645 | } |
7646 | |
7647 | /// Return a pointer (suitable for setting in an ExtProtoInfo) to the |
7648 | /// ExtParameterInfo array we've built up. |
7649 | const FunctionProtoType::ExtParameterInfo * |
7650 | getPointerOrNull(unsigned numParams) { |
7651 | if (!HasInteresting) return nullptr; |
7652 | Infos.resize(numParams); |
7653 | return Infos.data(); |
7654 | } |
7655 | }; |
7656 | |
7657 | void PerformPendingInstantiations(bool LocalOnly = false); |
7658 | |
7659 | TypeSourceInfo *SubstType(TypeSourceInfo *T, |
7660 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7661 | SourceLocation Loc, DeclarationName Entity, |
7662 | bool AllowDeducedTST = false); |
7663 | |
7664 | QualType SubstType(QualType T, |
7665 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7666 | SourceLocation Loc, DeclarationName Entity); |
7667 | |
7668 | TypeSourceInfo *SubstType(TypeLoc TL, |
7669 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7670 | SourceLocation Loc, DeclarationName Entity); |
7671 | |
7672 | TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, |
7673 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7674 | SourceLocation Loc, |
7675 | DeclarationName Entity, |
7676 | CXXRecordDecl *ThisContext, |
7677 | unsigned ThisTypeQuals); |
7678 | void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, |
7679 | const MultiLevelTemplateArgumentList &Args); |
7680 | bool SubstExceptionSpec(SourceLocation Loc, |
7681 | FunctionProtoType::ExceptionSpecInfo &ESI, |
7682 | SmallVectorImpl<QualType> &ExceptionStorage, |
7683 | const MultiLevelTemplateArgumentList &Args); |
7684 | ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, |
7685 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7686 | int indexAdjustment, |
7687 | Optional<unsigned> NumExpansions, |
7688 | bool ExpectParameterPack); |
7689 | bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, |
7690 | const FunctionProtoType::ExtParameterInfo *ExtParamInfos, |
7691 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7692 | SmallVectorImpl<QualType> &ParamTypes, |
7693 | SmallVectorImpl<ParmVarDecl *> *OutParams, |
7694 | ExtParameterInfoBuilder &ParamInfos); |
7695 | ExprResult SubstExpr(Expr *E, |
7696 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7697 | |
7698 | /// \brief Substitute the given template arguments into a list of |
7699 | /// expressions, expanding pack expansions if required. |
7700 | /// |
7701 | /// \param Exprs The list of expressions to substitute into. |
7702 | /// |
7703 | /// \param IsCall Whether this is some form of call, in which case |
7704 | /// default arguments will be dropped. |
7705 | /// |
7706 | /// \param TemplateArgs The set of template arguments to substitute. |
7707 | /// |
7708 | /// \param Outputs Will receive all of the substituted arguments. |
7709 | /// |
7710 | /// \returns true if an error occurred, false otherwise. |
7711 | bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, |
7712 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7713 | SmallVectorImpl<Expr *> &Outputs); |
7714 | |
7715 | StmtResult SubstStmt(Stmt *S, |
7716 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7717 | |
7718 | Decl *SubstDecl(Decl *D, DeclContext *Owner, |
7719 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7720 | |
7721 | ExprResult SubstInitializer(Expr *E, |
7722 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7723 | bool CXXDirectInit); |
7724 | |
7725 | bool |
7726 | SubstBaseSpecifiers(CXXRecordDecl *Instantiation, |
7727 | CXXRecordDecl *Pattern, |
7728 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7729 | |
7730 | bool |
7731 | InstantiateClass(SourceLocation PointOfInstantiation, |
7732 | CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, |
7733 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7734 | TemplateSpecializationKind TSK, |
7735 | bool Complain = true); |
7736 | |
7737 | bool InstantiateEnum(SourceLocation PointOfInstantiation, |
7738 | EnumDecl *Instantiation, EnumDecl *Pattern, |
7739 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7740 | TemplateSpecializationKind TSK); |
7741 | |
7742 | bool InstantiateInClassInitializer( |
7743 | SourceLocation PointOfInstantiation, FieldDecl *Instantiation, |
7744 | FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); |
7745 | |
7746 | struct LateInstantiatedAttribute { |
7747 | const Attr *TmplAttr; |
7748 | LocalInstantiationScope *Scope; |
7749 | Decl *NewDecl; |
7750 | |
7751 | LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, |
7752 | Decl *D) |
7753 | : TmplAttr(A), Scope(S), NewDecl(D) |
7754 | { } |
7755 | }; |
7756 | typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; |
7757 | |
7758 | void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, |
7759 | const Decl *Pattern, Decl *Inst, |
7760 | LateInstantiatedAttrVec *LateAttrs = nullptr, |
7761 | LocalInstantiationScope *OuterMostScope = nullptr); |
7762 | |
7763 | void |
7764 | InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, |
7765 | const Decl *Pattern, Decl *Inst, |
7766 | LateInstantiatedAttrVec *LateAttrs = nullptr, |
7767 | LocalInstantiationScope *OuterMostScope = nullptr); |
7768 | |
7769 | bool usesPartialOrExplicitSpecialization( |
7770 | SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); |
7771 | |
7772 | bool |
7773 | InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, |
7774 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
7775 | TemplateSpecializationKind TSK, |
7776 | bool Complain = true); |
7777 | |
7778 | void InstantiateClassMembers(SourceLocation PointOfInstantiation, |
7779 | CXXRecordDecl *Instantiation, |
7780 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7781 | TemplateSpecializationKind TSK); |
7782 | |
7783 | void InstantiateClassTemplateSpecializationMembers( |
7784 | SourceLocation PointOfInstantiation, |
7785 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
7786 | TemplateSpecializationKind TSK); |
7787 | |
7788 | NestedNameSpecifierLoc |
7789 | SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, |
7790 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7791 | |
7792 | DeclarationNameInfo |
7793 | SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, |
7794 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7795 | TemplateName |
7796 | SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, |
7797 | SourceLocation Loc, |
7798 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7799 | bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, |
7800 | TemplateArgumentListInfo &Result, |
7801 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7802 | |
7803 | void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, |
7804 | FunctionDecl *Function); |
7805 | FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, |
7806 | const TemplateArgumentList *Args, |
7807 | SourceLocation Loc); |
7808 | void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, |
7809 | FunctionDecl *Function, |
7810 | bool Recursive = false, |
7811 | bool DefinitionRequired = false, |
7812 | bool AtEndOfTU = false); |
7813 | VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( |
7814 | VarTemplateDecl *VarTemplate, VarDecl *FromVar, |
7815 | const TemplateArgumentList &TemplateArgList, |
7816 | const TemplateArgumentListInfo &TemplateArgsInfo, |
7817 | SmallVectorImpl<TemplateArgument> &Converted, |
7818 | SourceLocation PointOfInstantiation, void *InsertPos, |
7819 | LateInstantiatedAttrVec *LateAttrs = nullptr, |
7820 | LocalInstantiationScope *StartingScope = nullptr); |
7821 | VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( |
7822 | VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, |
7823 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7824 | void |
7825 | BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, |
7826 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7827 | LateInstantiatedAttrVec *LateAttrs, |
7828 | DeclContext *Owner, |
7829 | LocalInstantiationScope *StartingScope, |
7830 | bool InstantiatingVarTemplate = false); |
7831 | void InstantiateVariableInitializer( |
7832 | VarDecl *Var, VarDecl *OldVar, |
7833 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7834 | void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, |
7835 | VarDecl *Var, bool Recursive = false, |
7836 | bool DefinitionRequired = false, |
7837 | bool AtEndOfTU = false); |
7838 | |
7839 | void InstantiateMemInitializers(CXXConstructorDecl *New, |
7840 | const CXXConstructorDecl *Tmpl, |
7841 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7842 | |
7843 | NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, |
7844 | const MultiLevelTemplateArgumentList &TemplateArgs, |
7845 | bool FindingInstantiatedContext = false); |
7846 | DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, |
7847 | const MultiLevelTemplateArgumentList &TemplateArgs); |
7848 | |
7849 | // Objective-C declarations. |
7850 | enum ObjCContainerKind { |
7851 | OCK_None = -1, |
7852 | OCK_Interface = 0, |
7853 | OCK_Protocol, |
7854 | OCK_Category, |
7855 | OCK_ClassExtension, |
7856 | OCK_Implementation, |
7857 | OCK_CategoryImplementation |
7858 | }; |
7859 | ObjCContainerKind getObjCContainerKind() const; |
7860 | |
7861 | DeclResult actOnObjCTypeParam(Scope *S, |
7862 | ObjCTypeParamVariance variance, |
7863 | SourceLocation varianceLoc, |
7864 | unsigned index, |
7865 | IdentifierInfo *paramName, |
7866 | SourceLocation paramLoc, |
7867 | SourceLocation colonLoc, |
7868 | ParsedType typeBound); |
7869 | |
7870 | ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, |
7871 | ArrayRef<Decl *> typeParams, |
7872 | SourceLocation rAngleLoc); |
7873 | void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); |
7874 | |
7875 | Decl *ActOnStartClassInterface(Scope *S, |
7876 | SourceLocation AtInterfaceLoc, |
7877 | IdentifierInfo *ClassName, |
7878 | SourceLocation ClassLoc, |
7879 | ObjCTypeParamList *typeParamList, |
7880 | IdentifierInfo *SuperName, |
7881 | SourceLocation SuperLoc, |
7882 | ArrayRef<ParsedType> SuperTypeArgs, |
7883 | SourceRange SuperTypeArgsRange, |
7884 | Decl * const *ProtoRefs, |
7885 | unsigned NumProtoRefs, |
7886 | const SourceLocation *ProtoLocs, |
7887 | SourceLocation EndProtoLoc, |
7888 | AttributeList *AttrList); |
7889 | |
7890 | void ActOnSuperClassOfClassInterface(Scope *S, |
7891 | SourceLocation AtInterfaceLoc, |
7892 | ObjCInterfaceDecl *IDecl, |
7893 | IdentifierInfo *ClassName, |
7894 | SourceLocation ClassLoc, |
7895 | IdentifierInfo *SuperName, |
7896 | SourceLocation SuperLoc, |
7897 | ArrayRef<ParsedType> SuperTypeArgs, |
7898 | SourceRange SuperTypeArgsRange); |
7899 | |
7900 | void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, |
7901 | SmallVectorImpl<SourceLocation> &ProtocolLocs, |
7902 | IdentifierInfo *SuperName, |
7903 | SourceLocation SuperLoc); |
7904 | |
7905 | Decl *ActOnCompatibilityAlias( |
7906 | SourceLocation AtCompatibilityAliasLoc, |
7907 | IdentifierInfo *AliasName, SourceLocation AliasLocation, |
7908 | IdentifierInfo *ClassName, SourceLocation ClassLocation); |
7909 | |
7910 | bool CheckForwardProtocolDeclarationForCircularDependency( |
7911 | IdentifierInfo *PName, |
7912 | SourceLocation &PLoc, SourceLocation PrevLoc, |
7913 | const ObjCList<ObjCProtocolDecl> &PList); |
7914 | |
7915 | Decl *ActOnStartProtocolInterface( |
7916 | SourceLocation AtProtoInterfaceLoc, |
7917 | IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, |
7918 | Decl * const *ProtoRefNames, unsigned NumProtoRefs, |
7919 | const SourceLocation *ProtoLocs, |
7920 | SourceLocation EndProtoLoc, |
7921 | AttributeList *AttrList); |
7922 | |
7923 | Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, |
7924 | IdentifierInfo *ClassName, |
7925 | SourceLocation ClassLoc, |
7926 | ObjCTypeParamList *typeParamList, |
7927 | IdentifierInfo *CategoryName, |
7928 | SourceLocation CategoryLoc, |
7929 | Decl * const *ProtoRefs, |
7930 | unsigned NumProtoRefs, |
7931 | const SourceLocation *ProtoLocs, |
7932 | SourceLocation EndProtoLoc, |
7933 | AttributeList *AttrList); |
7934 | |
7935 | Decl *ActOnStartClassImplementation( |
7936 | SourceLocation AtClassImplLoc, |
7937 | IdentifierInfo *ClassName, SourceLocation ClassLoc, |
7938 | IdentifierInfo *SuperClassname, |
7939 | SourceLocation SuperClassLoc); |
7940 | |
7941 | Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, |
7942 | IdentifierInfo *ClassName, |
7943 | SourceLocation ClassLoc, |
7944 | IdentifierInfo *CatName, |
7945 | SourceLocation CatLoc); |
7946 | |
7947 | DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, |
7948 | ArrayRef<Decl *> Decls); |
7949 | |
7950 | DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, |
7951 | IdentifierInfo **IdentList, |
7952 | SourceLocation *IdentLocs, |
7953 | ArrayRef<ObjCTypeParamList *> TypeParamLists, |
7954 | unsigned NumElts); |
7955 | |
7956 | DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, |
7957 | ArrayRef<IdentifierLocPair> IdentList, |
7958 | AttributeList *attrList); |
7959 | |
7960 | void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, |
7961 | ArrayRef<IdentifierLocPair> ProtocolId, |
7962 | SmallVectorImpl<Decl *> &Protocols); |
7963 | |
7964 | void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, |
7965 | SourceLocation ProtocolLoc, |
7966 | IdentifierInfo *TypeArgId, |
7967 | SourceLocation TypeArgLoc, |
7968 | bool SelectProtocolFirst = false); |
7969 | |
7970 | /// Given a list of identifiers (and their locations), resolve the |
7971 | /// names to either Objective-C protocol qualifiers or type |
7972 | /// arguments, as appropriate. |
7973 | void actOnObjCTypeArgsOrProtocolQualifiers( |
7974 | Scope *S, |
7975 | ParsedType baseType, |
7976 | SourceLocation lAngleLoc, |
7977 | ArrayRef<IdentifierInfo *> identifiers, |
7978 | ArrayRef<SourceLocation> identifierLocs, |
7979 | SourceLocation rAngleLoc, |
7980 | SourceLocation &typeArgsLAngleLoc, |
7981 | SmallVectorImpl<ParsedType> &typeArgs, |
7982 | SourceLocation &typeArgsRAngleLoc, |
7983 | SourceLocation &protocolLAngleLoc, |
7984 | SmallVectorImpl<Decl *> &protocols, |
7985 | SourceLocation &protocolRAngleLoc, |
7986 | bool warnOnIncompleteProtocols); |
7987 | |
7988 | /// Build a an Objective-C protocol-qualified 'id' type where no |
7989 | /// base type was specified. |
7990 | TypeResult actOnObjCProtocolQualifierType( |
7991 | SourceLocation lAngleLoc, |
7992 | ArrayRef<Decl *> protocols, |
7993 | ArrayRef<SourceLocation> protocolLocs, |
7994 | SourceLocation rAngleLoc); |
7995 | |
7996 | /// Build a specialized and/or protocol-qualified Objective-C type. |
7997 | TypeResult actOnObjCTypeArgsAndProtocolQualifiers( |
7998 | Scope *S, |
7999 | SourceLocation Loc, |
8000 | ParsedType BaseType, |
8001 | SourceLocation TypeArgsLAngleLoc, |
8002 | ArrayRef<ParsedType> TypeArgs, |
8003 | SourceLocation TypeArgsRAngleLoc, |
8004 | SourceLocation ProtocolLAngleLoc, |
8005 | ArrayRef<Decl *> Protocols, |
8006 | ArrayRef<SourceLocation> ProtocolLocs, |
8007 | SourceLocation ProtocolRAngleLoc); |
8008 | |
8009 | /// Build an Objective-C type parameter type. |
8010 | QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, |
8011 | SourceLocation ProtocolLAngleLoc, |
8012 | ArrayRef<ObjCProtocolDecl *> Protocols, |
8013 | ArrayRef<SourceLocation> ProtocolLocs, |
8014 | SourceLocation ProtocolRAngleLoc, |
8015 | bool FailOnError = false); |
8016 | |
8017 | /// Build an Objective-C object pointer type. |
8018 | QualType BuildObjCObjectType(QualType BaseType, |
8019 | SourceLocation Loc, |
8020 | SourceLocation TypeArgsLAngleLoc, |
8021 | ArrayRef<TypeSourceInfo *> TypeArgs, |
8022 | SourceLocation TypeArgsRAngleLoc, |
8023 | SourceLocation ProtocolLAngleLoc, |
8024 | ArrayRef<ObjCProtocolDecl *> Protocols, |
8025 | ArrayRef<SourceLocation> ProtocolLocs, |
8026 | SourceLocation ProtocolRAngleLoc, |
8027 | bool FailOnError = false); |
8028 | |
8029 | /// Check the application of the Objective-C '__kindof' qualifier to |
8030 | /// the given type. |
8031 | bool checkObjCKindOfType(QualType &type, SourceLocation loc); |
8032 | |
8033 | /// Ensure attributes are consistent with type. |
8034 | /// \param [in, out] Attributes The attributes to check; they will |
8035 | /// be modified to be consistent with \p PropertyTy. |
8036 | void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, |
8037 | SourceLocation Loc, |
8038 | unsigned &Attributes, |
8039 | bool propertyInPrimaryClass); |
8040 | |
8041 | /// Process the specified property declaration and create decls for the |
8042 | /// setters and getters as needed. |
8043 | /// \param property The property declaration being processed |
8044 | void ProcessPropertyDecl(ObjCPropertyDecl *property); |
8045 | |
8046 | |
8047 | void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, |
8048 | ObjCPropertyDecl *SuperProperty, |
8049 | const IdentifierInfo *Name, |
8050 | bool OverridingProtocolProperty); |
8051 | |
8052 | void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, |
8053 | ObjCInterfaceDecl *ID); |
8054 | |
8055 | Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, |
8056 | ArrayRef<Decl *> allMethods = None, |
8057 | ArrayRef<DeclGroupPtrTy> allTUVars = None); |
8058 | |
8059 | Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, |
8060 | SourceLocation LParenLoc, |
8061 | FieldDeclarator &FD, ObjCDeclSpec &ODS, |
8062 | Selector GetterSel, Selector SetterSel, |
8063 | tok::ObjCKeywordKind MethodImplKind, |
8064 | DeclContext *lexicalDC = nullptr); |
8065 | |
8066 | Decl *ActOnPropertyImplDecl(Scope *S, |
8067 | SourceLocation AtLoc, |
8068 | SourceLocation PropertyLoc, |
8069 | bool ImplKind, |
8070 | IdentifierInfo *PropertyId, |
8071 | IdentifierInfo *PropertyIvar, |
8072 | SourceLocation PropertyIvarLoc, |
8073 | ObjCPropertyQueryKind QueryKind); |
8074 | |
8075 | enum ObjCSpecialMethodKind { |
8076 | OSMK_None, |
8077 | OSMK_Alloc, |
8078 | OSMK_New, |
8079 | OSMK_Copy, |
8080 | OSMK_RetainingInit, |
8081 | OSMK_NonRetainingInit |
8082 | }; |
8083 | |
8084 | struct ObjCArgInfo { |
8085 | IdentifierInfo *Name; |
8086 | SourceLocation NameLoc; |
8087 | // The Type is null if no type was specified, and the DeclSpec is invalid |
8088 | // in this case. |
8089 | ParsedType Type; |
8090 | ObjCDeclSpec DeclSpec; |
8091 | |
8092 | /// ArgAttrs - Attribute list for this argument. |
8093 | AttributeList *ArgAttrs; |
8094 | }; |
8095 | |
8096 | Decl *ActOnMethodDeclaration( |
8097 | Scope *S, |
8098 | SourceLocation BeginLoc, // location of the + or -. |
8099 | SourceLocation EndLoc, // location of the ; or {. |
8100 | tok::TokenKind MethodType, |
8101 | ObjCDeclSpec &ReturnQT, ParsedType ReturnType, |
8102 | ArrayRef<SourceLocation> SelectorLocs, Selector Sel, |
8103 | // optional arguments. The number of types/arguments is obtained |
8104 | // from the Sel.getNumArgs(). |
8105 | ObjCArgInfo *ArgInfo, |
8106 | DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args |
8107 | AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, |
8108 | bool isVariadic, bool MethodDefinition); |
8109 | |
8110 | ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, |
8111 | const ObjCObjectPointerType *OPT, |
8112 | bool IsInstance); |
8113 | ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, |
8114 | bool IsInstance); |
8115 | |
8116 | bool CheckARCMethodDecl(ObjCMethodDecl *method); |
8117 | bool inferObjCARCLifetime(ValueDecl *decl); |
8118 | |
8119 | ExprResult |
8120 | HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, |
8121 | Expr *BaseExpr, |
8122 | SourceLocation OpLoc, |
8123 | DeclarationName MemberName, |
8124 | SourceLocation MemberLoc, |
8125 | SourceLocation SuperLoc, QualType SuperType, |
8126 | bool Super); |
8127 | |
8128 | ExprResult |
8129 | ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, |
8130 | IdentifierInfo &propertyName, |
8131 | SourceLocation receiverNameLoc, |
8132 | SourceLocation propertyNameLoc); |
8133 | |
8134 | ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); |
8135 | |
8136 | /// \brief Describes the kind of message expression indicated by a message |
8137 | /// send that starts with an identifier. |
8138 | enum ObjCMessageKind { |
8139 | /// \brief The message is sent to 'super'. |
8140 | ObjCSuperMessage, |
8141 | /// \brief The message is an instance message. |
8142 | ObjCInstanceMessage, |
8143 | /// \brief The message is a class message, and the identifier is a type |
8144 | /// name. |
8145 | ObjCClassMessage |
8146 | }; |
8147 | |
8148 | ObjCMessageKind getObjCMessageKind(Scope *S, |
8149 | IdentifierInfo *Name, |
8150 | SourceLocation NameLoc, |
8151 | bool IsSuper, |
8152 | bool HasTrailingDot, |
8153 | ParsedType &ReceiverType); |
8154 | |
8155 | ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, |
8156 | Selector Sel, |
8157 | SourceLocation LBracLoc, |
8158 | ArrayRef<SourceLocation> SelectorLocs, |
8159 | SourceLocation RBracLoc, |
8160 | MultiExprArg Args); |
8161 | |
8162 | ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, |
8163 | QualType ReceiverType, |
8164 | SourceLocation SuperLoc, |
8165 | Selector Sel, |
8166 | ObjCMethodDecl *Method, |
8167 | SourceLocation LBracLoc, |
8168 | ArrayRef<SourceLocation> SelectorLocs, |
8169 | SourceLocation RBracLoc, |
8170 | MultiExprArg Args, |
8171 | bool isImplicit = false); |
8172 | |
8173 | ExprResult BuildClassMessageImplicit(QualType ReceiverType, |
8174 | bool isSuperReceiver, |
8175 | SourceLocation Loc, |
8176 | Selector Sel, |
8177 | ObjCMethodDecl *Method, |
8178 | MultiExprArg Args); |
8179 | |
8180 | ExprResult ActOnClassMessage(Scope *S, |
8181 | ParsedType Receiver, |
8182 | Selector Sel, |
8183 | SourceLocation LBracLoc, |
8184 | ArrayRef<SourceLocation> SelectorLocs, |
8185 | SourceLocation RBracLoc, |
8186 | MultiExprArg Args); |
8187 | |
8188 | ExprResult BuildInstanceMessage(Expr *Receiver, |
8189 | QualType ReceiverType, |
8190 | SourceLocation SuperLoc, |
8191 | Selector Sel, |
8192 | ObjCMethodDecl *Method, |
8193 | SourceLocation LBracLoc, |
8194 | ArrayRef<SourceLocation> SelectorLocs, |
8195 | SourceLocation RBracLoc, |
8196 | MultiExprArg Args, |
8197 | bool isImplicit = false); |
8198 | |
8199 | ExprResult BuildInstanceMessageImplicit(Expr *Receiver, |
8200 | QualType ReceiverType, |
8201 | SourceLocation Loc, |
8202 | Selector Sel, |
8203 | ObjCMethodDecl *Method, |
8204 | MultiExprArg Args); |
8205 | |
8206 | ExprResult ActOnInstanceMessage(Scope *S, |
8207 | Expr *Receiver, |
8208 | Selector Sel, |
8209 | SourceLocation LBracLoc, |
8210 | ArrayRef<SourceLocation> SelectorLocs, |
8211 | SourceLocation RBracLoc, |
8212 | MultiExprArg Args); |
8213 | |
8214 | ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, |
8215 | ObjCBridgeCastKind Kind, |
8216 | SourceLocation BridgeKeywordLoc, |
8217 | TypeSourceInfo *TSInfo, |
8218 | Expr *SubExpr); |
8219 | |
8220 | ExprResult ActOnObjCBridgedCast(Scope *S, |
8221 | SourceLocation LParenLoc, |
8222 | ObjCBridgeCastKind Kind, |
8223 | SourceLocation BridgeKeywordLoc, |
8224 | ParsedType Type, |
8225 | SourceLocation RParenLoc, |
8226 | Expr *SubExpr); |
8227 | |
8228 | void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); |
8229 | |
8230 | void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); |
8231 | |
8232 | bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, |
8233 | CastKind &Kind); |
8234 | |
8235 | bool checkObjCBridgeRelatedComponents(SourceLocation Loc, |
8236 | QualType DestType, QualType SrcType, |
8237 | ObjCInterfaceDecl *&RelatedClass, |
8238 | ObjCMethodDecl *&ClassMethod, |
8239 | ObjCMethodDecl *&InstanceMethod, |
8240 | TypedefNameDecl *&TDNDecl, |
8241 | bool CfToNs, bool Diagnose = true); |
8242 | |
8243 | bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, |
8244 | QualType DestType, QualType SrcType, |
8245 | Expr *&SrcExpr, bool Diagnose = true); |
8246 | |
8247 | bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, |
8248 | bool Diagnose = true); |
8249 | |
8250 | bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); |
8251 | |
8252 | /// \brief Check whether the given new method is a valid override of the |
8253 | /// given overridden method, and set any properties that should be inherited. |
8254 | void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, |
8255 | const ObjCMethodDecl *Overridden); |
8256 | |
8257 | /// \brief Describes the compatibility of a result type with its method. |
8258 | enum ResultTypeCompatibilityKind { |
8259 | RTC_Compatible, |
8260 | RTC_Incompatible, |
8261 | RTC_Unknown |
8262 | }; |
8263 | |
8264 | void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, |
8265 | ObjCInterfaceDecl *CurrentClass, |
8266 | ResultTypeCompatibilityKind RTC); |
8267 | |
8268 | enum PragmaOptionsAlignKind { |
8269 | POAK_Native, // #pragma options align=native |
8270 | POAK_Natural, // #pragma options align=natural |
8271 | POAK_Packed, // #pragma options align=packed |
8272 | POAK_Power, // #pragma options align=power |
8273 | POAK_Mac68k, // #pragma options align=mac68k |
8274 | POAK_Reset // #pragma options align=reset |
8275 | }; |
8276 | |
8277 | /// ActOnPragmaClangSection - Called on well formed \#pragma clang section |
8278 | void ActOnPragmaClangSection(SourceLocation PragmaLoc, |
8279 | PragmaClangSectionAction Action, |
8280 | PragmaClangSectionKind SecKind, StringRef SecName); |
8281 | |
8282 | /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. |
8283 | void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, |
8284 | SourceLocation PragmaLoc); |
8285 | |
8286 | /// ActOnPragmaPack - Called on well formed \#pragma pack(...). |
8287 | void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, |
8288 | StringRef SlotLabel, Expr *Alignment); |
8289 | |
8290 | enum class PragmaPackDiagnoseKind { |
8291 | NonDefaultStateAtInclude, |
8292 | ChangedStateAtExit |
8293 | }; |
8294 | |
8295 | void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, |
8296 | SourceLocation IncludeLoc); |
8297 | void DiagnoseUnterminatedPragmaPack(); |
8298 | |
8299 | /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. |
8300 | void ActOnPragmaMSStruct(PragmaMSStructKind Kind); |
8301 | |
8302 | /// ActOnPragmaMSComment - Called on well formed |
8303 | /// \#pragma comment(kind, "arg"). |
8304 | void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, |
8305 | StringRef Arg); |
8306 | |
8307 | /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma |
8308 | /// pointers_to_members(representation method[, general purpose |
8309 | /// representation]). |
8310 | void ActOnPragmaMSPointersToMembers( |
8311 | LangOptions::PragmaMSPointersToMembersKind Kind, |
8312 | SourceLocation PragmaLoc); |
8313 | |
8314 | /// \brief Called on well formed \#pragma vtordisp(). |
8315 | void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, |
8316 | SourceLocation PragmaLoc, |
8317 | MSVtorDispAttr::Mode Value); |
8318 | |
8319 | enum PragmaSectionKind { |
8320 | PSK_DataSeg, |
8321 | PSK_BSSSeg, |
8322 | PSK_ConstSeg, |
8323 | PSK_CodeSeg, |
8324 | }; |
8325 | |
8326 | bool UnifySection(StringRef SectionName, |
8327 | int SectionFlags, |
8328 | DeclaratorDecl *TheDecl); |
8329 | bool UnifySection(StringRef SectionName, |
8330 | int SectionFlags, |
8331 | SourceLocation PragmaSectionLocation); |
8332 | |
8333 | /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. |
8334 | void ActOnPragmaMSSeg(SourceLocation PragmaLocation, |
8335 | PragmaMsStackAction Action, |
8336 | llvm::StringRef StackSlotLabel, |
8337 | StringLiteral *SegmentName, |
8338 | llvm::StringRef PragmaName); |
8339 | |
8340 | /// \brief Called on well formed \#pragma section(). |
8341 | void ActOnPragmaMSSection(SourceLocation PragmaLocation, |
8342 | int SectionFlags, StringLiteral *SegmentName); |
8343 | |
8344 | /// \brief Called on well-formed \#pragma init_seg(). |
8345 | void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, |
8346 | StringLiteral *SegmentName); |
8347 | |
8348 | /// \brief Called on #pragma clang __debug dump II |
8349 | void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); |
8350 | |
8351 | /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch |
8352 | void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, |
8353 | StringRef Value); |
8354 | |
8355 | /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. |
8356 | void ActOnPragmaUnused(const Token &Identifier, |
8357 | Scope *curScope, |
8358 | SourceLocation PragmaLoc); |
8359 | |
8360 | /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . |
8361 | void ActOnPragmaVisibility(const IdentifierInfo* VisType, |
8362 | SourceLocation PragmaLoc); |
8363 | |
8364 | NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, |
8365 | SourceLocation Loc); |
8366 | void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); |
8367 | |
8368 | /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. |
8369 | void ActOnPragmaWeakID(IdentifierInfo* WeakName, |
8370 | SourceLocation PragmaLoc, |
8371 | SourceLocation WeakNameLoc); |
8372 | |
8373 | /// ActOnPragmaRedefineExtname - Called on well formed |
8374 | /// \#pragma redefine_extname oldname newname. |
8375 | void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, |
8376 | IdentifierInfo* AliasName, |
8377 | SourceLocation PragmaLoc, |
8378 | SourceLocation WeakNameLoc, |
8379 | SourceLocation AliasNameLoc); |
8380 | |
8381 | /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. |
8382 | void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, |
8383 | IdentifierInfo* AliasName, |
8384 | SourceLocation PragmaLoc, |
8385 | SourceLocation WeakNameLoc, |
8386 | SourceLocation AliasNameLoc); |
8387 | |
8388 | /// ActOnPragmaFPContract - Called on well formed |
8389 | /// \#pragma {STDC,OPENCL} FP_CONTRACT and |
8390 | /// \#pragma clang fp contract |
8391 | void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC); |
8392 | |
8393 | /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to |
8394 | /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. |
8395 | void AddAlignmentAttributesForRecord(RecordDecl *RD); |
8396 | |
8397 | /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. |
8398 | void AddMsStructLayoutForRecord(RecordDecl *RD); |
8399 | |
8400 | /// FreePackedContext - Deallocate and null out PackContext. |
8401 | void FreePackedContext(); |
8402 | |
8403 | /// PushNamespaceVisibilityAttr - Note that we've entered a |
8404 | /// namespace with a visibility attribute. |
8405 | void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, |
8406 | SourceLocation Loc); |
8407 | |
8408 | /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, |
8409 | /// add an appropriate visibility attribute. |
8410 | void AddPushedVisibilityAttribute(Decl *RD); |
8411 | |
8412 | /// PopPragmaVisibility - Pop the top element of the visibility stack; used |
8413 | /// for '\#pragma GCC visibility' and visibility attributes on namespaces. |
8414 | void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); |
8415 | |
8416 | /// FreeVisContext - Deallocate and null out VisContext. |
8417 | void FreeVisContext(); |
8418 | |
8419 | /// AddCFAuditedAttribute - Check whether we're currently within |
8420 | /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding |
8421 | /// the appropriate attribute. |
8422 | void AddCFAuditedAttribute(Decl *D); |
8423 | |
8424 | /// \brief Called on well-formed '\#pragma clang attribute push'. |
8425 | void ActOnPragmaAttributePush(AttributeList &Attribute, |
8426 | SourceLocation PragmaLoc, |
8427 | attr::ParsedSubjectMatchRuleSet Rules); |
8428 | |
8429 | /// \brief Called on well-formed '\#pragma clang attribute pop'. |
8430 | void ActOnPragmaAttributePop(SourceLocation PragmaLoc); |
8431 | |
8432 | /// \brief Adds the attributes that have been specified using the |
8433 | /// '\#pragma clang attribute push' directives to the given declaration. |
8434 | void AddPragmaAttributes(Scope *S, Decl *D); |
8435 | |
8436 | void DiagnoseUnterminatedPragmaAttribute(); |
8437 | |
8438 | /// \brief Called on well formed \#pragma clang optimize. |
8439 | void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); |
8440 | |
8441 | /// \brief Get the location for the currently active "\#pragma clang optimize |
8442 | /// off". If this location is invalid, then the state of the pragma is "on". |
8443 | SourceLocation getOptimizeOffPragmaLocation() const { |
8444 | return OptimizeOffPragmaLocation; |
8445 | } |
8446 | |
8447 | /// \brief Only called on function definitions; if there is a pragma in scope |
8448 | /// with the effect of a range-based optnone, consider marking the function |
8449 | /// with attribute optnone. |
8450 | void AddRangeBasedOptnone(FunctionDecl *FD); |
8451 | |
8452 | /// \brief Adds the 'optnone' attribute to the function declaration if there |
8453 | /// are no conflicts; Loc represents the location causing the 'optnone' |
8454 | /// attribute to be added (usually because of a pragma). |
8455 | void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); |
8456 | |
8457 | /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. |
8458 | void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, |
8459 | unsigned SpellingListIndex, bool IsPackExpansion); |
8460 | void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, |
8461 | unsigned SpellingListIndex, bool IsPackExpansion); |
8462 | |
8463 | /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular |
8464 | /// declaration. |
8465 | void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, |
8466 | unsigned SpellingListIndex); |
8467 | |
8468 | /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular |
8469 | /// declaration. |
8470 | void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, |
8471 | unsigned SpellingListIndex); |
8472 | |
8473 | /// AddAlignValueAttr - Adds an align_value attribute to a particular |
8474 | /// declaration. |
8475 | void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, |
8476 | unsigned SpellingListIndex); |
8477 | |
8478 | /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular |
8479 | /// declaration. |
8480 | void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, |
8481 | Expr *MinBlocks, unsigned SpellingListIndex); |
8482 | |
8483 | /// AddModeAttr - Adds a mode attribute to a particular declaration. |
8484 | void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, |
8485 | unsigned SpellingListIndex, bool InInstantiation = false); |
8486 | |
8487 | void AddParameterABIAttr(SourceRange AttrRange, Decl *D, |
8488 | ParameterABI ABI, unsigned SpellingListIndex); |
8489 | |
8490 | void AddNSConsumedAttr(SourceRange AttrRange, Decl *D, |
8491 | unsigned SpellingListIndex, bool isNSConsumed, |
8492 | bool isTemplateInstantiation); |
8493 | |
8494 | bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); |
8495 | |
8496 | //===--------------------------------------------------------------------===// |
8497 | // C++ Coroutines TS |
8498 | // |
8499 | bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, |
8500 | StringRef Keyword); |
8501 | ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); |
8502 | ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); |
8503 | StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); |
8504 | |
8505 | ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, |
8506 | bool IsImplicit = false); |
8507 | ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, |
8508 | UnresolvedLookupExpr* Lookup); |
8509 | ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); |
8510 | StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, |
8511 | bool IsImplicit = false); |
8512 | StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); |
8513 | bool buildCoroutineParameterMoves(SourceLocation Loc); |
8514 | VarDecl *buildCoroutinePromise(SourceLocation Loc); |
8515 | void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); |
8516 | |
8517 | //===--------------------------------------------------------------------===// |
8518 | // OpenCL extensions. |
8519 | // |
8520 | private: |
8521 | std::string CurrOpenCLExtension; |
8522 | /// Extensions required by an OpenCL type. |
8523 | llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; |
8524 | /// Extensions required by an OpenCL declaration. |
8525 | llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; |
8526 | public: |
8527 | llvm::StringRef getCurrentOpenCLExtension() const { |
8528 | return CurrOpenCLExtension; |
8529 | } |
8530 | void setCurrentOpenCLExtension(llvm::StringRef Ext) { |
8531 | CurrOpenCLExtension = Ext; |
8532 | } |
8533 | |
8534 | /// \brief Set OpenCL extensions for a type which can only be used when these |
8535 | /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. |
8536 | /// \param Exts A space separated list of OpenCL extensions. |
8537 | void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); |
8538 | |
8539 | /// \brief Set OpenCL extensions for a declaration which can only be |
8540 | /// used when these OpenCL extensions are enabled. If \p Exts is empty, do |
8541 | /// nothing. |
8542 | /// \param Exts A space separated list of OpenCL extensions. |
8543 | void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); |
8544 | |
8545 | /// \brief Set current OpenCL extensions for a type which can only be used |
8546 | /// when these OpenCL extensions are enabled. If current OpenCL extension is |
8547 | /// empty, do nothing. |
8548 | void setCurrentOpenCLExtensionForType(QualType T); |
8549 | |
8550 | /// \brief Set current OpenCL extensions for a declaration which |
8551 | /// can only be used when these OpenCL extensions are enabled. If current |
8552 | /// OpenCL extension is empty, do nothing. |
8553 | void setCurrentOpenCLExtensionForDecl(Decl *FD); |
8554 | |
8555 | bool isOpenCLDisabledDecl(Decl *FD); |
8556 | |
8557 | /// \brief Check if type \p T corresponding to declaration specifier \p DS |
8558 | /// is disabled due to required OpenCL extensions being disabled. If so, |
8559 | /// emit diagnostics. |
8560 | /// \return true if type is disabled. |
8561 | bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); |
8562 | |
8563 | /// \brief Check if declaration \p D used by expression \p E |
8564 | /// is disabled due to required OpenCL extensions being disabled. If so, |
8565 | /// emit diagnostics. |
8566 | /// \return true if type is disabled. |
8567 | bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); |
8568 | |
8569 | //===--------------------------------------------------------------------===// |
8570 | // OpenMP directives and clauses. |
8571 | // |
8572 | private: |
8573 | void *VarDataSharingAttributesStack; |
8574 | /// Set to true inside '#pragma omp declare target' region. |
8575 | bool IsInOpenMPDeclareTargetContext = false; |
8576 | /// \brief Initialization of data-sharing attributes stack. |
8577 | void InitDataSharingAttributesStack(); |
8578 | void DestroyDataSharingAttributesStack(); |
8579 | ExprResult |
8580 | VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, |
8581 | bool StrictlyPositive = true); |
8582 | /// Returns OpenMP nesting level for current directive. |
8583 | unsigned getOpenMPNestingLevel() const; |
8584 | |
8585 | /// Adjusts the function scopes index for the target-based regions. |
8586 | void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, |
8587 | unsigned Level) const; |
8588 | |
8589 | /// Push new OpenMP function region for non-capturing function. |
8590 | void pushOpenMPFunctionRegion(); |
8591 | |
8592 | /// Pop OpenMP function region for non-capturing function. |
8593 | void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); |
8594 | |
8595 | /// Checks if a type or a declaration is disabled due to the owning extension |
8596 | /// being disabled, and emits diagnostic messages if it is disabled. |
8597 | /// \param D type or declaration to be checked. |
8598 | /// \param DiagLoc source location for the diagnostic message. |
8599 | /// \param DiagInfo information to be emitted for the diagnostic message. |
8600 | /// \param SrcRange source range of the declaration. |
8601 | /// \param Map maps type or declaration to the extensions. |
8602 | /// \param Selector selects diagnostic message: 0 for type and 1 for |
8603 | /// declaration. |
8604 | /// \return true if the type or declaration is disabled. |
8605 | template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> |
8606 | bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, |
8607 | MapT &Map, unsigned Selector = 0, |
8608 | SourceRange SrcRange = SourceRange()); |
8609 | |
8610 | public: |
8611 | /// \brief Return true if the provided declaration \a VD should be captured by |
8612 | /// reference. |
8613 | /// \param Level Relative level of nested OpenMP construct for that the check |
8614 | /// is performed. |
8615 | bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level); |
8616 | |
8617 | /// \brief Check if the specified variable is used in one of the private |
8618 | /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP |
8619 | /// constructs. |
8620 | VarDecl *IsOpenMPCapturedDecl(ValueDecl *D); |
8621 | ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, |
8622 | ExprObjectKind OK, SourceLocation Loc); |
8623 | |
8624 | /// \brief Check if the specified variable is used in 'private' clause. |
8625 | /// \param Level Relative level of nested OpenMP construct for that the check |
8626 | /// is performed. |
8627 | bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level); |
8628 | |
8629 | /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) |
8630 | /// for \p FD based on DSA for the provided corresponding captured declaration |
8631 | /// \p D. |
8632 | void setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level); |
8633 | |
8634 | /// \brief Check if the specified variable is captured by 'target' directive. |
8635 | /// \param Level Relative level of nested OpenMP construct for that the check |
8636 | /// is performed. |
8637 | bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level); |
8638 | |
8639 | ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, |
8640 | Expr *Op); |
8641 | /// \brief Called on start of new data sharing attribute block. |
8642 | void StartOpenMPDSABlock(OpenMPDirectiveKind K, |
8643 | const DeclarationNameInfo &DirName, Scope *CurScope, |
8644 | SourceLocation Loc); |
8645 | /// \brief Start analysis of clauses. |
8646 | void StartOpenMPClause(OpenMPClauseKind K); |
8647 | /// \brief End analysis of clauses. |
8648 | void EndOpenMPClause(); |
8649 | /// \brief Called on end of data sharing attribute block. |
8650 | void EndOpenMPDSABlock(Stmt *CurDirective); |
8651 | |
8652 | /// \brief Check if the current region is an OpenMP loop region and if it is, |
8653 | /// mark loop control variable, used in \p Init for loop initialization, as |
8654 | /// private by default. |
8655 | /// \param Init First part of the for loop. |
8656 | void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); |
8657 | |
8658 | // OpenMP directives and clauses. |
8659 | /// \brief Called on correct id-expression from the '#pragma omp |
8660 | /// threadprivate'. |
8661 | ExprResult ActOnOpenMPIdExpression(Scope *CurScope, |
8662 | CXXScopeSpec &ScopeSpec, |
8663 | const DeclarationNameInfo &Id); |
8664 | /// \brief Called on well-formed '#pragma omp threadprivate'. |
8665 | DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( |
8666 | SourceLocation Loc, |
8667 | ArrayRef<Expr *> VarList); |
8668 | /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness. |
8669 | OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl( |
8670 | SourceLocation Loc, |
8671 | ArrayRef<Expr *> VarList); |
8672 | /// \brief Check if the specified type is allowed to be used in 'omp declare |
8673 | /// reduction' construct. |
8674 | QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, |
8675 | TypeResult ParsedType); |
8676 | /// \brief Called on start of '#pragma omp declare reduction'. |
8677 | DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( |
8678 | Scope *S, DeclContext *DC, DeclarationName Name, |
8679 | ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, |
8680 | AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); |
8681 | /// \brief Initialize declare reduction construct initializer. |
8682 | void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); |
8683 | /// \brief Finish current declare reduction construct initializer. |
8684 | void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); |
8685 | /// \brief Initialize declare reduction construct initializer. |
8686 | /// \return omp_priv variable. |
8687 | VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); |
8688 | /// \brief Finish current declare reduction construct initializer. |
8689 | void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, |
8690 | VarDecl *OmpPrivParm); |
8691 | /// \brief Called at the end of '#pragma omp declare reduction'. |
8692 | DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( |
8693 | Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); |
8694 | |
8695 | /// Called on the start of target region i.e. '#pragma omp declare target'. |
8696 | bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); |
8697 | /// Called at the end of target region i.e. '#pragme omp end declare target'. |
8698 | void ActOnFinishOpenMPDeclareTargetDirective(); |
8699 | /// Called on correct id-expression from the '#pragma omp declare target'. |
8700 | void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, |
8701 | const DeclarationNameInfo &Id, |
8702 | OMPDeclareTargetDeclAttr::MapTypeTy MT, |
8703 | NamedDeclSetType &SameDirectiveDecls); |
8704 | /// Check declaration inside target region. |
8705 | void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, |
8706 | SourceLocation IdLoc = SourceLocation()); |
8707 | /// Return true inside OpenMP declare target region. |
8708 | bool isInOpenMPDeclareTargetContext() const { |
8709 | return IsInOpenMPDeclareTargetContext; |
8710 | } |
8711 | /// Return true inside OpenMP target region. |
8712 | bool isInOpenMPTargetExecutionDirective() const; |
8713 | /// Return true if (un)supported features for the current target should be |
8714 | /// diagnosed if OpenMP (offloading) is enabled. |
8715 | bool shouldDiagnoseTargetSupportFromOpenMP() const { |
8716 | return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() || |
8717 | isInOpenMPTargetExecutionDirective(); |
8718 | } |
8719 | |
8720 | /// Return the number of captured regions created for an OpenMP directive. |
8721 | static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); |
8722 | |
8723 | /// \brief Initialization of captured region for OpenMP region. |
8724 | void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); |
8725 | /// \brief End of OpenMP region. |
8726 | /// |
8727 | /// \param S Statement associated with the current OpenMP region. |
8728 | /// \param Clauses List of clauses for the current OpenMP region. |
8729 | /// |
8730 | /// \returns Statement for finished OpenMP region. |
8731 | StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); |
8732 | StmtResult ActOnOpenMPExecutableDirective( |
8733 | OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, |
8734 | OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, |
8735 | Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); |
8736 | /// \brief Called on well-formed '\#pragma omp parallel' after parsing |
8737 | /// of the associated statement. |
8738 | StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, |
8739 | Stmt *AStmt, |
8740 | SourceLocation StartLoc, |
8741 | SourceLocation EndLoc); |
8742 | /// \brief Called on well-formed '\#pragma omp simd' after parsing |
8743 | /// of the associated statement. |
8744 | StmtResult ActOnOpenMPSimdDirective( |
8745 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8746 | SourceLocation EndLoc, |
8747 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8748 | /// \brief Called on well-formed '\#pragma omp for' after parsing |
8749 | /// of the associated statement. |
8750 | StmtResult ActOnOpenMPForDirective( |
8751 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8752 | SourceLocation EndLoc, |
8753 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8754 | /// \brief Called on well-formed '\#pragma omp for simd' after parsing |
8755 | /// of the associated statement. |
8756 | StmtResult ActOnOpenMPForSimdDirective( |
8757 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8758 | SourceLocation EndLoc, |
8759 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8760 | /// \brief Called on well-formed '\#pragma omp sections' after parsing |
8761 | /// of the associated statement. |
8762 | StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, |
8763 | Stmt *AStmt, SourceLocation StartLoc, |
8764 | SourceLocation EndLoc); |
8765 | /// \brief Called on well-formed '\#pragma omp section' after parsing of the |
8766 | /// associated statement. |
8767 | StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, |
8768 | SourceLocation EndLoc); |
8769 | /// \brief Called on well-formed '\#pragma omp single' after parsing of the |
8770 | /// associated statement. |
8771 | StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, |
8772 | Stmt *AStmt, SourceLocation StartLoc, |
8773 | SourceLocation EndLoc); |
8774 | /// \brief Called on well-formed '\#pragma omp master' after parsing of the |
8775 | /// associated statement. |
8776 | StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, |
8777 | SourceLocation EndLoc); |
8778 | /// \brief Called on well-formed '\#pragma omp critical' after parsing of the |
8779 | /// associated statement. |
8780 | StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, |
8781 | ArrayRef<OMPClause *> Clauses, |
8782 | Stmt *AStmt, SourceLocation StartLoc, |
8783 | SourceLocation EndLoc); |
8784 | /// \brief Called on well-formed '\#pragma omp parallel for' after parsing |
8785 | /// of the associated statement. |
8786 | StmtResult ActOnOpenMPParallelForDirective( |
8787 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8788 | SourceLocation EndLoc, |
8789 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8790 | /// \brief Called on well-formed '\#pragma omp parallel for simd' after |
8791 | /// parsing of the associated statement. |
8792 | StmtResult ActOnOpenMPParallelForSimdDirective( |
8793 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8794 | SourceLocation EndLoc, |
8795 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8796 | /// \brief Called on well-formed '\#pragma omp parallel sections' after |
8797 | /// parsing of the associated statement. |
8798 | StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, |
8799 | Stmt *AStmt, |
8800 | SourceLocation StartLoc, |
8801 | SourceLocation EndLoc); |
8802 | /// \brief Called on well-formed '\#pragma omp task' after parsing of the |
8803 | /// associated statement. |
8804 | StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, |
8805 | Stmt *AStmt, SourceLocation StartLoc, |
8806 | SourceLocation EndLoc); |
8807 | /// \brief Called on well-formed '\#pragma omp taskyield'. |
8808 | StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, |
8809 | SourceLocation EndLoc); |
8810 | /// \brief Called on well-formed '\#pragma omp barrier'. |
8811 | StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, |
8812 | SourceLocation EndLoc); |
8813 | /// \brief Called on well-formed '\#pragma omp taskwait'. |
8814 | StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, |
8815 | SourceLocation EndLoc); |
8816 | /// \brief Called on well-formed '\#pragma omp taskgroup'. |
8817 | StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, |
8818 | Stmt *AStmt, SourceLocation StartLoc, |
8819 | SourceLocation EndLoc); |
8820 | /// \brief Called on well-formed '\#pragma omp flush'. |
8821 | StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, |
8822 | SourceLocation StartLoc, |
8823 | SourceLocation EndLoc); |
8824 | /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the |
8825 | /// associated statement. |
8826 | StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, |
8827 | Stmt *AStmt, SourceLocation StartLoc, |
8828 | SourceLocation EndLoc); |
8829 | /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the |
8830 | /// associated statement. |
8831 | StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, |
8832 | Stmt *AStmt, SourceLocation StartLoc, |
8833 | SourceLocation EndLoc); |
8834 | /// \brief Called on well-formed '\#pragma omp target' after parsing of the |
8835 | /// associated statement. |
8836 | StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, |
8837 | Stmt *AStmt, SourceLocation StartLoc, |
8838 | SourceLocation EndLoc); |
8839 | /// \brief Called on well-formed '\#pragma omp target data' after parsing of |
8840 | /// the associated statement. |
8841 | StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, |
8842 | Stmt *AStmt, SourceLocation StartLoc, |
8843 | SourceLocation EndLoc); |
8844 | /// \brief Called on well-formed '\#pragma omp target enter data' after |
8845 | /// parsing of the associated statement. |
8846 | StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, |
8847 | SourceLocation StartLoc, |
8848 | SourceLocation EndLoc, |
8849 | Stmt *AStmt); |
8850 | /// \brief Called on well-formed '\#pragma omp target exit data' after |
8851 | /// parsing of the associated statement. |
8852 | StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, |
8853 | SourceLocation StartLoc, |
8854 | SourceLocation EndLoc, |
8855 | Stmt *AStmt); |
8856 | /// \brief Called on well-formed '\#pragma omp target parallel' after |
8857 | /// parsing of the associated statement. |
8858 | StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, |
8859 | Stmt *AStmt, |
8860 | SourceLocation StartLoc, |
8861 | SourceLocation EndLoc); |
8862 | /// \brief Called on well-formed '\#pragma omp target parallel for' after |
8863 | /// parsing of the associated statement. |
8864 | StmtResult ActOnOpenMPTargetParallelForDirective( |
8865 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8866 | SourceLocation EndLoc, |
8867 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8868 | /// \brief Called on well-formed '\#pragma omp teams' after parsing of the |
8869 | /// associated statement. |
8870 | StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, |
8871 | Stmt *AStmt, SourceLocation StartLoc, |
8872 | SourceLocation EndLoc); |
8873 | /// \brief Called on well-formed '\#pragma omp cancellation point'. |
8874 | StmtResult |
8875 | ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, |
8876 | SourceLocation EndLoc, |
8877 | OpenMPDirectiveKind CancelRegion); |
8878 | /// \brief Called on well-formed '\#pragma omp cancel'. |
8879 | StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, |
8880 | SourceLocation StartLoc, |
8881 | SourceLocation EndLoc, |
8882 | OpenMPDirectiveKind CancelRegion); |
8883 | /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the |
8884 | /// associated statement. |
8885 | StmtResult ActOnOpenMPTaskLoopDirective( |
8886 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8887 | SourceLocation EndLoc, |
8888 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8889 | /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of |
8890 | /// the associated statement. |
8891 | StmtResult ActOnOpenMPTaskLoopSimdDirective( |
8892 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8893 | SourceLocation EndLoc, |
8894 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8895 | /// \brief Called on well-formed '\#pragma omp distribute' after parsing |
8896 | /// of the associated statement. |
8897 | StmtResult ActOnOpenMPDistributeDirective( |
8898 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8899 | SourceLocation EndLoc, |
8900 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8901 | /// \brief Called on well-formed '\#pragma omp target update'. |
8902 | StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, |
8903 | SourceLocation StartLoc, |
8904 | SourceLocation EndLoc, |
8905 | Stmt *AStmt); |
8906 | /// \brief Called on well-formed '\#pragma omp distribute parallel for' after |
8907 | /// parsing of the associated statement. |
8908 | StmtResult ActOnOpenMPDistributeParallelForDirective( |
8909 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8910 | SourceLocation EndLoc, |
8911 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8912 | /// \brief Called on well-formed '\#pragma omp distribute parallel for simd' |
8913 | /// after parsing of the associated statement. |
8914 | StmtResult ActOnOpenMPDistributeParallelForSimdDirective( |
8915 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8916 | SourceLocation EndLoc, |
8917 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8918 | /// \brief Called on well-formed '\#pragma omp distribute simd' after |
8919 | /// parsing of the associated statement. |
8920 | StmtResult ActOnOpenMPDistributeSimdDirective( |
8921 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8922 | SourceLocation EndLoc, |
8923 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8924 | /// \brief Called on well-formed '\#pragma omp target parallel for simd' after |
8925 | /// parsing of the associated statement. |
8926 | StmtResult ActOnOpenMPTargetParallelForSimdDirective( |
8927 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8928 | SourceLocation EndLoc, |
8929 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8930 | /// \brief Called on well-formed '\#pragma omp target simd' after parsing of |
8931 | /// the associated statement. |
8932 | StmtResult ActOnOpenMPTargetSimdDirective( |
8933 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8934 | SourceLocation EndLoc, |
8935 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8936 | /// Called on well-formed '\#pragma omp teams distribute' after parsing of |
8937 | /// the associated statement. |
8938 | StmtResult ActOnOpenMPTeamsDistributeDirective( |
8939 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8940 | SourceLocation EndLoc, |
8941 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8942 | /// Called on well-formed '\#pragma omp teams distribute simd' after parsing |
8943 | /// of the associated statement. |
8944 | StmtResult ActOnOpenMPTeamsDistributeSimdDirective( |
8945 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8946 | SourceLocation EndLoc, |
8947 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8948 | /// Called on well-formed '\#pragma omp teams distribute parallel for simd' |
8949 | /// after parsing of the associated statement. |
8950 | StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( |
8951 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8952 | SourceLocation EndLoc, |
8953 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8954 | /// Called on well-formed '\#pragma omp teams distribute parallel for' |
8955 | /// after parsing of the associated statement. |
8956 | StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( |
8957 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8958 | SourceLocation EndLoc, |
8959 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8960 | /// Called on well-formed '\#pragma omp target teams' after parsing of the |
8961 | /// associated statement. |
8962 | StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, |
8963 | Stmt *AStmt, |
8964 | SourceLocation StartLoc, |
8965 | SourceLocation EndLoc); |
8966 | /// Called on well-formed '\#pragma omp target teams distribute' after parsing |
8967 | /// of the associated statement. |
8968 | StmtResult ActOnOpenMPTargetTeamsDistributeDirective( |
8969 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8970 | SourceLocation EndLoc, |
8971 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8972 | /// Called on well-formed '\#pragma omp target teams distribute parallel for' |
8973 | /// after parsing of the associated statement. |
8974 | StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( |
8975 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8976 | SourceLocation EndLoc, |
8977 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8978 | /// Called on well-formed '\#pragma omp target teams distribute parallel for |
8979 | /// simd' after parsing of the associated statement. |
8980 | StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( |
8981 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8982 | SourceLocation EndLoc, |
8983 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8984 | /// Called on well-formed '\#pragma omp target teams distribute simd' after |
8985 | /// parsing of the associated statement. |
8986 | StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( |
8987 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, |
8988 | SourceLocation EndLoc, |
8989 | llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA); |
8990 | |
8991 | /// Checks correctness of linear modifiers. |
8992 | bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, |
8993 | SourceLocation LinLoc); |
8994 | /// Checks that the specified declaration matches requirements for the linear |
8995 | /// decls. |
8996 | bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, |
8997 | OpenMPLinearClauseKind LinKind, QualType Type); |
8998 | |
8999 | /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of |
9000 | /// the associated method/function. |
9001 | DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( |
9002 | DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, |
9003 | Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, |
9004 | ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, |
9005 | ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); |
9006 | |
9007 | OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, |
9008 | Expr *Expr, |
9009 | SourceLocation StartLoc, |
9010 | SourceLocation LParenLoc, |
9011 | SourceLocation EndLoc); |
9012 | /// \brief Called on well-formed 'if' clause. |
9013 | OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, |
9014 | Expr *Condition, SourceLocation StartLoc, |
9015 | SourceLocation LParenLoc, |
9016 | SourceLocation NameModifierLoc, |
9017 | SourceLocation ColonLoc, |
9018 | SourceLocation EndLoc); |
9019 | /// \brief Called on well-formed 'final' clause. |
9020 | OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, |
9021 | SourceLocation LParenLoc, |
9022 | SourceLocation EndLoc); |
9023 | /// \brief Called on well-formed 'num_threads' clause. |
9024 | OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, |
9025 | SourceLocation StartLoc, |
9026 | SourceLocation LParenLoc, |
9027 | SourceLocation EndLoc); |
9028 | /// \brief Called on well-formed 'safelen' clause. |
9029 | OMPClause *ActOnOpenMPSafelenClause(Expr *Length, |
9030 | SourceLocation StartLoc, |
9031 | SourceLocation LParenLoc, |
9032 | SourceLocation EndLoc); |
9033 | /// \brief Called on well-formed 'simdlen' clause. |
9034 | OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, |
9035 | SourceLocation LParenLoc, |
9036 | SourceLocation EndLoc); |
9037 | /// \brief Called on well-formed 'collapse' clause. |
9038 | OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, |
9039 | SourceLocation StartLoc, |
9040 | SourceLocation LParenLoc, |
9041 | SourceLocation EndLoc); |
9042 | /// \brief Called on well-formed 'ordered' clause. |
9043 | OMPClause * |
9044 | ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, |
9045 | SourceLocation LParenLoc = SourceLocation(), |
9046 | Expr *NumForLoops = nullptr); |
9047 | /// \brief Called on well-formed 'grainsize' clause. |
9048 | OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, |
9049 | SourceLocation LParenLoc, |
9050 | SourceLocation EndLoc); |
9051 | /// \brief Called on well-formed 'num_tasks' clause. |
9052 | OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, |
9053 | SourceLocation LParenLoc, |
9054 | SourceLocation EndLoc); |
9055 | /// \brief Called on well-formed 'hint' clause. |
9056 | OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, |
9057 | SourceLocation LParenLoc, |
9058 | SourceLocation EndLoc); |
9059 | |
9060 | OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, |
9061 | unsigned Argument, |
9062 | SourceLocation ArgumentLoc, |
9063 | SourceLocation StartLoc, |
9064 | SourceLocation LParenLoc, |
9065 | SourceLocation EndLoc); |
9066 | /// \brief Called on well-formed 'default' clause. |
9067 | OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, |
9068 | SourceLocation KindLoc, |
9069 | SourceLocation StartLoc, |
9070 | SourceLocation LParenLoc, |
9071 | SourceLocation EndLoc); |
9072 | /// \brief Called on well-formed 'proc_bind' clause. |
9073 | OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, |
9074 | SourceLocation KindLoc, |
9075 | SourceLocation StartLoc, |
9076 | SourceLocation LParenLoc, |
9077 | SourceLocation EndLoc); |
9078 | |
9079 | OMPClause *ActOnOpenMPSingleExprWithArgClause( |
9080 | OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, |
9081 | SourceLocation StartLoc, SourceLocation LParenLoc, |
9082 | ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, |
9083 | SourceLocation EndLoc); |
9084 | /// \brief Called on well-formed 'schedule' clause. |
9085 | OMPClause *ActOnOpenMPScheduleClause( |
9086 | OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, |
9087 | OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, |
9088 | SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, |
9089 | SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); |
9090 | |
9091 | OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, |
9092 | SourceLocation EndLoc); |
9093 | /// \brief Called on well-formed 'nowait' clause. |
9094 | OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, |
9095 | SourceLocation EndLoc); |
9096 | /// \brief Called on well-formed 'untied' clause. |
9097 | OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, |
9098 | SourceLocation EndLoc); |
9099 | /// \brief Called on well-formed 'mergeable' clause. |
9100 | OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, |
9101 | SourceLocation EndLoc); |
9102 | /// \brief Called on well-formed 'read' clause. |
9103 | OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, |
9104 | SourceLocation EndLoc); |
9105 | /// \brief Called on well-formed 'write' clause. |
9106 | OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, |
9107 | SourceLocation EndLoc); |
9108 | /// \brief Called on well-formed 'update' clause. |
9109 | OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, |
9110 | SourceLocation EndLoc); |
9111 | /// \brief Called on well-formed 'capture' clause. |
9112 | OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, |
9113 | SourceLocation EndLoc); |
9114 | /// \brief Called on well-formed 'seq_cst' clause. |
9115 | OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, |
9116 | SourceLocation EndLoc); |
9117 | /// \brief Called on well-formed 'threads' clause. |
9118 | OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, |
9119 | SourceLocation EndLoc); |
9120 | /// \brief Called on well-formed 'simd' clause. |
9121 | OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, |
9122 | SourceLocation EndLoc); |
9123 | /// \brief Called on well-formed 'nogroup' clause. |
9124 | OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, |
9125 | SourceLocation EndLoc); |
9126 | |
9127 | OMPClause *ActOnOpenMPVarListClause( |
9128 | OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, |
9129 | SourceLocation StartLoc, SourceLocation LParenLoc, |
9130 | SourceLocation ColonLoc, SourceLocation EndLoc, |
9131 | CXXScopeSpec &ReductionIdScopeSpec, |
9132 | const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, |
9133 | OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, |
9134 | OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, |
9135 | SourceLocation DepLinMapLoc); |
9136 | /// \brief Called on well-formed 'private' clause. |
9137 | OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, |
9138 | SourceLocation StartLoc, |
9139 | SourceLocation LParenLoc, |
9140 | SourceLocation EndLoc); |
9141 | /// \brief Called on well-formed 'firstprivate' clause. |
9142 | OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, |
9143 | SourceLocation StartLoc, |
9144 | SourceLocation LParenLoc, |
9145 | SourceLocation EndLoc); |
9146 | /// \brief Called on well-formed 'lastprivate' clause. |
9147 | OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, |
9148 | SourceLocation StartLoc, |
9149 | SourceLocation LParenLoc, |
9150 | SourceLocation EndLoc); |
9151 | /// \brief Called on well-formed 'shared' clause. |
9152 | OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, |
9153 | SourceLocation StartLoc, |
9154 | SourceLocation LParenLoc, |
9155 | SourceLocation EndLoc); |
9156 | /// \brief Called on well-formed 'reduction' clause. |
9157 | OMPClause *ActOnOpenMPReductionClause( |
9158 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, |
9159 | SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, |
9160 | CXXScopeSpec &ReductionIdScopeSpec, |
9161 | const DeclarationNameInfo &ReductionId, |
9162 | ArrayRef<Expr *> UnresolvedReductions = llvm::None); |
9163 | /// Called on well-formed 'task_reduction' clause. |
9164 | OMPClause *ActOnOpenMPTaskReductionClause( |
9165 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, |
9166 | SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, |
9167 | CXXScopeSpec &ReductionIdScopeSpec, |
9168 | const DeclarationNameInfo &ReductionId, |
9169 | ArrayRef<Expr *> UnresolvedReductions = llvm::None); |
9170 | /// Called on well-formed 'in_reduction' clause. |
9171 | OMPClause *ActOnOpenMPInReductionClause( |
9172 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, |
9173 | SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, |
9174 | CXXScopeSpec &ReductionIdScopeSpec, |
9175 | const DeclarationNameInfo &ReductionId, |
9176 | ArrayRef<Expr *> UnresolvedReductions = llvm::None); |
9177 | /// \brief Called on well-formed 'linear' clause. |
9178 | OMPClause * |
9179 | ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, |
9180 | SourceLocation StartLoc, SourceLocation LParenLoc, |
9181 | OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, |
9182 | SourceLocation ColonLoc, SourceLocation EndLoc); |
9183 | /// \brief Called on well-formed 'aligned' clause. |
9184 | OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, |
9185 | Expr *Alignment, |
9186 | SourceLocation StartLoc, |
9187 | SourceLocation LParenLoc, |
9188 | SourceLocation ColonLoc, |
9189 | SourceLocation EndLoc); |
9190 | /// \brief Called on well-formed 'copyin' clause. |
9191 | OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, |
9192 | SourceLocation StartLoc, |
9193 | SourceLocation LParenLoc, |
9194 | SourceLocation EndLoc); |
9195 | /// \brief Called on well-formed 'copyprivate' clause. |
9196 | OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, |
9197 | SourceLocation StartLoc, |
9198 | SourceLocation LParenLoc, |
9199 | SourceLocation EndLoc); |
9200 | /// \brief Called on well-formed 'flush' pseudo clause. |
9201 | OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, |
9202 | SourceLocation StartLoc, |
9203 | SourceLocation LParenLoc, |
9204 | SourceLocation EndLoc); |
9205 | /// \brief Called on well-formed 'depend' clause. |
9206 | OMPClause * |
9207 | ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, |
9208 | SourceLocation ColonLoc, ArrayRef<Expr *> VarList, |
9209 | SourceLocation StartLoc, SourceLocation LParenLoc, |
9210 | SourceLocation EndLoc); |
9211 | /// \brief Called on well-formed 'device' clause. |
9212 | OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, |
9213 | SourceLocation LParenLoc, |
9214 | SourceLocation EndLoc); |
9215 | /// \brief Called on well-formed 'map' clause. |
9216 | OMPClause * |
9217 | ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, |
9218 | OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, |
9219 | SourceLocation MapLoc, SourceLocation ColonLoc, |
9220 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, |
9221 | SourceLocation LParenLoc, SourceLocation EndLoc); |
9222 | /// \brief Called on well-formed 'num_teams' clause. |
9223 | OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, |
9224 | SourceLocation LParenLoc, |
9225 | SourceLocation EndLoc); |
9226 | /// \brief Called on well-formed 'thread_limit' clause. |
9227 | OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, |
9228 | SourceLocation StartLoc, |
9229 | SourceLocation LParenLoc, |
9230 | SourceLocation EndLoc); |
9231 | /// \brief Called on well-formed 'priority' clause. |
9232 | OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, |
9233 | SourceLocation LParenLoc, |
9234 | SourceLocation EndLoc); |
9235 | /// \brief Called on well-formed 'dist_schedule' clause. |
9236 | OMPClause *ActOnOpenMPDistScheduleClause( |
9237 | OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, |
9238 | SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, |
9239 | SourceLocation CommaLoc, SourceLocation EndLoc); |
9240 | /// \brief Called on well-formed 'defaultmap' clause. |
9241 | OMPClause *ActOnOpenMPDefaultmapClause( |
9242 | OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, |
9243 | SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, |
9244 | SourceLocation KindLoc, SourceLocation EndLoc); |
9245 | /// \brief Called on well-formed 'to' clause. |
9246 | OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList, |
9247 | SourceLocation StartLoc, |
9248 | SourceLocation LParenLoc, |
9249 | SourceLocation EndLoc); |
9250 | /// \brief Called on well-formed 'from' clause. |
9251 | OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, |
9252 | SourceLocation StartLoc, |
9253 | SourceLocation LParenLoc, |
9254 | SourceLocation EndLoc); |
9255 | /// Called on well-formed 'use_device_ptr' clause. |
9256 | OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, |
9257 | SourceLocation StartLoc, |
9258 | SourceLocation LParenLoc, |
9259 | SourceLocation EndLoc); |
9260 | /// Called on well-formed 'is_device_ptr' clause. |
9261 | OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, |
9262 | SourceLocation StartLoc, |
9263 | SourceLocation LParenLoc, |
9264 | SourceLocation EndLoc); |
9265 | |
9266 | /// \brief The kind of conversion being performed. |
9267 | enum CheckedConversionKind { |
9268 | /// \brief An implicit conversion. |
9269 | CCK_ImplicitConversion, |
9270 | /// \brief A C-style cast. |
9271 | CCK_CStyleCast, |
9272 | /// \brief A functional-style cast. |
9273 | CCK_FunctionalCast, |
9274 | /// \brief A cast other than a C-style cast. |
9275 | CCK_OtherCast |
9276 | }; |
9277 | |
9278 | /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit |
9279 | /// cast. If there is already an implicit cast, merge into the existing one. |
9280 | /// If isLvalue, the result of the cast is an lvalue. |
9281 | ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, |
9282 | ExprValueKind VK = VK_RValue, |
9283 | const CXXCastPath *BasePath = nullptr, |
9284 | CheckedConversionKind CCK |
9285 | = CCK_ImplicitConversion); |
9286 | |
9287 | /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding |
9288 | /// to the conversion from scalar type ScalarTy to the Boolean type. |
9289 | static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); |
9290 | |
9291 | /// IgnoredValueConversions - Given that an expression's result is |
9292 | /// syntactically ignored, perform any conversions that are |
9293 | /// required. |
9294 | ExprResult IgnoredValueConversions(Expr *E); |
9295 | |
9296 | // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts |
9297 | // functions and arrays to their respective pointers (C99 6.3.2.1). |
9298 | ExprResult UsualUnaryConversions(Expr *E); |
9299 | |
9300 | /// CallExprUnaryConversions - a special case of an unary conversion |
9301 | /// performed on a function designator of a call expression. |
9302 | ExprResult CallExprUnaryConversions(Expr *E); |
9303 | |
9304 | // DefaultFunctionArrayConversion - converts functions and arrays |
9305 | // to their respective pointers (C99 6.3.2.1). |
9306 | ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); |
9307 | |
9308 | // DefaultFunctionArrayLvalueConversion - converts functions and |
9309 | // arrays to their respective pointers and performs the |
9310 | // lvalue-to-rvalue conversion. |
9311 | ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, |
9312 | bool Diagnose = true); |
9313 | |
9314 | // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on |
9315 | // the operand. This is DefaultFunctionArrayLvalueConversion, |
9316 | // except that it assumes the operand isn't of function or array |
9317 | // type. |
9318 | ExprResult DefaultLvalueConversion(Expr *E); |
9319 | |
9320 | // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that |
9321 | // do not have a prototype. Integer promotions are performed on each |
9322 | // argument, and arguments that have type float are promoted to double. |
9323 | ExprResult DefaultArgumentPromotion(Expr *E); |
9324 | |
9325 | /// If \p E is a prvalue denoting an unmaterialized temporary, materialize |
9326 | /// it as an xvalue. In C++98, the result will still be a prvalue, because |
9327 | /// we don't have xvalues there. |
9328 | ExprResult TemporaryMaterializationConversion(Expr *E); |
9329 | |
9330 | // Used for emitting the right warning by DefaultVariadicArgumentPromotion |
9331 | enum VariadicCallType { |
9332 | VariadicFunction, |
9333 | VariadicBlock, |
9334 | VariadicMethod, |
9335 | VariadicConstructor, |
9336 | VariadicDoesNotApply |
9337 | }; |
9338 | |
9339 | VariadicCallType getVariadicCallType(FunctionDecl *FDecl, |
9340 | const FunctionProtoType *Proto, |
9341 | Expr *Fn); |
9342 | |
9343 | // Used for determining in which context a type is allowed to be passed to a |
9344 | // vararg function. |
9345 | enum VarArgKind { |
9346 | VAK_Valid, |
9347 | VAK_ValidInCXX11, |
9348 | VAK_Undefined, |
9349 | VAK_MSVCUndefined, |
9350 | VAK_Invalid |
9351 | }; |
9352 | |
9353 | // Determines which VarArgKind fits an expression. |
9354 | VarArgKind isValidVarArgType(const QualType &Ty); |
9355 | |
9356 | /// Check to see if the given expression is a valid argument to a variadic |
9357 | /// function, issuing a diagnostic if not. |
9358 | void checkVariadicArgument(const Expr *E, VariadicCallType CT); |
9359 | |
9360 | /// Check to see if a given expression could have '.c_str()' called on it. |
9361 | bool hasCStrMethod(const Expr *E); |
9362 | |
9363 | /// GatherArgumentsForCall - Collector argument expressions for various |
9364 | /// form of call prototypes. |
9365 | bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, |
9366 | const FunctionProtoType *Proto, |
9367 | unsigned FirstParam, ArrayRef<Expr *> Args, |
9368 | SmallVectorImpl<Expr *> &AllArgs, |
9369 | VariadicCallType CallType = VariadicDoesNotApply, |
9370 | bool AllowExplicit = false, |
9371 | bool IsListInitialization = false); |
9372 | |
9373 | // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but |
9374 | // will create a runtime trap if the resulting type is not a POD type. |
9375 | ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, |
9376 | FunctionDecl *FDecl); |
9377 | |
9378 | // UsualArithmeticConversions - performs the UsualUnaryConversions on it's |
9379 | // operands and then handles various conversions that are common to binary |
9380 | // operators (C99 6.3.1.8). If both operands aren't arithmetic, this |
9381 | // routine returns the first non-arithmetic type found. The client is |
9382 | // responsible for emitting appropriate error diagnostics. |
9383 | QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, |
9384 | bool IsCompAssign = false); |
9385 | |
9386 | /// AssignConvertType - All of the 'assignment' semantic checks return this |
9387 | /// enum to indicate whether the assignment was allowed. These checks are |
9388 | /// done for simple assignments, as well as initialization, return from |
9389 | /// function, argument passing, etc. The query is phrased in terms of a |
9390 | /// source and destination type. |
9391 | enum AssignConvertType { |
9392 | /// Compatible - the types are compatible according to the standard. |
9393 | Compatible, |
9394 | |
9395 | /// PointerToInt - The assignment converts a pointer to an int, which we |
9396 | /// accept as an extension. |
9397 | PointerToInt, |
9398 | |
9399 | /// IntToPointer - The assignment converts an int to a pointer, which we |
9400 | /// accept as an extension. |
9401 | IntToPointer, |
9402 | |
9403 | /// FunctionVoidPointer - The assignment is between a function pointer and |
9404 | /// void*, which the standard doesn't allow, but we accept as an extension. |
9405 | FunctionVoidPointer, |
9406 | |
9407 | /// IncompatiblePointer - The assignment is between two pointers types that |
9408 | /// are not compatible, but we accept them as an extension. |
9409 | IncompatiblePointer, |
9410 | |
9411 | /// IncompatiblePointerSign - The assignment is between two pointers types |
9412 | /// which point to integers which have a different sign, but are otherwise |
9413 | /// identical. This is a subset of the above, but broken out because it's by |
9414 | /// far the most common case of incompatible pointers. |
9415 | IncompatiblePointerSign, |
9416 | |
9417 | /// CompatiblePointerDiscardsQualifiers - The assignment discards |
9418 | /// c/v/r qualifiers, which we accept as an extension. |
9419 | CompatiblePointerDiscardsQualifiers, |
9420 | |
9421 | /// IncompatiblePointerDiscardsQualifiers - The assignment |
9422 | /// discards qualifiers that we don't permit to be discarded, |
9423 | /// like address spaces. |
9424 | IncompatiblePointerDiscardsQualifiers, |
9425 | |
9426 | /// IncompatibleNestedPointerQualifiers - The assignment is between two |
9427 | /// nested pointer types, and the qualifiers other than the first two |
9428 | /// levels differ e.g. char ** -> const char **, but we accept them as an |
9429 | /// extension. |
9430 | IncompatibleNestedPointerQualifiers, |
9431 | |
9432 | /// IncompatibleVectors - The assignment is between two vector types that |
9433 | /// have the same size, which we accept as an extension. |
9434 | IncompatibleVectors, |
9435 | |
9436 | /// IntToBlockPointer - The assignment converts an int to a block |
9437 | /// pointer. We disallow this. |
9438 | IntToBlockPointer, |
9439 | |
9440 | /// IncompatibleBlockPointer - The assignment is between two block |
9441 | /// pointers types that are not compatible. |
9442 | IncompatibleBlockPointer, |
9443 | |
9444 | /// IncompatibleObjCQualifiedId - The assignment is between a qualified |
9445 | /// id type and something else (that is incompatible with it). For example, |
9446 | /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. |
9447 | IncompatibleObjCQualifiedId, |
9448 | |
9449 | /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an |
9450 | /// object with __weak qualifier. |
9451 | IncompatibleObjCWeakRef, |
9452 | |
9453 | /// Incompatible - We reject this conversion outright, it is invalid to |
9454 | /// represent it in the AST. |
9455 | Incompatible |
9456 | }; |
9457 | |
9458 | /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the |
9459 | /// assignment conversion type specified by ConvTy. This returns true if the |
9460 | /// conversion was invalid or false if the conversion was accepted. |
9461 | bool DiagnoseAssignmentResult(AssignConvertType ConvTy, |
9462 | SourceLocation Loc, |
9463 | QualType DstType, QualType SrcType, |
9464 | Expr *SrcExpr, AssignmentAction Action, |
9465 | bool *Complained = nullptr); |
9466 | |
9467 | /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag |
9468 | /// enum. If AllowMask is true, then we also allow the complement of a valid |
9469 | /// value, to be used as a mask. |
9470 | bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, |
9471 | bool AllowMask) const; |
9472 | |
9473 | /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant |
9474 | /// integer not in the range of enum values. |
9475 | void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, |
9476 | Expr *SrcExpr); |
9477 | |
9478 | /// CheckAssignmentConstraints - Perform type checking for assignment, |
9479 | /// argument passing, variable initialization, and function return values. |
9480 | /// C99 6.5.16. |
9481 | AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, |
9482 | QualType LHSType, |
9483 | QualType RHSType); |
9484 | |
9485 | /// Check assignment constraints and optionally prepare for a conversion of |
9486 | /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS |
9487 | /// is true. |
9488 | AssignConvertType CheckAssignmentConstraints(QualType LHSType, |
9489 | ExprResult &RHS, |
9490 | CastKind &Kind, |
9491 | bool ConvertRHS = true); |
9492 | |
9493 | /// Check assignment constraints for an assignment of RHS to LHSType. |
9494 | /// |
9495 | /// \param LHSType The destination type for the assignment. |
9496 | /// \param RHS The source expression for the assignment. |
9497 | /// \param Diagnose If \c true, diagnostics may be produced when checking |
9498 | /// for assignability. If a diagnostic is produced, \p RHS will be |
9499 | /// set to ExprError(). Note that this function may still return |
9500 | /// without producing a diagnostic, even for an invalid assignment. |
9501 | /// \param DiagnoseCFAudited If \c true, the target is a function parameter |
9502 | /// in an audited Core Foundation API and does not need to be checked |
9503 | /// for ARC retain issues. |
9504 | /// \param ConvertRHS If \c true, \p RHS will be updated to model the |
9505 | /// conversions necessary to perform the assignment. If \c false, |
9506 | /// \p Diagnose must also be \c false. |
9507 | AssignConvertType CheckSingleAssignmentConstraints( |
9508 | QualType LHSType, ExprResult &RHS, bool Diagnose = true, |
9509 | bool DiagnoseCFAudited = false, bool ConvertRHS = true); |
9510 | |
9511 | // \brief If the lhs type is a transparent union, check whether we |
9512 | // can initialize the transparent union with the given expression. |
9513 | AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, |
9514 | ExprResult &RHS); |
9515 | |
9516 | bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); |
9517 | |
9518 | bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); |
9519 | |
9520 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
9521 | AssignmentAction Action, |
9522 | bool AllowExplicit = false); |
9523 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
9524 | AssignmentAction Action, |
9525 | bool AllowExplicit, |
9526 | ImplicitConversionSequence& ICS); |
9527 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
9528 | const ImplicitConversionSequence& ICS, |
9529 | AssignmentAction Action, |
9530 | CheckedConversionKind CCK |
9531 | = CCK_ImplicitConversion); |
9532 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, |
9533 | const StandardConversionSequence& SCS, |
9534 | AssignmentAction Action, |
9535 | CheckedConversionKind CCK); |
9536 | |
9537 | /// the following "Check" methods will return a valid/converted QualType |
9538 | /// or a null QualType (indicating an error diagnostic was issued). |
9539 | |
9540 | /// type checking binary operators (subroutines of CreateBuiltinBinOp). |
9541 | QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, |
9542 | ExprResult &RHS); |
9543 | QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, |
9544 | ExprResult &RHS); |
9545 | QualType CheckPointerToMemberOperands( // C++ 5.5 |
9546 | ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, |
9547 | SourceLocation OpLoc, bool isIndirect); |
9548 | QualType CheckMultiplyDivideOperands( // C99 6.5.5 |
9549 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, |
9550 | bool IsDivide); |
9551 | QualType CheckRemainderOperands( // C99 6.5.5 |
9552 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9553 | bool IsCompAssign = false); |
9554 | QualType CheckAdditionOperands( // C99 6.5.6 |
9555 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9556 | BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); |
9557 | QualType CheckSubtractionOperands( // C99 6.5.6 |
9558 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9559 | QualType* CompLHSTy = nullptr); |
9560 | QualType CheckShiftOperands( // C99 6.5.7 |
9561 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9562 | BinaryOperatorKind Opc, bool IsCompAssign = false); |
9563 | QualType CheckCompareOperands( // C99 6.5.8/9 |
9564 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9565 | BinaryOperatorKind Opc, bool isRelational); |
9566 | QualType CheckBitwiseOperands( // C99 6.5.[10...12] |
9567 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9568 | BinaryOperatorKind Opc); |
9569 | QualType CheckLogicalOperands( // C99 6.5.[13,14] |
9570 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, |
9571 | BinaryOperatorKind Opc); |
9572 | // CheckAssignmentOperands is used for both simple and compound assignment. |
9573 | // For simple assignment, pass both expressions and a null converted type. |
9574 | // For compound assignment, pass both expressions and the converted type. |
9575 | QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] |
9576 | Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); |
9577 | |
9578 | ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, |
9579 | UnaryOperatorKind Opcode, Expr *Op); |
9580 | ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, |
9581 | BinaryOperatorKind Opcode, |
9582 | Expr *LHS, Expr *RHS); |
9583 | ExprResult checkPseudoObjectRValue(Expr *E); |
9584 | Expr *recreateSyntacticForm(PseudoObjectExpr *E); |
9585 | |
9586 | QualType CheckConditionalOperands( // C99 6.5.15 |
9587 | ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, |
9588 | ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); |
9589 | QualType CXXCheckConditionalOperands( // C++ 5.16 |
9590 | ExprResult &cond, ExprResult &lhs, ExprResult &rhs, |
9591 | ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); |
9592 | QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, |
9593 | bool ConvertArgs = true); |
9594 | QualType FindCompositePointerType(SourceLocation Loc, |
9595 | ExprResult &E1, ExprResult &E2, |
9596 | bool ConvertArgs = true) { |
9597 | Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); |
9598 | QualType Composite = |
9599 | FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); |
9600 | E1 = E1Tmp; |
9601 | E2 = E2Tmp; |
9602 | return Composite; |
9603 | } |
9604 | |
9605 | QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, |
9606 | SourceLocation QuestionLoc); |
9607 | |
9608 | bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, |
9609 | SourceLocation QuestionLoc); |
9610 | |
9611 | void DiagnoseAlwaysNonNullPointer(Expr *E, |
9612 | Expr::NullPointerConstantKind NullType, |
9613 | bool IsEqual, SourceRange Range); |
9614 | |
9615 | /// type checking for vector binary operators. |
9616 | QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, |
9617 | SourceLocation Loc, bool IsCompAssign, |
9618 | bool AllowBothBool, bool AllowBoolConversion); |
9619 | QualType GetSignedVectorType(QualType V); |
9620 | QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, |
9621 | SourceLocation Loc, |
9622 | BinaryOperatorKind Opc); |
9623 | QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
9624 | SourceLocation Loc); |
9625 | |
9626 | bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); |
9627 | bool isLaxVectorConversion(QualType srcType, QualType destType); |
9628 | |
9629 | /// type checking declaration initializers (C99 6.7.8) |
9630 | bool CheckForConstantInitializer(Expr *e, QualType t); |
9631 | |
9632 | // type checking C++ declaration initializers (C++ [dcl.init]). |
9633 | |
9634 | /// ReferenceCompareResult - Expresses the result of comparing two |
9635 | /// types (cv1 T1 and cv2 T2) to determine their compatibility for the |
9636 | /// purposes of initialization by reference (C++ [dcl.init.ref]p4). |
9637 | enum ReferenceCompareResult { |
9638 | /// Ref_Incompatible - The two types are incompatible, so direct |
9639 | /// reference binding is not possible. |
9640 | Ref_Incompatible = 0, |
9641 | /// Ref_Related - The two types are reference-related, which means |
9642 | /// that their unqualified forms (T1 and T2) are either the same |
9643 | /// or T1 is a base class of T2. |
9644 | Ref_Related, |
9645 | /// Ref_Compatible - The two types are reference-compatible. |
9646 | Ref_Compatible |
9647 | }; |
9648 | |
9649 | ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, |
9650 | QualType T1, QualType T2, |
9651 | bool &DerivedToBase, |
9652 | bool &ObjCConversion, |
9653 | bool &ObjCLifetimeConversion); |
9654 | |
9655 | ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, |
9656 | Expr *CastExpr, CastKind &CastKind, |
9657 | ExprValueKind &VK, CXXCastPath &Path); |
9658 | |
9659 | /// \brief Force an expression with unknown-type to an expression of the |
9660 | /// given type. |
9661 | ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); |
9662 | |
9663 | /// \brief Type-check an expression that's being passed to an |
9664 | /// __unknown_anytype parameter. |
9665 | ExprResult checkUnknownAnyArg(SourceLocation callLoc, |
9666 | Expr *result, QualType ¶mType); |
9667 | |
9668 | // CheckVectorCast - check type constraints for vectors. |
9669 | // Since vectors are an extension, there are no C standard reference for this. |
9670 | // We allow casting between vectors and integer datatypes of the same size. |
9671 | // returns true if the cast is invalid |
9672 | bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, |
9673 | CastKind &Kind); |
9674 | |
9675 | /// \brief Prepare `SplattedExpr` for a vector splat operation, adding |
9676 | /// implicit casts if necessary. |
9677 | ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); |
9678 | |
9679 | // CheckExtVectorCast - check type constraints for extended vectors. |
9680 | // Since vectors are an extension, there are no C standard reference for this. |
9681 | // We allow casting between vectors and integer datatypes of the same size, |
9682 | // or vectors and the element type of that vector. |
9683 | // returns the cast expr |
9684 | ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, |
9685 | CastKind &Kind); |
9686 | |
9687 | ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, |
9688 | SourceLocation LParenLoc, |
9689 | Expr *CastExpr, |
9690 | SourceLocation RParenLoc); |
9691 | |
9692 | enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; |
9693 | |
9694 | /// \brief Checks for invalid conversions and casts between |
9695 | /// retainable pointers and other pointer kinds for ARC and Weak. |
9696 | ARCConversionResult CheckObjCConversion(SourceRange castRange, |
9697 | QualType castType, Expr *&op, |
9698 | CheckedConversionKind CCK, |
9699 | bool Diagnose = true, |
9700 | bool DiagnoseCFAudited = false, |
9701 | BinaryOperatorKind Opc = BO_PtrMemD |
9702 | ); |
9703 | |
9704 | Expr *stripARCUnbridgedCast(Expr *e); |
9705 | void diagnoseARCUnbridgedCast(Expr *e); |
9706 | |
9707 | bool CheckObjCARCUnavailableWeakConversion(QualType castType, |
9708 | QualType ExprType); |
9709 | |
9710 | /// checkRetainCycles - Check whether an Objective-C message send |
9711 | /// might create an obvious retain cycle. |
9712 | void checkRetainCycles(ObjCMessageExpr *msg); |
9713 | void checkRetainCycles(Expr *receiver, Expr *argument); |
9714 | void checkRetainCycles(VarDecl *Var, Expr *Init); |
9715 | |
9716 | /// checkUnsafeAssigns - Check whether +1 expr is being assigned |
9717 | /// to weak/__unsafe_unretained type. |
9718 | bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); |
9719 | |
9720 | /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned |
9721 | /// to weak/__unsafe_unretained expression. |
9722 | void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); |
9723 | |
9724 | /// CheckMessageArgumentTypes - Check types in an Obj-C message send. |
9725 | /// \param Method - May be null. |
9726 | /// \param [out] ReturnType - The return type of the send. |
9727 | /// \return true iff there were any incompatible types. |
9728 | bool CheckMessageArgumentTypes(QualType ReceiverType, |
9729 | MultiExprArg Args, Selector Sel, |
9730 | ArrayRef<SourceLocation> SelectorLocs, |
9731 | ObjCMethodDecl *Method, bool isClassMessage, |
9732 | bool isSuperMessage, |
9733 | SourceLocation lbrac, SourceLocation rbrac, |
9734 | SourceRange RecRange, |
9735 | QualType &ReturnType, ExprValueKind &VK); |
9736 | |
9737 | /// \brief Determine the result of a message send expression based on |
9738 | /// the type of the receiver, the method expected to receive the message, |
9739 | /// and the form of the message send. |
9740 | QualType getMessageSendResultType(QualType ReceiverType, |
9741 | ObjCMethodDecl *Method, |
9742 | bool isClassMessage, bool isSuperMessage); |
9743 | |
9744 | /// \brief If the given expression involves a message send to a method |
9745 | /// with a related result type, emit a note describing what happened. |
9746 | void EmitRelatedResultTypeNote(const Expr *E); |
9747 | |
9748 | /// \brief Given that we had incompatible pointer types in a return |
9749 | /// statement, check whether we're in a method with a related result |
9750 | /// type, and if so, emit a note describing what happened. |
9751 | void EmitRelatedResultTypeNoteForReturn(QualType destType); |
9752 | |
9753 | class ConditionResult { |
9754 | Decl *ConditionVar; |
9755 | FullExprArg Condition; |
9756 | bool Invalid; |
9757 | bool HasKnownValue; |
9758 | bool KnownValue; |
9759 | |
9760 | friend class Sema; |
9761 | ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, |
9762 | bool IsConstexpr) |
9763 | : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), |
9764 | HasKnownValue(IsConstexpr && Condition.get() && |
9765 | !Condition.get()->isValueDependent()), |
9766 | KnownValue(HasKnownValue && |
9767 | !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} |
9768 | explicit ConditionResult(bool Invalid) |
9769 | : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), |
9770 | HasKnownValue(false), KnownValue(false) {} |
9771 | |
9772 | public: |
9773 | ConditionResult() : ConditionResult(false) {} |
9774 | bool isInvalid() const { return Invalid; } |
9775 | std::pair<VarDecl *, Expr *> get() const { |
9776 | return std::make_pair(cast_or_null<VarDecl>(ConditionVar), |
9777 | Condition.get()); |
9778 | } |
9779 | llvm::Optional<bool> getKnownValue() const { |
9780 | if (!HasKnownValue) |
9781 | return None; |
9782 | return KnownValue; |
9783 | } |
9784 | }; |
9785 | static ConditionResult ConditionError() { return ConditionResult(true); } |
9786 | |
9787 | enum class ConditionKind { |
9788 | Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. |
9789 | ConstexprIf, ///< A constant boolean condition from 'if constexpr'. |
9790 | Switch ///< An integral condition for a 'switch' statement. |
9791 | }; |
9792 | |
9793 | ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, |
9794 | Expr *SubExpr, ConditionKind CK); |
9795 | |
9796 | ConditionResult ActOnConditionVariable(Decl *ConditionVar, |
9797 | SourceLocation StmtLoc, |
9798 | ConditionKind CK); |
9799 | |
9800 | DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); |
9801 | |
9802 | ExprResult CheckConditionVariable(VarDecl *ConditionVar, |
9803 | SourceLocation StmtLoc, |
9804 | ConditionKind CK); |
9805 | ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); |
9806 | |
9807 | /// CheckBooleanCondition - Diagnose problems involving the use of |
9808 | /// the given expression as a boolean condition (e.g. in an if |
9809 | /// statement). Also performs the standard function and array |
9810 | /// decays, possibly changing the input variable. |
9811 | /// |
9812 | /// \param Loc - A location associated with the condition, e.g. the |
9813 | /// 'if' keyword. |
9814 | /// \return true iff there were any errors |
9815 | ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, |
9816 | bool IsConstexpr = false); |
9817 | |
9818 | /// DiagnoseAssignmentAsCondition - Given that an expression is |
9819 | /// being used as a boolean condition, warn if it's an assignment. |
9820 | void DiagnoseAssignmentAsCondition(Expr *E); |
9821 | |
9822 | /// \brief Redundant parentheses over an equality comparison can indicate |
9823 | /// that the user intended an assignment used as condition. |
9824 | void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); |
9825 | |
9826 | /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. |
9827 | ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); |
9828 | |
9829 | /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have |
9830 | /// the specified width and sign. If an overflow occurs, detect it and emit |
9831 | /// the specified diagnostic. |
9832 | void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, |
9833 | unsigned NewWidth, bool NewSign, |
9834 | SourceLocation Loc, unsigned DiagID); |
9835 | |
9836 | /// Checks that the Objective-C declaration is declared in the global scope. |
9837 | /// Emits an error and marks the declaration as invalid if it's not declared |
9838 | /// in the global scope. |
9839 | bool CheckObjCDeclScope(Decl *D); |
9840 | |
9841 | /// \brief Abstract base class used for diagnosing integer constant |
9842 | /// expression violations. |
9843 | class VerifyICEDiagnoser { |
9844 | public: |
9845 | bool Suppress; |
9846 | |
9847 | VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } |
9848 | |
9849 | virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; |
9850 | virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); |
9851 | virtual ~VerifyICEDiagnoser() { } |
9852 | }; |
9853 | |
9854 | /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, |
9855 | /// and reports the appropriate diagnostics. Returns false on success. |
9856 | /// Can optionally return the value of the expression. |
9857 | ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
9858 | VerifyICEDiagnoser &Diagnoser, |
9859 | bool AllowFold = true); |
9860 | ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
9861 | unsigned DiagID, |
9862 | bool AllowFold = true); |
9863 | ExprResult VerifyIntegerConstantExpression(Expr *E, |
9864 | llvm::APSInt *Result = nullptr); |
9865 | |
9866 | /// VerifyBitField - verifies that a bit field expression is an ICE and has |
9867 | /// the correct width, and that the field type is valid. |
9868 | /// Returns false on success. |
9869 | /// Can optionally return whether the bit-field is of width 0 |
9870 | ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, |
9871 | QualType FieldTy, bool IsMsStruct, |
9872 | Expr *BitWidth, bool *ZeroWidth = nullptr); |
9873 | |
9874 | private: |
9875 | unsigned ForceCUDAHostDeviceDepth = 0; |
9876 | |
9877 | public: |
9878 | /// Increments our count of the number of times we've seen a pragma forcing |
9879 | /// functions to be __host__ __device__. So long as this count is greater |
9880 | /// than zero, all functions encountered will be __host__ __device__. |
9881 | void PushForceCUDAHostDevice(); |
9882 | |
9883 | /// Decrements our count of the number of times we've seen a pragma forcing |
9884 | /// functions to be __host__ __device__. Returns false if the count is 0 |
9885 | /// before incrementing, so you can emit an error. |
9886 | bool PopForceCUDAHostDevice(); |
9887 | |
9888 | /// Diagnostics that are emitted only if we discover that the given function |
9889 | /// must be codegen'ed. Because handling these correctly adds overhead to |
9890 | /// compilation, this is currently only enabled for CUDA compilations. |
9891 | llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, |
9892 | std::vector<PartialDiagnosticAt>> |
9893 | CUDADeferredDiags; |
9894 | |
9895 | /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the |
9896 | /// key in a hashtable, both the FD and location are hashed. |
9897 | struct FunctionDeclAndLoc { |
9898 | CanonicalDeclPtr<FunctionDecl> FD; |
9899 | SourceLocation Loc; |
9900 | }; |
9901 | |
9902 | /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a |
9903 | /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the |
9904 | /// same deferred diag twice. |
9905 | llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; |
9906 | |
9907 | /// An inverse call graph, mapping known-emitted functions to one of their |
9908 | /// known-emitted callers (plus the location of the call). |
9909 | /// |
9910 | /// Functions that we can tell a priori must be emitted aren't added to this |
9911 | /// map. |
9912 | llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, |
9913 | /* Caller = */ FunctionDeclAndLoc> |
9914 | CUDAKnownEmittedFns; |
9915 | |
9916 | /// A partial call graph maintained during CUDA compilation to support |
9917 | /// deferred diagnostics. |
9918 | /// |
9919 | /// Functions are only added here if, at the time they're considered, they are |
9920 | /// not known-emitted. As soon as we discover that a function is |
9921 | /// known-emitted, we remove it and everything it transitively calls from this |
9922 | /// set and add those functions to CUDAKnownEmittedFns. |
9923 | llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>, |
9924 | /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>, |
9925 | SourceLocation>> |
9926 | CUDACallGraph; |
9927 | |
9928 | /// Diagnostic builder for CUDA errors which may or may not be deferred. |
9929 | /// |
9930 | /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) |
9931 | /// which are not allowed to appear inside __device__ functions and are |
9932 | /// allowed to appear in __host__ __device__ functions only if the host+device |
9933 | /// function is never codegen'ed. |
9934 | /// |
9935 | /// To handle this, we use the notion of "deferred diagnostics", where we |
9936 | /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. |
9937 | /// |
9938 | /// This class lets you emit either a regular diagnostic, a deferred |
9939 | /// diagnostic, or no diagnostic at all, according to an argument you pass to |
9940 | /// its constructor, thus simplifying the process of creating these "maybe |
9941 | /// deferred" diagnostics. |
9942 | class CUDADiagBuilder { |
9943 | public: |
9944 | enum Kind { |
9945 | /// Emit no diagnostics. |
9946 | K_Nop, |
9947 | /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). |
9948 | K_Immediate, |
9949 | /// Emit the diagnostic immediately, and, if it's a warning or error, also |
9950 | /// emit a call stack showing how this function can be reached by an a |
9951 | /// priori known-emitted function. |
9952 | K_ImmediateWithCallStack, |
9953 | /// Create a deferred diagnostic, which is emitted only if the function |
9954 | /// it's attached to is codegen'ed. Also emit a call stack as with |
9955 | /// K_ImmediateWithCallStack. |
9956 | K_Deferred |
9957 | }; |
9958 | |
9959 | CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, |
9960 | FunctionDecl *Fn, Sema &S); |
9961 | ~CUDADiagBuilder(); |
9962 | |
9963 | /// Convertible to bool: True if we immediately emitted an error, false if |
9964 | /// we didn't emit an error or we created a deferred error. |
9965 | /// |
9966 | /// Example usage: |
9967 | /// |
9968 | /// if (CUDADiagBuilder(...) << foo << bar) |
9969 | /// return ExprError(); |
9970 | /// |
9971 | /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably |
9972 | /// want to use these instead of creating a CUDADiagBuilder yourself. |
9973 | operator bool() const { return ImmediateDiag.hasValue(); } |
9974 | |
9975 | template <typename T> |
9976 | friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag, |
9977 | const T &Value) { |
9978 | if (Diag.ImmediateDiag.hasValue()) |
9979 | *Diag.ImmediateDiag << Value; |
9980 | else if (Diag.PartialDiag.hasValue()) |
9981 | *Diag.PartialDiag << Value; |
9982 | return Diag; |
9983 | } |
9984 | |
9985 | private: |
9986 | Sema &S; |
9987 | SourceLocation Loc; |
9988 | unsigned DiagID; |
9989 | FunctionDecl *Fn; |
9990 | bool ShowCallStack; |
9991 | |
9992 | // Invariant: At most one of these Optionals has a value. |
9993 | // FIXME: Switch these to a Variant once that exists. |
9994 | llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; |
9995 | llvm::Optional<PartialDiagnostic> PartialDiag; |
9996 | }; |
9997 | |
9998 | /// Creates a CUDADiagBuilder that emits the diagnostic if the current context |
9999 | /// is "used as device code". |
10000 | /// |
10001 | /// - If CurContext is a __host__ function, does not emit any diagnostics. |
10002 | /// - If CurContext is a __device__ or __global__ function, emits the |
10003 | /// diagnostics immediately. |
10004 | /// - If CurContext is a __host__ __device__ function and we are compiling for |
10005 | /// the device, creates a diagnostic which is emitted if and when we realize |
10006 | /// that the function will be codegen'ed. |
10007 | /// |
10008 | /// Example usage: |
10009 | /// |
10010 | /// // Variable-length arrays are not allowed in CUDA device code. |
10011 | /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) |
10012 | /// return ExprError(); |
10013 | /// // Otherwise, continue parsing as normal. |
10014 | CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); |
10015 | |
10016 | /// Creates a CUDADiagBuilder that emits the diagnostic if the current context |
10017 | /// is "used as host code". |
10018 | /// |
10019 | /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. |
10020 | CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); |
10021 | |
10022 | enum CUDAFunctionTarget { |
10023 | CFT_Device, |
10024 | CFT_Global, |
10025 | CFT_Host, |
10026 | CFT_HostDevice, |
10027 | CFT_InvalidTarget |
10028 | }; |
10029 | |
10030 | /// Determines whether the given function is a CUDA device/host/kernel/etc. |
10031 | /// function. |
10032 | /// |
10033 | /// Use this rather than examining the function's attributes yourself -- you |
10034 | /// will get it wrong. Returns CFT_Host if D is null. |
10035 | CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, |
10036 | bool IgnoreImplicitHDAttr = false); |
10037 | CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr); |
10038 | |
10039 | /// Gets the CUDA target for the current context. |
10040 | CUDAFunctionTarget CurrentCUDATarget() { |
10041 | return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); |
10042 | } |
10043 | |
10044 | // CUDA function call preference. Must be ordered numerically from |
10045 | // worst to best. |
10046 | enum CUDAFunctionPreference { |
10047 | CFP_Never, // Invalid caller/callee combination. |
10048 | CFP_WrongSide, // Calls from host-device to host or device |
10049 | // function that do not match current compilation |
10050 | // mode. |
10051 | CFP_HostDevice, // Any calls to host/device functions. |
10052 | CFP_SameSide, // Calls from host-device to host or device |
10053 | // function matching current compilation mode. |
10054 | CFP_Native, // host-to-host or device-to-device calls. |
10055 | }; |
10056 | |
10057 | /// Identifies relative preference of a given Caller/Callee |
10058 | /// combination, based on their host/device attributes. |
10059 | /// \param Caller function which needs address of \p Callee. |
10060 | /// nullptr in case of global context. |
10061 | /// \param Callee target function |
10062 | /// |
10063 | /// \returns preference value for particular Caller/Callee combination. |
10064 | CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, |
10065 | const FunctionDecl *Callee); |
10066 | |
10067 | /// Determines whether Caller may invoke Callee, based on their CUDA |
10068 | /// host/device attributes. Returns false if the call is not allowed. |
10069 | /// |
10070 | /// Note: Will return true for CFP_WrongSide calls. These may appear in |
10071 | /// semantically correct CUDA programs, but only if they're never codegen'ed. |
10072 | bool IsAllowedCUDACall(const FunctionDecl *Caller, |
10073 | const FunctionDecl *Callee) { |
10074 | return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; |
10075 | } |
10076 | |
10077 | /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, |
10078 | /// depending on FD and the current compilation settings. |
10079 | void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, |
10080 | const LookupResult &Previous); |
10081 | |
10082 | public: |
10083 | /// Check whether we're allowed to call Callee from the current context. |
10084 | /// |
10085 | /// - If the call is never allowed in a semantically-correct program |
10086 | /// (CFP_Never), emits an error and returns false. |
10087 | /// |
10088 | /// - If the call is allowed in semantically-correct programs, but only if |
10089 | /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to |
10090 | /// be emitted if and when the caller is codegen'ed, and returns true. |
10091 | /// |
10092 | /// Will only create deferred diagnostics for a given SourceLocation once, |
10093 | /// so you can safely call this multiple times without generating duplicate |
10094 | /// deferred errors. |
10095 | /// |
10096 | /// - Otherwise, returns true without emitting any diagnostics. |
10097 | bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); |
10098 | |
10099 | /// Set __device__ or __host__ __device__ attributes on the given lambda |
10100 | /// operator() method. |
10101 | /// |
10102 | /// CUDA lambdas declared inside __device__ or __global__ functions inherit |
10103 | /// the __device__ attribute. Similarly, lambdas inside __host__ __device__ |
10104 | /// functions become __host__ __device__ themselves. |
10105 | void CUDASetLambdaAttrs(CXXMethodDecl *Method); |
10106 | |
10107 | /// Finds a function in \p Matches with highest calling priority |
10108 | /// from \p Caller context and erases all functions with lower |
10109 | /// calling priority. |
10110 | void EraseUnwantedCUDAMatches( |
10111 | const FunctionDecl *Caller, |
10112 | SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); |
10113 | |
10114 | /// Given a implicit special member, infer its CUDA target from the |
10115 | /// calls it needs to make to underlying base/field special members. |
10116 | /// \param ClassDecl the class for which the member is being created. |
10117 | /// \param CSM the kind of special member. |
10118 | /// \param MemberDecl the special member itself. |
10119 | /// \param ConstRHS true if this is a copy operation with a const object on |
10120 | /// its RHS. |
10121 | /// \param Diagnose true if this call should emit diagnostics. |
10122 | /// \return true if there was an error inferring. |
10123 | /// The result of this call is implicit CUDA target attribute(s) attached to |
10124 | /// the member declaration. |
10125 | bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, |
10126 | CXXSpecialMember CSM, |
10127 | CXXMethodDecl *MemberDecl, |
10128 | bool ConstRHS, |
10129 | bool Diagnose); |
10130 | |
10131 | /// \return true if \p CD can be considered empty according to CUDA |
10132 | /// (E.2.3.1 in CUDA 7.5 Programming guide). |
10133 | bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); |
10134 | bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); |
10135 | |
10136 | /// Check whether NewFD is a valid overload for CUDA. Emits |
10137 | /// diagnostics and invalidates NewFD if not. |
10138 | void checkCUDATargetOverload(FunctionDecl *NewFD, |
10139 | const LookupResult &Previous); |
10140 | /// Copies target attributes from the template TD to the function FD. |
10141 | void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); |
10142 | |
10143 | /// \name Code completion |
10144 | //@{ |
10145 | /// \brief Describes the context in which code completion occurs. |
10146 | enum ParserCompletionContext { |
10147 | /// \brief Code completion occurs at top-level or namespace context. |
10148 | PCC_Namespace, |
10149 | /// \brief Code completion occurs within a class, struct, or union. |
10150 | PCC_Class, |
10151 | /// \brief Code completion occurs within an Objective-C interface, protocol, |
10152 | /// or category. |
10153 | PCC_ObjCInterface, |
10154 | /// \brief Code completion occurs within an Objective-C implementation or |
10155 | /// category implementation |
10156 | PCC_ObjCImplementation, |
10157 | /// \brief Code completion occurs within the list of instance variables |
10158 | /// in an Objective-C interface, protocol, category, or implementation. |
10159 | PCC_ObjCInstanceVariableList, |
10160 | /// \brief Code completion occurs following one or more template |
10161 | /// headers. |
10162 | PCC_Template, |
10163 | /// \brief Code completion occurs following one or more template |
10164 | /// headers within a class. |
10165 | PCC_MemberTemplate, |
10166 | /// \brief Code completion occurs within an expression. |
10167 | PCC_Expression, |
10168 | /// \brief Code completion occurs within a statement, which may |
10169 | /// also be an expression or a declaration. |
10170 | PCC_Statement, |
10171 | /// \brief Code completion occurs at the beginning of the |
10172 | /// initialization statement (or expression) in a for loop. |
10173 | PCC_ForInit, |
10174 | /// \brief Code completion occurs within the condition of an if, |
10175 | /// while, switch, or for statement. |
10176 | PCC_Condition, |
10177 | /// \brief Code completion occurs within the body of a function on a |
10178 | /// recovery path, where we do not have a specific handle on our position |
10179 | /// in the grammar. |
10180 | PCC_RecoveryInFunction, |
10181 | /// \brief Code completion occurs where only a type is permitted. |
10182 | PCC_Type, |
10183 | /// \brief Code completion occurs in a parenthesized expression, which |
10184 | /// might also be a type cast. |
10185 | PCC_ParenthesizedExpression, |
10186 | /// \brief Code completion occurs within a sequence of declaration |
10187 | /// specifiers within a function, method, or block. |
10188 | PCC_LocalDeclarationSpecifiers |
10189 | }; |
10190 | |
10191 | void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); |
10192 | void CodeCompleteOrdinaryName(Scope *S, |
10193 | ParserCompletionContext CompletionContext); |
10194 | void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, |
10195 | bool AllowNonIdentifiers, |
10196 | bool AllowNestedNameSpecifiers); |
10197 | |
10198 | struct CodeCompleteExpressionData; |
10199 | void CodeCompleteExpression(Scope *S, |
10200 | const CodeCompleteExpressionData &Data); |
10201 | void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, |
10202 | SourceLocation OpLoc, bool IsArrow, |
10203 | bool IsBaseExprStatement); |
10204 | void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); |
10205 | void CodeCompleteTag(Scope *S, unsigned TagSpec); |
10206 | void CodeCompleteTypeQualifiers(DeclSpec &DS); |
10207 | void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, |
10208 | const VirtSpecifiers *VS = nullptr); |
10209 | void CodeCompleteBracketDeclarator(Scope *S); |
10210 | void CodeCompleteCase(Scope *S); |
10211 | void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args); |
10212 | void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc, |
10213 | ArrayRef<Expr *> Args); |
10214 | void CodeCompleteInitializer(Scope *S, Decl *D); |
10215 | void CodeCompleteReturn(Scope *S); |
10216 | void CodeCompleteAfterIf(Scope *S); |
10217 | void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); |
10218 | |
10219 | void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, |
10220 | bool EnteringContext); |
10221 | void CodeCompleteUsing(Scope *S); |
10222 | void CodeCompleteUsingDirective(Scope *S); |
10223 | void CodeCompleteNamespaceDecl(Scope *S); |
10224 | void CodeCompleteNamespaceAliasDecl(Scope *S); |
10225 | void CodeCompleteOperatorName(Scope *S); |
10226 | void CodeCompleteConstructorInitializer( |
10227 | Decl *Constructor, |
10228 | ArrayRef<CXXCtorInitializer *> Initializers); |
10229 | |
10230 | void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, |
10231 | bool AfterAmpersand); |
10232 | |
10233 | void CodeCompleteObjCAtDirective(Scope *S); |
10234 | void CodeCompleteObjCAtVisibility(Scope *S); |
10235 | void CodeCompleteObjCAtStatement(Scope *S); |
10236 | void CodeCompleteObjCAtExpression(Scope *S); |
10237 | void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); |
10238 | void CodeCompleteObjCPropertyGetter(Scope *S); |
10239 | void CodeCompleteObjCPropertySetter(Scope *S); |
10240 | void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, |
10241 | bool IsParameter); |
10242 | void CodeCompleteObjCMessageReceiver(Scope *S); |
10243 | void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, |
10244 | ArrayRef<IdentifierInfo *> SelIdents, |
10245 | bool AtArgumentExpression); |
10246 | void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, |
10247 | ArrayRef<IdentifierInfo *> SelIdents, |
10248 | bool AtArgumentExpression, |
10249 | bool IsSuper = false); |
10250 | void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, |
10251 | ArrayRef<IdentifierInfo *> SelIdents, |
10252 | bool AtArgumentExpression, |
10253 | ObjCInterfaceDecl *Super = nullptr); |
10254 | void CodeCompleteObjCForCollection(Scope *S, |
10255 | DeclGroupPtrTy IterationVar); |
10256 | void CodeCompleteObjCSelector(Scope *S, |
10257 | ArrayRef<IdentifierInfo *> SelIdents); |
10258 | void CodeCompleteObjCProtocolReferences( |
10259 | ArrayRef<IdentifierLocPair> Protocols); |
10260 | void CodeCompleteObjCProtocolDecl(Scope *S); |
10261 | void CodeCompleteObjCInterfaceDecl(Scope *S); |
10262 | void CodeCompleteObjCSuperclass(Scope *S, |
10263 | IdentifierInfo *ClassName, |
10264 | SourceLocation ClassNameLoc); |
10265 | void CodeCompleteObjCImplementationDecl(Scope *S); |
10266 | void CodeCompleteObjCInterfaceCategory(Scope *S, |
10267 | IdentifierInfo *ClassName, |
10268 | SourceLocation ClassNameLoc); |
10269 | void CodeCompleteObjCImplementationCategory(Scope *S, |
10270 | IdentifierInfo *ClassName, |
10271 | SourceLocation ClassNameLoc); |
10272 | void CodeCompleteObjCPropertyDefinition(Scope *S); |
10273 | void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, |
10274 | IdentifierInfo *PropertyName); |
10275 | void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, |
10276 | ParsedType ReturnType); |
10277 | void CodeCompleteObjCMethodDeclSelector(Scope *S, |
10278 | bool IsInstanceMethod, |
10279 | bool AtParameterName, |
10280 | ParsedType ReturnType, |
10281 | ArrayRef<IdentifierInfo *> SelIdents); |
10282 | void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, |
10283 | SourceLocation ClassNameLoc, |
10284 | bool IsBaseExprStatement); |
10285 | void CodeCompletePreprocessorDirective(bool InConditional); |
10286 | void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); |
10287 | void CodeCompletePreprocessorMacroName(bool IsDefinition); |
10288 | void CodeCompletePreprocessorExpression(); |
10289 | void CodeCompletePreprocessorMacroArgument(Scope *S, |
10290 | IdentifierInfo *Macro, |
10291 | MacroInfo *MacroInfo, |
10292 | unsigned Argument); |
10293 | void CodeCompleteNaturalLanguage(); |
10294 | void CodeCompleteAvailabilityPlatformName(); |
10295 | void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, |
10296 | CodeCompletionTUInfo &CCTUInfo, |
10297 | SmallVectorImpl<CodeCompletionResult> &Results); |
10298 | //@} |
10299 | |
10300 | //===--------------------------------------------------------------------===// |
10301 | // Extra semantic analysis beyond the C type system |
10302 | |
10303 | public: |
10304 | SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, |
10305 | unsigned ByteNo) const; |
10306 | |
10307 | private: |
10308 | void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, |
10309 | const ArraySubscriptExpr *ASE=nullptr, |
10310 | bool AllowOnePastEnd=true, bool IndexNegated=false); |
10311 | void CheckArrayAccess(const Expr *E); |
10312 | // Used to grab the relevant information from a FormatAttr and a |
10313 | // FunctionDeclaration. |
10314 | struct FormatStringInfo { |
10315 | unsigned FormatIdx; |
10316 | unsigned FirstDataArg; |
10317 | bool HasVAListArg; |
10318 | }; |
10319 | |
10320 | static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, |
10321 | FormatStringInfo *FSI); |
10322 | bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, |
10323 | const FunctionProtoType *Proto); |
10324 | bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, |
10325 | ArrayRef<const Expr *> Args); |
10326 | bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, |
10327 | const FunctionProtoType *Proto); |
10328 | bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); |
10329 | void CheckConstructorCall(FunctionDecl *FDecl, |
10330 | ArrayRef<const Expr *> Args, |
10331 | const FunctionProtoType *Proto, |
10332 | SourceLocation Loc); |
10333 | |
10334 | void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, |
10335 | const Expr *ThisArg, ArrayRef<const Expr *> Args, |
10336 | bool IsMemberFunction, SourceLocation Loc, SourceRange Range, |
10337 | VariadicCallType CallType); |
10338 | |
10339 | bool CheckObjCString(Expr *Arg); |
10340 | ExprResult CheckOSLogFormatStringArg(Expr *Arg); |
10341 | |
10342 | ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, |
10343 | unsigned BuiltinID, CallExpr *TheCall); |
10344 | |
10345 | bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, |
10346 | unsigned MaxWidth); |
10347 | bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10348 | bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10349 | |
10350 | bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10351 | bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10352 | bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10353 | bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); |
10354 | bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); |
10355 | bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10356 | bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); |
10357 | |
10358 | bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); |
10359 | bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); |
10360 | bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); |
10361 | bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); |
10362 | bool SemaBuiltinVSX(CallExpr *TheCall); |
10363 | bool SemaBuiltinOSLogFormat(CallExpr *TheCall); |
10364 | |
10365 | public: |
10366 | // Used by C++ template instantiation. |
10367 | ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); |
10368 | ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, |
10369 | SourceLocation BuiltinLoc, |
10370 | SourceLocation RParenLoc); |
10371 | |
10372 | private: |
10373 | bool SemaBuiltinPrefetch(CallExpr *TheCall); |
10374 | bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); |
10375 | bool SemaBuiltinAssume(CallExpr *TheCall); |
10376 | bool SemaBuiltinAssumeAligned(CallExpr *TheCall); |
10377 | bool SemaBuiltinLongjmp(CallExpr *TheCall); |
10378 | bool SemaBuiltinSetjmp(CallExpr *TheCall); |
10379 | ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); |
10380 | ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); |
10381 | ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, |
10382 | AtomicExpr::AtomicOp Op); |
10383 | bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, |
10384 | llvm::APSInt &Result); |
10385 | bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, |
10386 | int Low, int High); |
10387 | bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, |
10388 | unsigned Multiple); |
10389 | bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, |
10390 | int ArgNum, unsigned ExpectedFieldNum, |
10391 | bool AllowName); |
10392 | public: |
10393 | enum FormatStringType { |
10394 | FST_Scanf, |
10395 | FST_Printf, |
10396 | FST_NSString, |
10397 | FST_Strftime, |
10398 | FST_Strfmon, |
10399 | FST_Kprintf, |
10400 | FST_FreeBSDKPrintf, |
10401 | FST_OSTrace, |
10402 | FST_OSLog, |
10403 | FST_Unknown |
10404 | }; |
10405 | static FormatStringType GetFormatStringType(const FormatAttr *Format); |
10406 | |
10407 | bool FormatStringHasSArg(const StringLiteral *FExpr); |
10408 | |
10409 | static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); |
10410 | |
10411 | private: |
10412 | bool CheckFormatArguments(const FormatAttr *Format, |
10413 | ArrayRef<const Expr *> Args, |
10414 | bool IsCXXMember, |
10415 | VariadicCallType CallType, |
10416 | SourceLocation Loc, SourceRange Range, |
10417 | llvm::SmallBitVector &CheckedVarArgs); |
10418 | bool CheckFormatArguments(ArrayRef<const Expr *> Args, |
10419 | bool HasVAListArg, unsigned format_idx, |
10420 | unsigned firstDataArg, FormatStringType Type, |
10421 | VariadicCallType CallType, |
10422 | SourceLocation Loc, SourceRange range, |
10423 | llvm::SmallBitVector &CheckedVarArgs); |
10424 | |
10425 | void CheckAbsoluteValueFunction(const CallExpr *Call, |
10426 | const FunctionDecl *FDecl); |
10427 | |
10428 | void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); |
10429 | |
10430 | void CheckMemaccessArguments(const CallExpr *Call, |
10431 | unsigned BId, |
10432 | IdentifierInfo *FnName); |
10433 | |
10434 | void CheckStrlcpycatArguments(const CallExpr *Call, |
10435 | IdentifierInfo *FnName); |
10436 | |
10437 | void CheckStrncatArguments(const CallExpr *Call, |
10438 | IdentifierInfo *FnName); |
10439 | |
10440 | void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, |
10441 | SourceLocation ReturnLoc, |
10442 | bool isObjCMethod = false, |
10443 | const AttrVec *Attrs = nullptr, |
10444 | const FunctionDecl *FD = nullptr); |
10445 | |
10446 | public: |
10447 | void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); |
10448 | |
10449 | private: |
10450 | void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); |
10451 | void CheckBoolLikeConversion(Expr *E, SourceLocation CC); |
10452 | void CheckForIntOverflow(Expr *E); |
10453 | void CheckUnsequencedOperations(Expr *E); |
10454 | |
10455 | /// \brief Perform semantic checks on a completed expression. This will either |
10456 | /// be a full-expression or a default argument expression. |
10457 | void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), |
10458 | bool IsConstexpr = false); |
10459 | |
10460 | void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, |
10461 | Expr *Init); |
10462 | |
10463 | /// Check if there is a field shadowing. |
10464 | void CheckShadowInheritedFields(const SourceLocation &Loc, |
10465 | DeclarationName FieldName, |
10466 | const CXXRecordDecl *RD); |
10467 | |
10468 | /// \brief Check if the given expression contains 'break' or 'continue' |
10469 | /// statement that produces control flow different from GCC. |
10470 | void CheckBreakContinueBinding(Expr *E); |
10471 | |
10472 | /// \brief Check whether receiver is mutable ObjC container which |
10473 | /// attempts to add itself into the container |
10474 | void CheckObjCCircularContainer(ObjCMessageExpr *Message); |
10475 | |
10476 | void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); |
10477 | void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, |
10478 | bool DeleteWasArrayForm); |
10479 | public: |
10480 | /// \brief Register a magic integral constant to be used as a type tag. |
10481 | void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, |
10482 | uint64_t MagicValue, QualType Type, |
10483 | bool LayoutCompatible, bool MustBeNull); |
10484 | |
10485 | struct TypeTagData { |
10486 | TypeTagData() {} |
10487 | |
10488 | TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : |
10489 | Type(Type), LayoutCompatible(LayoutCompatible), |
10490 | MustBeNull(MustBeNull) |
10491 | {} |
10492 | |
10493 | QualType Type; |
10494 | |
10495 | /// If true, \c Type should be compared with other expression's types for |
10496 | /// layout-compatibility. |
10497 | unsigned LayoutCompatible : 1; |
10498 | unsigned MustBeNull : 1; |
10499 | }; |
10500 | |
10501 | /// A pair of ArgumentKind identifier and magic value. This uniquely |
10502 | /// identifies the magic value. |
10503 | typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; |
10504 | |
10505 | private: |
10506 | /// \brief A map from magic value to type information. |
10507 | std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> |
10508 | TypeTagForDatatypeMagicValues; |
10509 | |
10510 | /// \brief Peform checks on a call of a function with argument_with_type_tag |
10511 | /// or pointer_with_type_tag attributes. |
10512 | void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, |
10513 | const ArrayRef<const Expr *> ExprArgs, |
10514 | SourceLocation CallSiteLoc); |
10515 | |
10516 | /// \brief Check if we are taking the address of a packed field |
10517 | /// as this may be a problem if the pointer value is dereferenced. |
10518 | void CheckAddressOfPackedMember(Expr *rhs); |
10519 | |
10520 | /// \brief The parser's current scope. |
10521 | /// |
10522 | /// The parser maintains this state here. |
10523 | Scope *CurScope; |
10524 | |
10525 | mutable IdentifierInfo *Ident_super; |
10526 | mutable IdentifierInfo *Ident___float128; |
10527 | |
10528 | /// Nullability type specifiers. |
10529 | IdentifierInfo *Ident__Nonnull = nullptr; |
10530 | IdentifierInfo *Ident__Nullable = nullptr; |
10531 | IdentifierInfo *Ident__Null_unspecified = nullptr; |
10532 | |
10533 | IdentifierInfo *Ident_NSError = nullptr; |
10534 | |
10535 | /// \brief The handler for the FileChanged preprocessor events. |
10536 | /// |
10537 | /// Used for diagnostics that implement custom semantic analysis for #include |
10538 | /// directives, like -Wpragma-pack. |
10539 | sema::SemaPPCallbacks *SemaPPCallbackHandler; |
10540 | |
10541 | protected: |
10542 | friend class Parser; |
10543 | friend class InitializationSequence; |
10544 | friend class ASTReader; |
10545 | friend class ASTDeclReader; |
10546 | friend class ASTWriter; |
10547 | |
10548 | public: |
10549 | /// Retrieve the keyword associated |
10550 | IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); |
10551 | |
10552 | /// The struct behind the CFErrorRef pointer. |
10553 | RecordDecl *CFError = nullptr; |
10554 | |
10555 | /// Retrieve the identifier "NSError". |
10556 | IdentifierInfo *getNSErrorIdent(); |
10557 | |
10558 | /// \brief Retrieve the parser's current scope. |
10559 | /// |
10560 | /// This routine must only be used when it is certain that semantic analysis |
10561 | /// and the parser are in precisely the same context, which is not the case |
10562 | /// when, e.g., we are performing any kind of template instantiation. |
10563 | /// Therefore, the only safe places to use this scope are in the parser |
10564 | /// itself and in routines directly invoked from the parser and *never* from |
10565 | /// template substitution or instantiation. |
10566 | Scope *getCurScope() const { return CurScope; } |
10567 | |
10568 | void incrementMSManglingNumber() const { |
10569 | return CurScope->incrementMSManglingNumber(); |
10570 | } |
10571 | |
10572 | IdentifierInfo *getSuperIdentifier() const; |
10573 | IdentifierInfo *getFloat128Identifier() const; |
10574 | |
10575 | Decl *getObjCDeclContext() const; |
10576 | |
10577 | DeclContext *getCurLexicalContext() const { |
10578 | return OriginalLexicalContext ? OriginalLexicalContext : CurContext; |
10579 | } |
10580 | |
10581 | const DeclContext *getCurObjCLexicalContext() const { |
10582 | const DeclContext *DC = getCurLexicalContext(); |
10583 | // A category implicitly has the attribute of the interface. |
10584 | if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) |
10585 | DC = CatD->getClassInterface(); |
10586 | return DC; |
10587 | } |
10588 | |
10589 | /// \brief To be used for checking whether the arguments being passed to |
10590 | /// function exceeds the number of parameters expected for it. |
10591 | static bool TooManyArguments(size_t NumParams, size_t NumArgs, |
10592 | bool PartialOverloading = false) { |
10593 | // We check whether we're just after a comma in code-completion. |
10594 | if (NumArgs > 0 && PartialOverloading) |
10595 | return NumArgs + 1 > NumParams; // If so, we view as an extra argument. |
10596 | return NumArgs > NumParams; |
10597 | } |
10598 | |
10599 | // Emitting members of dllexported classes is delayed until the class |
10600 | // (including field initializers) is fully parsed. |
10601 | SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; |
10602 | |
10603 | private: |
10604 | class SavePendingParsedClassStateRAII { |
10605 | public: |
10606 | SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } |
10607 | |
10608 | ~SavePendingParsedClassStateRAII() { |
10609 | assert(S.DelayedExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedExceptionSpecChecks.empty () && "there shouldn't be any pending delayed exception spec checks" ) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 10610, __extension__ __PRETTY_FUNCTION__)) |
10610 | "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedExceptionSpecChecks.empty () && "there shouldn't be any pending delayed exception spec checks" ) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 10610, __extension__ __PRETTY_FUNCTION__)); |
10611 | assert(S.DelayedDefaultedMemberExceptionSpecs.empty() &&(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs .empty() && "there shouldn't be any pending delayed defaulted member " "exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 10613, __extension__ __PRETTY_FUNCTION__)) |
10612 | "there shouldn't be any pending delayed defaulted member "(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs .empty() && "there shouldn't be any pending delayed defaulted member " "exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 10613, __extension__ __PRETTY_FUNCTION__)) |
10613 | "exception specs")(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs .empty() && "there shouldn't be any pending delayed defaulted member " "exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 10613, __extension__ __PRETTY_FUNCTION__)); |
10614 | assert(S.DelayedDllExportClasses.empty() &&(static_cast <bool> (S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes") ? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 10615, __extension__ __PRETTY_FUNCTION__)) |
10615 | "there shouldn't be any pending delayed DLL export classes")(static_cast <bool> (S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes") ? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h" , 10615, __extension__ __PRETTY_FUNCTION__)); |
10616 | swapSavedState(); |
10617 | } |
10618 | |
10619 | private: |
10620 | Sema &S; |
10621 | decltype(DelayedExceptionSpecChecks) SavedExceptionSpecChecks; |
10622 | decltype(DelayedDefaultedMemberExceptionSpecs) |
10623 | SavedDefaultedMemberExceptionSpecs; |
10624 | decltype(DelayedDllExportClasses) SavedDllExportClasses; |
10625 | |
10626 | void swapSavedState() { |
10627 | SavedExceptionSpecChecks.swap(S.DelayedExceptionSpecChecks); |
10628 | SavedDefaultedMemberExceptionSpecs.swap( |
10629 | S.DelayedDefaultedMemberExceptionSpecs); |
10630 | SavedDllExportClasses.swap(S.DelayedDllExportClasses); |
10631 | } |
10632 | }; |
10633 | |
10634 | /// \brief Helper class that collects misaligned member designations and |
10635 | /// their location info for delayed diagnostics. |
10636 | struct MisalignedMember { |
10637 | Expr *E; |
10638 | RecordDecl *RD; |
10639 | ValueDecl *MD; |
10640 | CharUnits Alignment; |
10641 | |
10642 | MisalignedMember() : E(), RD(), MD(), Alignment() {} |
10643 | MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, |
10644 | CharUnits Alignment) |
10645 | : E(E), RD(RD), MD(MD), Alignment(Alignment) {} |
10646 | explicit MisalignedMember(Expr *E) |
10647 | : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} |
10648 | |
10649 | bool operator==(const MisalignedMember &m) { return this->E == m.E; } |
10650 | }; |
10651 | /// \brief Small set of gathered accesses to potentially misaligned members |
10652 | /// due to the packed attribute. |
10653 | SmallVector<MisalignedMember, 4> MisalignedMembers; |
10654 | |
10655 | /// \brief Adds an expression to the set of gathered misaligned members. |
10656 | void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, |
10657 | CharUnits Alignment); |
10658 | |
10659 | public: |
10660 | /// \brief Diagnoses the current set of gathered accesses. This typically |
10661 | /// happens at full expression level. The set is cleared after emitting the |
10662 | /// diagnostics. |
10663 | void DiagnoseMisalignedMembers(); |
10664 | |
10665 | /// \brief This function checks if the expression is in the sef of potentially |
10666 | /// misaligned members and it is converted to some pointer type T with lower |
10667 | /// or equal alignment requirements. If so it removes it. This is used when |
10668 | /// we do not want to diagnose such misaligned access (e.g. in conversions to |
10669 | /// void*). |
10670 | void DiscardMisalignedMemberAddress(const Type *T, Expr *E); |
10671 | |
10672 | /// \brief This function calls Action when it determines that E designates a |
10673 | /// misaligned member due to the packed attribute. This is used to emit |
10674 | /// local diagnostics like in reference binding. |
10675 | void RefersToMemberWithReducedAlignment( |
10676 | Expr *E, |
10677 | llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> |
10678 | Action); |
10679 | }; |
10680 | |
10681 | /// \brief RAII object that enters a new expression evaluation context. |
10682 | class EnterExpressionEvaluationContext { |
10683 | Sema &Actions; |
10684 | bool Entered = true; |
10685 | |
10686 | public: |
10687 | |
10688 | EnterExpressionEvaluationContext(Sema &Actions, |
10689 | Sema::ExpressionEvaluationContext NewContext, |
10690 | Decl *LambdaContextDecl = nullptr, |
10691 | bool IsDecltype = false, |
10692 | bool ShouldEnter = true) |
10693 | : Actions(Actions), Entered(ShouldEnter) { |
10694 | if (Entered) |
10695 | Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, |
10696 | IsDecltype); |
10697 | } |
10698 | EnterExpressionEvaluationContext(Sema &Actions, |
10699 | Sema::ExpressionEvaluationContext NewContext, |
10700 | Sema::ReuseLambdaContextDecl_t, |
10701 | bool IsDecltype = false) |
10702 | : Actions(Actions) { |
10703 | Actions.PushExpressionEvaluationContext(NewContext, |
10704 | Sema::ReuseLambdaContextDecl, |
10705 | IsDecltype); |
10706 | } |
10707 | |
10708 | enum InitListTag { InitList }; |
10709 | EnterExpressionEvaluationContext(Sema &Actions, InitListTag, |
10710 | bool ShouldEnter = true) |
10711 | : Actions(Actions), Entered(false) { |
10712 | // In C++11 onwards, narrowing checks are performed on the contents of |
10713 | // braced-init-lists, even when they occur within unevaluated operands. |
10714 | // Therefore we still need to instantiate constexpr functions used in such |
10715 | // a context. |
10716 | if (ShouldEnter && Actions.isUnevaluatedContext() && |
10717 | Actions.getLangOpts().CPlusPlus11) { |
10718 | Actions.PushExpressionEvaluationContext( |
10719 | Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false); |
10720 | Entered = true; |
10721 | } |
10722 | } |
10723 | |
10724 | ~EnterExpressionEvaluationContext() { |
10725 | if (Entered) |
10726 | Actions.PopExpressionEvaluationContext(); |
10727 | } |
10728 | }; |
10729 | |
10730 | DeductionFailureInfo |
10731 | MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, |
10732 | sema::TemplateDeductionInfo &Info); |
10733 | |
10734 | /// \brief Contains a late templated function. |
10735 | /// Will be parsed at the end of the translation unit, used by Sema & Parser. |
10736 | struct LateParsedTemplate { |
10737 | CachedTokens Toks; |
10738 | /// \brief The template function declaration to be late parsed. |
10739 | Decl *D; |
10740 | }; |
10741 | |
10742 | } // end namespace clang |
10743 | |
10744 | namespace llvm { |
10745 | // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its |
10746 | // SourceLocation. |
10747 | template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { |
10748 | using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; |
10749 | using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; |
10750 | |
10751 | static FunctionDeclAndLoc getEmptyKey() { |
10752 | return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; |
10753 | } |
10754 | |
10755 | static FunctionDeclAndLoc getTombstoneKey() { |
10756 | return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; |
10757 | } |
10758 | |
10759 | static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { |
10760 | return hash_combine(FDBaseInfo::getHashValue(FDL.FD), |
10761 | FDL.Loc.getRawEncoding()); |
10762 | } |
10763 | |
10764 | static bool isEqual(const FunctionDeclAndLoc &LHS, |
10765 | const FunctionDeclAndLoc &RHS) { |
10766 | return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; |
10767 | } |
10768 | }; |
10769 | } // namespace llvm |
10770 | |
10771 | #endif |
1 | //===- PartialDiagnostic.h - Diagnostic "closures" --------------*- C++ -*-===// |
2 | // |
3 | // The LLVM Compiler Infrastructure |
4 | // |
5 | // This file is distributed under the University of Illinois Open Source |
6 | // License. See LICENSE.TXT for details. |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | // |
10 | /// \file |
11 | /// \brief Implements a partial diagnostic that can be emitted anwyhere |
12 | /// in a DiagnosticBuilder stream. |
13 | // |
14 | //===----------------------------------------------------------------------===// |
15 | |
16 | #ifndef LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H |
17 | #define LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H |
18 | |
19 | #include "clang/Basic/Diagnostic.h" |
20 | #include "clang/Basic/LLVM.h" |
21 | #include "clang/Basic/SourceLocation.h" |
22 | #include "llvm/ADT/SmallVector.h" |
23 | #include "llvm/ADT/StringRef.h" |
24 | #include <cassert> |
25 | #include <cstdint> |
26 | #include <string> |
27 | #include <type_traits> |
28 | #include <utility> |
29 | |
30 | namespace clang { |
31 | |
32 | class DeclContext; |
33 | class IdentifierInfo; |
34 | |
35 | class PartialDiagnostic { |
36 | public: |
37 | enum { |
38 | // The MaxArguments and MaxFixItHints member enum values from |
39 | // DiagnosticsEngine are private but DiagnosticsEngine declares |
40 | // PartialDiagnostic a friend. These enum values are redeclared |
41 | // here so that the nested Storage class below can access them. |
42 | MaxArguments = DiagnosticsEngine::MaxArguments |
43 | }; |
44 | |
45 | struct Storage { |
46 | enum { |
47 | /// \brief The maximum number of arguments we can hold. We |
48 | /// currently only support up to 10 arguments (%0-%9). |
49 | /// |
50 | /// A single diagnostic with more than that almost certainly has to |
51 | /// be simplified anyway. |
52 | MaxArguments = PartialDiagnostic::MaxArguments |
53 | }; |
54 | |
55 | /// \brief The number of entries in Arguments. |
56 | unsigned char NumDiagArgs = 0; |
57 | |
58 | /// \brief Specifies for each argument whether it is in DiagArgumentsStr |
59 | /// or in DiagArguments. |
60 | unsigned char DiagArgumentsKind[MaxArguments]; |
61 | |
62 | /// \brief The values for the various substitution positions. |
63 | /// |
64 | /// This is used when the argument is not an std::string. The specific value |
65 | /// is mangled into an intptr_t and the interpretation depends on exactly |
66 | /// what sort of argument kind it is. |
67 | intptr_t DiagArgumentsVal[MaxArguments]; |
68 | |
69 | /// \brief The values for the various substitution positions that have |
70 | /// string arguments. |
71 | std::string DiagArgumentsStr[MaxArguments]; |
72 | |
73 | /// \brief The list of ranges added to this diagnostic. |
74 | SmallVector<CharSourceRange, 8> DiagRanges; |
75 | |
76 | /// \brief If valid, provides a hint with some code to insert, remove, or |
77 | /// modify at a particular position. |
78 | SmallVector<FixItHint, 6> FixItHints; |
79 | |
80 | Storage() = default; |
81 | }; |
82 | |
83 | /// \brief An allocator for Storage objects, which uses a small cache to |
84 | /// objects, used to reduce malloc()/free() traffic for partial diagnostics. |
85 | class StorageAllocator { |
86 | static const unsigned NumCached = 16; |
87 | Storage Cached[NumCached]; |
88 | Storage *FreeList[NumCached]; |
89 | unsigned NumFreeListEntries; |
90 | |
91 | public: |
92 | StorageAllocator(); |
93 | ~StorageAllocator(); |
94 | |
95 | /// \brief Allocate new storage. |
96 | Storage *Allocate() { |
97 | if (NumFreeListEntries == 0) |
98 | return new Storage; |
99 | |
100 | Storage *Result = FreeList[--NumFreeListEntries]; |
101 | Result->NumDiagArgs = 0; |
102 | Result->DiagRanges.clear(); |
103 | Result->FixItHints.clear(); |
104 | return Result; |
105 | } |
106 | |
107 | /// \brief Free the given storage object. |
108 | void Deallocate(Storage *S) { |
109 | if (S >= Cached && S <= Cached + NumCached) { |
110 | FreeList[NumFreeListEntries++] = S; |
111 | return; |
112 | } |
113 | |
114 | delete S; |
115 | } |
116 | }; |
117 | |
118 | private: |
119 | // NOTE: Sema assumes that PartialDiagnostic is location-invariant |
120 | // in the sense that its bits can be safely memcpy'ed and destructed |
121 | // in the new location. |
122 | |
123 | /// \brief The diagnostic ID. |
124 | mutable unsigned DiagID = 0; |
125 | |
126 | /// \brief Storage for args and ranges. |
127 | mutable Storage *DiagStorage = nullptr; |
128 | |
129 | /// \brief Allocator used to allocate storage for this diagnostic. |
130 | StorageAllocator *Allocator = nullptr; |
131 | |
132 | /// \brief Retrieve storage for this particular diagnostic. |
133 | Storage *getStorage() const { |
134 | if (DiagStorage) |
135 | return DiagStorage; |
136 | |
137 | if (Allocator) |
138 | DiagStorage = Allocator->Allocate(); |
139 | else { |
140 | assert(Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))(static_cast <bool> (Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) ? void (0) : __assert_fail ("Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 140, __extension__ __PRETTY_FUNCTION__)); |
141 | DiagStorage = new Storage; |
142 | } |
143 | return DiagStorage; |
144 | } |
145 | |
146 | void freeStorage() { |
147 | if (!DiagStorage) |
148 | return; |
149 | |
150 | // The hot path for PartialDiagnostic is when we just used it to wrap an ID |
151 | // (typically so we have the flexibility of passing a more complex |
152 | // diagnostic into the callee, but that does not commonly occur). |
153 | // |
154 | // Split this out into a slow function for silly compilers (*cough*) which |
155 | // can't do decent partial inlining. |
156 | freeStorageSlow(); |
157 | } |
158 | |
159 | void freeStorageSlow() { |
160 | if (Allocator) |
161 | Allocator->Deallocate(DiagStorage); |
162 | else if (Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) |
163 | delete DiagStorage; |
164 | DiagStorage = nullptr; |
165 | } |
166 | |
167 | void AddSourceRange(const CharSourceRange &R) const { |
168 | if (!DiagStorage) |
169 | DiagStorage = getStorage(); |
170 | |
171 | DiagStorage->DiagRanges.push_back(R); |
172 | } |
173 | |
174 | void AddFixItHint(const FixItHint &Hint) const { |
175 | if (Hint.isNull()) |
176 | return; |
177 | |
178 | if (!DiagStorage) |
179 | DiagStorage = getStorage(); |
180 | |
181 | DiagStorage->FixItHints.push_back(Hint); |
182 | } |
183 | |
184 | public: |
185 | struct NullDiagnostic {}; |
186 | |
187 | /// \brief Create a null partial diagnostic, which cannot carry a payload, |
188 | /// and only exists to be swapped with a real partial diagnostic. |
189 | PartialDiagnostic(NullDiagnostic) {} |
190 | |
191 | PartialDiagnostic(unsigned DiagID, StorageAllocator &Allocator) |
192 | : DiagID(DiagID), Allocator(&Allocator) {} |
193 | |
194 | PartialDiagnostic(const PartialDiagnostic &Other) |
195 | : DiagID(Other.DiagID), Allocator(Other.Allocator) { |
196 | if (Other.DiagStorage) { |
197 | DiagStorage = getStorage(); |
198 | *DiagStorage = *Other.DiagStorage; |
199 | } |
200 | } |
201 | |
202 | PartialDiagnostic(PartialDiagnostic &&Other) |
203 | : DiagID(Other.DiagID), DiagStorage(Other.DiagStorage), |
204 | Allocator(Other.Allocator) { |
205 | Other.DiagStorage = nullptr; |
206 | } |
207 | |
208 | PartialDiagnostic(const PartialDiagnostic &Other, Storage *DiagStorage) |
209 | : DiagID(Other.DiagID), DiagStorage(DiagStorage), |
210 | Allocator(reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) { |
211 | if (Other.DiagStorage) |
212 | *this->DiagStorage = *Other.DiagStorage; |
213 | } |
214 | |
215 | PartialDiagnostic(const Diagnostic &Other, StorageAllocator &Allocator) |
216 | : DiagID(Other.getID()), Allocator(&Allocator) { |
217 | // Copy arguments. |
218 | for (unsigned I = 0, N = Other.getNumArgs(); I != N; ++I) { |
219 | if (Other.getArgKind(I) == DiagnosticsEngine::ak_std_string) |
220 | AddString(Other.getArgStdStr(I)); |
221 | else |
222 | AddTaggedVal(Other.getRawArg(I), Other.getArgKind(I)); |
223 | } |
224 | |
225 | // Copy source ranges. |
226 | for (unsigned I = 0, N = Other.getNumRanges(); I != N; ++I) |
227 | AddSourceRange(Other.getRange(I)); |
228 | |
229 | // Copy fix-its. |
230 | for (unsigned I = 0, N = Other.getNumFixItHints(); I != N; ++I) |
231 | AddFixItHint(Other.getFixItHint(I)); |
232 | } |
233 | |
234 | PartialDiagnostic &operator=(const PartialDiagnostic &Other) { |
235 | DiagID = Other.DiagID; |
236 | if (Other.DiagStorage) { |
237 | if (!DiagStorage) |
238 | DiagStorage = getStorage(); |
239 | |
240 | *DiagStorage = *Other.DiagStorage; |
241 | } else { |
242 | freeStorage(); |
243 | } |
244 | |
245 | return *this; |
246 | } |
247 | |
248 | PartialDiagnostic &operator=(PartialDiagnostic &&Other) { |
249 | freeStorage(); |
250 | |
251 | DiagID = Other.DiagID; |
252 | DiagStorage = Other.DiagStorage; |
253 | Allocator = Other.Allocator; |
254 | |
255 | Other.DiagStorage = nullptr; |
256 | return *this; |
257 | } |
258 | |
259 | ~PartialDiagnostic() { |
260 | freeStorage(); |
261 | } |
262 | |
263 | void swap(PartialDiagnostic &PD) { |
264 | std::swap(DiagID, PD.DiagID); |
265 | std::swap(DiagStorage, PD.DiagStorage); |
266 | std::swap(Allocator, PD.Allocator); |
267 | } |
268 | |
269 | unsigned getDiagID() const { return DiagID; } |
270 | |
271 | void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const { |
272 | if (!DiagStorage) |
273 | DiagStorage = getStorage(); |
274 | |
275 | assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage ::MaxArguments && "Too many arguments to diagnostic!" ) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 276, __extension__ __PRETTY_FUNCTION__)) |
276 | "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage ::MaxArguments && "Too many arguments to diagnostic!" ) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 276, __extension__ __PRETTY_FUNCTION__)); |
277 | DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind; |
278 | DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V; |
279 | } |
280 | |
281 | void AddString(StringRef V) const { |
282 | if (!DiagStorage) |
283 | DiagStorage = getStorage(); |
284 | |
285 | assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage ::MaxArguments && "Too many arguments to diagnostic!" ) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 286, __extension__ __PRETTY_FUNCTION__)) |
286 | "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage ::MaxArguments && "Too many arguments to diagnostic!" ) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 286, __extension__ __PRETTY_FUNCTION__)); |
287 | DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] |
288 | = DiagnosticsEngine::ak_std_string; |
289 | DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = V; |
290 | } |
291 | |
292 | void Emit(const DiagnosticBuilder &DB) const { |
293 | if (!DiagStorage) |
294 | return; |
295 | |
296 | // Add all arguments. |
297 | for (unsigned i = 0, e = DiagStorage->NumDiagArgs; i != e; ++i) { |
298 | if ((DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i] |
299 | == DiagnosticsEngine::ak_std_string) |
300 | DB.AddString(DiagStorage->DiagArgumentsStr[i]); |
301 | else |
302 | DB.AddTaggedVal(DiagStorage->DiagArgumentsVal[i], |
303 | (DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]); |
304 | } |
305 | |
306 | // Add all ranges. |
307 | for (const CharSourceRange &Range : DiagStorage->DiagRanges) |
308 | DB.AddSourceRange(Range); |
309 | |
310 | // Add all fix-its. |
311 | for (const FixItHint &Fix : DiagStorage->FixItHints) |
312 | DB.AddFixItHint(Fix); |
313 | } |
314 | |
315 | void EmitToString(DiagnosticsEngine &Diags, |
316 | SmallVectorImpl<char> &Buf) const { |
317 | // FIXME: It should be possible to render a diagnostic to a string without |
318 | // messing with the state of the diagnostics engine. |
319 | DiagnosticBuilder DB(Diags.Report(getDiagID())); |
320 | Emit(DB); |
321 | DB.FlushCounts(); |
322 | Diagnostic(&Diags).FormatDiagnostic(Buf); |
323 | DB.Clear(); |
324 | Diags.Clear(); |
325 | } |
326 | |
327 | /// \brief Clear out this partial diagnostic, giving it a new diagnostic ID |
328 | /// and removing all of its arguments, ranges, and fix-it hints. |
329 | void Reset(unsigned DiagID = 0) { |
330 | this->DiagID = DiagID; |
331 | freeStorage(); |
332 | } |
333 | |
334 | bool hasStorage() const { return DiagStorage != nullptr; } |
335 | |
336 | /// Retrieve the string argument at the given index. |
337 | StringRef getStringArg(unsigned I) { |
338 | assert(DiagStorage && "No diagnostic storage?")(static_cast <bool> (DiagStorage && "No diagnostic storage?" ) ? void (0) : __assert_fail ("DiagStorage && \"No diagnostic storage?\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 338, __extension__ __PRETTY_FUNCTION__)); |
339 | assert(I < DiagStorage->NumDiagArgs && "Not enough diagnostic args")(static_cast <bool> (I < DiagStorage->NumDiagArgs && "Not enough diagnostic args") ? void (0) : __assert_fail ("I < DiagStorage->NumDiagArgs && \"Not enough diagnostic args\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 339, __extension__ __PRETTY_FUNCTION__)); |
340 | assert(DiagStorage->DiagArgumentsKind[I](static_cast <bool> (DiagStorage->DiagArgumentsKind[ I] == DiagnosticsEngine::ak_std_string && "Not a string arg" ) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 341, __extension__ __PRETTY_FUNCTION__)) |
341 | == DiagnosticsEngine::ak_std_string && "Not a string arg")(static_cast <bool> (DiagStorage->DiagArgumentsKind[ I] == DiagnosticsEngine::ak_std_string && "Not a string arg" ) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\"" , "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h" , 341, __extension__ __PRETTY_FUNCTION__)); |
342 | return DiagStorage->DiagArgumentsStr[I]; |
343 | } |
344 | |
345 | friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
346 | unsigned I) { |
347 | PD.AddTaggedVal(I, DiagnosticsEngine::ak_uint); |
348 | return PD; |
349 | } |
350 | |
351 | friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
352 | int I) { |
353 | PD.AddTaggedVal(I, DiagnosticsEngine::ak_sint); |
354 | return PD; |
355 | } |
356 | |
357 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
358 | const char *S) { |
359 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(S), |
360 | DiagnosticsEngine::ak_c_string); |
361 | return PD; |
362 | } |
363 | |
364 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
365 | StringRef S) { |
366 | |
367 | PD.AddString(S); |
368 | return PD; |
369 | } |
370 | |
371 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
372 | const IdentifierInfo *II) { |
373 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(II), |
374 | DiagnosticsEngine::ak_identifierinfo); |
375 | return PD; |
376 | } |
377 | |
378 | // Adds a DeclContext to the diagnostic. The enable_if template magic is here |
379 | // so that we only match those arguments that are (statically) DeclContexts; |
380 | // other arguments that derive from DeclContext (e.g., RecordDecls) will not |
381 | // match. |
382 | template<typename T> |
383 | friend inline |
384 | typename std::enable_if<std::is_same<T, DeclContext>::value, |
385 | const PartialDiagnostic &>::type |
386 | operator<<(const PartialDiagnostic &PD, T *DC) { |
387 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(DC), |
388 | DiagnosticsEngine::ak_declcontext); |
389 | return PD; |
390 | } |
391 | |
392 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
393 | SourceRange R) { |
394 | PD.AddSourceRange(CharSourceRange::getTokenRange(R)); |
395 | return PD; |
396 | } |
397 | |
398 | friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
399 | const CharSourceRange &R) { |
400 | PD.AddSourceRange(R); |
401 | return PD; |
402 | } |
403 | |
404 | friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
405 | const FixItHint &Hint) { |
406 | PD.AddFixItHint(Hint); |
407 | return PD; |
408 | } |
409 | }; |
410 | |
411 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
412 | const PartialDiagnostic &PD) { |
413 | PD.Emit(DB); |
414 | return DB; |
415 | } |
416 | |
417 | /// \brief A partial diagnostic along with the source location where this |
418 | /// diagnostic occurs. |
419 | using PartialDiagnosticAt = std::pair<SourceLocation, PartialDiagnostic>; |
420 | |
421 | } // namespace clang |
422 | |
423 | #endif // LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H |