Bug Summary

File:tools/clang/lib/Sema/SemaExprCXX.cpp
Warning:line 706, column 7
Potential leak of memory pointed to by field 'DiagStorage'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExprCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp

1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
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 semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
14
15#include "clang/Sema/SemaInternal.h"
16#include "TreeTransform.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/CharUnits.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/RecursiveASTVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/AlignedAllocation.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
37#include "clang/Sema/SemaLambda.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "llvm/ADT/APInt.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/Support/ErrorHandling.h"
42using namespace clang;
43using namespace sema;
44
45/// \brief Handle the result of the special case name lookup for inheriting
46/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name")(static_cast <bool> (NNS->getAsIdentifier() == &
Name && "not a constructor name") ? void (0) : __assert_fail
("NNS->getAsIdentifier() == &Name && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 65, __extension__ __PRETTY_FUNCTION__))
;
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
71 case NestedNameSpecifier::Super:
72 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor")::llvm::llvm_unreachable_internal("Nested name specifier is not a type for inheriting ctor"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 74)
;
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
83ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
84 IdentifierInfo &II,
85 SourceLocation NameLoc,
86 Scope *S, CXXScopeSpec &SS,
87 ParsedType ObjectTypePtr,
88 bool EnteringContext) {
89 // Determine where to perform name lookup.
90
91 // FIXME: This area of the standard is very messy, and the current
92 // wording is rather unclear about which scopes we search for the
93 // destructor name; see core issues 399 and 555. Issue 399 in
94 // particular shows where the current description of destructor name
95 // lookup is completely out of line with existing practice, e.g.,
96 // this appears to be ill-formed:
97 //
98 // namespace N {
99 // template <typename T> struct S {
100 // ~S();
101 // };
102 // }
103 //
104 // void f(N::S<int>* s) {
105 // s->N::S<int>::~S();
106 // }
107 //
108 // See also PR6358 and PR6359.
109 // For this reason, we're currently only doing the C++03 version of this
110 // code; the C++0x version has to wait until we get a proper spec.
111 QualType SearchType;
112 DeclContext *LookupCtx = nullptr;
113 bool isDependent = false;
114 bool LookInScope = false;
115
116 if (SS.isInvalid())
117 return nullptr;
118
119 // If we have an object type, it's because we are in a
120 // pseudo-destructor-expression or a member access expression, and
121 // we know what type we're looking for.
122 if (ObjectTypePtr)
123 SearchType = GetTypeFromParser(ObjectTypePtr);
124
125 if (SS.isSet()) {
126 NestedNameSpecifier *NNS = SS.getScopeRep();
127
128 bool AlreadySearched = false;
129 bool LookAtPrefix = true;
130 // C++11 [basic.lookup.qual]p6:
131 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
132 // the type-names are looked up as types in the scope designated by the
133 // nested-name-specifier. Similarly, in a qualified-id of the form:
134 //
135 // nested-name-specifier[opt] class-name :: ~ class-name
136 //
137 // the second class-name is looked up in the same scope as the first.
138 //
139 // Here, we determine whether the code below is permitted to look at the
140 // prefix of the nested-name-specifier.
141 DeclContext *DC = computeDeclContext(SS, EnteringContext);
142 if (DC && DC->isFileContext()) {
143 AlreadySearched = true;
144 LookupCtx = DC;
145 isDependent = false;
146 } else if (DC && isa<CXXRecordDecl>(DC)) {
147 LookAtPrefix = false;
148 LookInScope = true;
149 }
150
151 // The second case from the C++03 rules quoted further above.
152 NestedNameSpecifier *Prefix = nullptr;
153 if (AlreadySearched) {
154 // Nothing left to do.
155 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
156 CXXScopeSpec PrefixSS;
157 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
158 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
159 isDependent = isDependentScopeSpecifier(PrefixSS);
160 } else if (ObjectTypePtr) {
161 LookupCtx = computeDeclContext(SearchType);
162 isDependent = SearchType->isDependentType();
163 } else {
164 LookupCtx = computeDeclContext(SS, EnteringContext);
165 isDependent = LookupCtx && LookupCtx->isDependentContext();
166 }
167 } else if (ObjectTypePtr) {
168 // C++ [basic.lookup.classref]p3:
169 // If the unqualified-id is ~type-name, the type-name is looked up
170 // in the context of the entire postfix-expression. If the type T
171 // of the object expression is of a class type C, the type-name is
172 // also looked up in the scope of class C. At least one of the
173 // lookups shall find a name that refers to (possibly
174 // cv-qualified) T.
175 LookupCtx = computeDeclContext(SearchType);
176 isDependent = SearchType->isDependentType();
177 assert((isDependent || !SearchType->isIncompleteType()) &&(static_cast <bool> ((isDependent || !SearchType->isIncompleteType
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 178, __extension__ __PRETTY_FUNCTION__))
178 "Caller should have completed object type")(static_cast <bool> ((isDependent || !SearchType->isIncompleteType
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 178, __extension__ __PRETTY_FUNCTION__))
;
179
180 LookInScope = true;
181 } else {
182 // Perform lookup into the current scope (only).
183 LookInScope = true;
184 }
185
186 TypeDecl *NonMatchingTypeDecl = nullptr;
187 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
188 for (unsigned Step = 0; Step != 2; ++Step) {
189 // Look for the name first in the computed lookup context (if we
190 // have one) and, if that fails to find a match, in the scope (if
191 // we're allowed to look there).
192 Found.clear();
193 if (Step == 0 && LookupCtx) {
194 if (RequireCompleteDeclContext(SS, LookupCtx))
195 return nullptr;
196 LookupQualifiedName(Found, LookupCtx);
197 } else if (Step == 1 && LookInScope && S) {
198 LookupName(Found, S);
199 } else {
200 continue;
201 }
202
203 // FIXME: Should we be suppressing ambiguities here?
204 if (Found.isAmbiguous())
205 return nullptr;
206
207 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
208 QualType T = Context.getTypeDeclType(Type);
209 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
210
211 if (SearchType.isNull() || SearchType->isDependentType() ||
212 Context.hasSameUnqualifiedType(T, SearchType)) {
213 // We found our type!
214
215 return CreateParsedType(T,
216 Context.getTrivialTypeSourceInfo(T, NameLoc));
217 }
218
219 if (!SearchType.isNull())
220 NonMatchingTypeDecl = Type;
221 }
222
223 // If the name that we found is a class template name, and it is
224 // the same name as the template name in the last part of the
225 // nested-name-specifier (if present) or the object type, then
226 // this is the destructor for that class.
227 // FIXME: This is a workaround until we get real drafting for core
228 // issue 399, for which there isn't even an obvious direction.
229 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
230 QualType MemberOfType;
231 if (SS.isSet()) {
232 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
233 // Figure out the type of the context, if it has one.
234 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
235 MemberOfType = Context.getTypeDeclType(Record);
236 }
237 }
238 if (MemberOfType.isNull())
239 MemberOfType = SearchType;
240
241 if (MemberOfType.isNull())
242 continue;
243
244 // We're referring into a class template specialization. If the
245 // class template we found is the same as the template being
246 // specialized, we found what we are looking for.
247 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
248 if (ClassTemplateSpecializationDecl *Spec
249 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
250 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
251 Template->getCanonicalDecl())
252 return CreateParsedType(
253 MemberOfType,
254 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
255 }
256
257 continue;
258 }
259
260 // We're referring to an unresolved class template
261 // specialization. Determine whether we class template we found
262 // is the same as the template being specialized or, if we don't
263 // know which template is being specialized, that it at least
264 // has the same name.
265 if (const TemplateSpecializationType *SpecType
266 = MemberOfType->getAs<TemplateSpecializationType>()) {
267 TemplateName SpecName = SpecType->getTemplateName();
268
269 // The class template we found is the same template being
270 // specialized.
271 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
272 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
273 return CreateParsedType(
274 MemberOfType,
275 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
276
277 continue;
278 }
279
280 // The class template we found has the same name as the
281 // (dependent) template name being specialized.
282 if (DependentTemplateName *DepTemplate
283 = SpecName.getAsDependentTemplateName()) {
284 if (DepTemplate->isIdentifier() &&
285 DepTemplate->getIdentifier() == Template->getIdentifier())
286 return CreateParsedType(
287 MemberOfType,
288 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
289
290 continue;
291 }
292 }
293 }
294 }
295
296 if (isDependent) {
297 // We didn't find our type, but that's okay: it's dependent
298 // anyway.
299
300 // FIXME: What if we have no nested-name-specifier?
301 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
302 SS.getWithLocInContext(Context),
303 II, NameLoc);
304 return ParsedType::make(T);
305 }
306
307 if (NonMatchingTypeDecl) {
308 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
309 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
310 << T << SearchType;
311 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
312 << T;
313 } else if (ObjectTypePtr)
314 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
315 << &II;
316 else {
317 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
318 diag::err_destructor_class_name);
319 if (S) {
320 const DeclContext *Ctx = S->getEntity();
321 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
322 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
323 Class->getNameAsString());
324 }
325 }
326
327 return nullptr;
328}
329
330ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
331 ParsedType ObjectType) {
332 if (DS.getTypeSpecType() == DeclSpec::TST_error)
333 return nullptr;
334
335 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
336 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
337 return nullptr;
338 }
339
340 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_decltype && "unexpected type in getDestructorType"
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 341, __extension__ __PRETTY_FUNCTION__))
341 "unexpected type in getDestructorType")(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_decltype && "unexpected type in getDestructorType"
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 341, __extension__ __PRETTY_FUNCTION__))
;
342 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
343
344 // If we know the type of the object, check that the correct destructor
345 // type was named now; we can give better diagnostics this way.
346 QualType SearchType = GetTypeFromParser(ObjectType);
347 if (!SearchType.isNull() && !SearchType->isDependentType() &&
348 !Context.hasSameUnqualifiedType(T, SearchType)) {
349 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
350 << T << SearchType;
351 return nullptr;
352 }
353
354 return ParsedType::make(T);
355}
356
357bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
358 const UnqualifiedId &Name) {
359 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)(static_cast <bool> (Name.getKind() == UnqualifiedIdKind
::IK_LiteralOperatorId) ? void (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 359, __extension__ __PRETTY_FUNCTION__))
;
360
361 if (!SS.isValid())
362 return false;
363
364 switch (SS.getScopeRep()->getKind()) {
365 case NestedNameSpecifier::Identifier:
366 case NestedNameSpecifier::TypeSpec:
367 case NestedNameSpecifier::TypeSpecWithTemplate:
368 // Per C++11 [over.literal]p2, literal operators can only be declared at
369 // namespace scope. Therefore, this unqualified-id cannot name anything.
370 // Reject it early, because we have no AST representation for this in the
371 // case where the scope is dependent.
372 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
373 << SS.getScopeRep();
374 return true;
375
376 case NestedNameSpecifier::Global:
377 case NestedNameSpecifier::Super:
378 case NestedNameSpecifier::Namespace:
379 case NestedNameSpecifier::NamespaceAlias:
380 return false;
381 }
382
383 llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 383)
;
384}
385
386/// \brief Build a C++ typeid expression with a type operand.
387ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
388 SourceLocation TypeidLoc,
389 TypeSourceInfo *Operand,
390 SourceLocation RParenLoc) {
391 // C++ [expr.typeid]p4:
392 // The top-level cv-qualifiers of the lvalue expression or the type-id
393 // that is the operand of typeid are always ignored.
394 // If the type of the type-id is a class type or a reference to a class
395 // type, the class shall be completely-defined.
396 Qualifiers Quals;
397 QualType T
398 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
399 Quals);
400 if (T->getAs<RecordType>() &&
401 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
402 return ExprError();
403
404 if (T->isVariablyModifiedType())
405 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
406
407 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
408 SourceRange(TypeidLoc, RParenLoc));
409}
410
411/// \brief Build a C++ typeid expression with an expression operand.
412ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
413 SourceLocation TypeidLoc,
414 Expr *E,
415 SourceLocation RParenLoc) {
416 bool WasEvaluated = false;
417 if (E && !E->isTypeDependent()) {
418 if (E->getType()->isPlaceholderType()) {
419 ExprResult result = CheckPlaceholderExpr(E);
420 if (result.isInvalid()) return ExprError();
421 E = result.get();
422 }
423
424 QualType T = E->getType();
425 if (const RecordType *RecordT = T->getAs<RecordType>()) {
426 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
427 // C++ [expr.typeid]p3:
428 // [...] If the type of the expression is a class type, the class
429 // shall be completely-defined.
430 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
431 return ExprError();
432
433 // C++ [expr.typeid]p3:
434 // When typeid is applied to an expression other than an glvalue of a
435 // polymorphic class type [...] [the] expression is an unevaluated
436 // operand. [...]
437 if (RecordD->isPolymorphic() && E->isGLValue()) {
438 // The subexpression is potentially evaluated; switch the context
439 // and recheck the subexpression.
440 ExprResult Result = TransformToPotentiallyEvaluated(E);
441 if (Result.isInvalid()) return ExprError();
442 E = Result.get();
443
444 // We require a vtable to query the type at run time.
445 MarkVTableUsed(TypeidLoc, RecordD);
446 WasEvaluated = true;
447 }
448 }
449
450 // C++ [expr.typeid]p4:
451 // [...] If the type of the type-id is a reference to a possibly
452 // cv-qualified type, the result of the typeid expression refers to a
453 // std::type_info object representing the cv-unqualified referenced
454 // type.
455 Qualifiers Quals;
456 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
457 if (!Context.hasSameType(T, UnqualT)) {
458 T = UnqualT;
459 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
460 }
461 }
462
463 if (E->getType()->isVariablyModifiedType())
464 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
465 << E->getType());
466 else if (!inTemplateInstantiation() &&
467 E->HasSideEffects(Context, WasEvaluated)) {
468 // The expression operand for typeid is in an unevaluated expression
469 // context, so side effects could result in unintended consequences.
470 Diag(E->getExprLoc(), WasEvaluated
471 ? diag::warn_side_effects_typeid
472 : diag::warn_side_effects_unevaluated_context);
473 }
474
475 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
476 SourceRange(TypeidLoc, RParenLoc));
477}
478
479/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
480ExprResult
481Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
482 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
483 // Find the std::type_info type.
484 if (!getStdNamespace())
485 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
486
487 if (!CXXTypeInfoDecl) {
488 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
489 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
490 LookupQualifiedName(R, getStdNamespace());
491 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
492 // Microsoft's typeinfo doesn't have type_info in std but in the global
493 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
494 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
495 LookupQualifiedName(R, Context.getTranslationUnitDecl());
496 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
497 }
498 if (!CXXTypeInfoDecl)
499 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
500 }
501
502 if (!getLangOpts().RTTI) {
503 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
504 }
505
506 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
507
508 if (isType) {
509 // The operand is a type; handle it as such.
510 TypeSourceInfo *TInfo = nullptr;
511 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
512 &TInfo);
513 if (T.isNull())
514 return ExprError();
515
516 if (!TInfo)
517 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
518
519 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
520 }
521
522 // The operand is an expression.
523 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
524}
525
526/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
527/// a single GUID.
528static void
529getUuidAttrOfType(Sema &SemaRef, QualType QT,
530 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
531 // Optionally remove one level of pointer, reference or array indirection.
532 const Type *Ty = QT.getTypePtr();
533 if (QT->isPointerType() || QT->isReferenceType())
534 Ty = QT->getPointeeType().getTypePtr();
535 else if (QT->isArrayType())
536 Ty = Ty->getBaseElementTypeUnsafe();
537
538 const auto *TD = Ty->getAsTagDecl();
539 if (!TD)
540 return;
541
542 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
543 UuidAttrs.insert(Uuid);
544 return;
545 }
546
547 // __uuidof can grab UUIDs from template arguments.
548 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
549 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
550 for (const TemplateArgument &TA : TAL.asArray()) {
551 const UuidAttr *UuidForTA = nullptr;
552 if (TA.getKind() == TemplateArgument::Type)
553 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
554 else if (TA.getKind() == TemplateArgument::Declaration)
555 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
556
557 if (UuidForTA)
558 UuidAttrs.insert(UuidForTA);
559 }
560 }
561}
562
563/// \brief Build a Microsoft __uuidof expression with a type operand.
564ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
565 SourceLocation TypeidLoc,
566 TypeSourceInfo *Operand,
567 SourceLocation RParenLoc) {
568 StringRef UuidStr;
569 if (!Operand->getType()->isDependentType()) {
570 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
571 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
572 if (UuidAttrs.empty())
573 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
574 if (UuidAttrs.size() > 1)
575 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
576 UuidStr = UuidAttrs.back()->getGuid();
577 }
578
579 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
580 SourceRange(TypeidLoc, RParenLoc));
581}
582
583/// \brief Build a Microsoft __uuidof expression with an expression operand.
584ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
585 SourceLocation TypeidLoc,
586 Expr *E,
587 SourceLocation RParenLoc) {
588 StringRef UuidStr;
589 if (!E->getType()->isDependentType()) {
590 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
591 UuidStr = "00000000-0000-0000-0000-000000000000";
592 } else {
593 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
594 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
595 if (UuidAttrs.empty())
596 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
597 if (UuidAttrs.size() > 1)
598 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
599 UuidStr = UuidAttrs.back()->getGuid();
600 }
601 }
602
603 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
604 SourceRange(TypeidLoc, RParenLoc));
605}
606
607/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
608ExprResult
609Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
610 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
611 // If MSVCGuidDecl has not been cached, do the lookup.
612 if (!MSVCGuidDecl) {
613 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
614 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
615 LookupQualifiedName(R, Context.getTranslationUnitDecl());
616 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
617 if (!MSVCGuidDecl)
618 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
619 }
620
621 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
622
623 if (isType) {
624 // The operand is a type; handle it as such.
625 TypeSourceInfo *TInfo = nullptr;
626 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
627 &TInfo);
628 if (T.isNull())
629 return ExprError();
630
631 if (!TInfo)
632 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
633
634 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
635 }
636
637 // The operand is an expression.
638 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
639}
640
641/// ActOnCXXBoolLiteral - Parse {true,false} literals.
642ExprResult
643Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
644 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(static_cast <bool> ((Kind == tok::kw_true || Kind == tok
::kw_false) && "Unknown C++ Boolean value!") ? void (
0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 645, __extension__ __PRETTY_FUNCTION__))
645 "Unknown C++ Boolean value!")(static_cast <bool> ((Kind == tok::kw_true || Kind == tok
::kw_false) && "Unknown C++ Boolean value!") ? void (
0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 645, __extension__ __PRETTY_FUNCTION__))
;
646 return new (Context)
647 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
648}
649
650/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
651ExprResult
652Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
653 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
654}
655
656/// ActOnCXXThrow - Parse throw expressions.
657ExprResult
658Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
659 bool IsThrownVarInScope = false;
660 if (Ex) {
1
Assuming 'Ex' is null
2
Taking false branch
661 // C++0x [class.copymove]p31:
662 // When certain criteria are met, an implementation is allowed to omit the
663 // copy/move construction of a class object [...]
664 //
665 // - in a throw-expression, when the operand is the name of a
666 // non-volatile automatic object (other than a function or catch-
667 // clause parameter) whose scope does not extend beyond the end of the
668 // innermost enclosing try-block (if there is one), the copy/move
669 // operation from the operand to the exception object (15.1) can be
670 // omitted by constructing the automatic object directly into the
671 // exception object
672 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
673 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
674 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
675 for( ; S; S = S->getParent()) {
676 if (S->isDeclScope(Var)) {
677 IsThrownVarInScope = true;
678 break;
679 }
680
681 if (S->getFlags() &
682 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
683 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
684 Scope::TryScope))
685 break;
686 }
687 }
688 }
689 }
690
691 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
3
Calling 'Sema::BuildCXXThrow'
692}
693
694ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
695 bool IsThrownVarInScope) {
696 // Don't report an error if 'throw' is used in system headers.
697 if (!getLangOpts().CXXExceptions &&
4
Assuming the condition is false
698 !getSourceManager().isInSystemHeader(OpLoc))
699 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
700
701 // Exceptions aren't allowed in CUDA device code.
702 if (getLangOpts().CUDA)
5
Assuming the condition is true
6
Taking true branch
703 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
7
Calling 'operator<<'
24
Returned allocated memory
704 << "throw" << CurrentCUDATarget();
705
706 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
25
Potential leak of memory pointed to by field 'DiagStorage'
707 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
708
709 if (Ex && !Ex->isTypeDependent()) {
710 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
711 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
712 return ExprError();
713
714 // Initialize the exception result. This implicitly weeds out
715 // abstract types or types with inaccessible copy constructors.
716
717 // C++0x [class.copymove]p31:
718 // When certain criteria are met, an implementation is allowed to omit the
719 // copy/move construction of a class object [...]
720 //
721 // - in a throw-expression, when the operand is the name of a
722 // non-volatile automatic object (other than a function or
723 // catch-clause
724 // parameter) whose scope does not extend beyond the end of the
725 // innermost enclosing try-block (if there is one), the copy/move
726 // operation from the operand to the exception object (15.1) can be
727 // omitted by constructing the automatic object directly into the
728 // exception object
729 const VarDecl *NRVOVariable = nullptr;
730 if (IsThrownVarInScope)
731 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
732
733 InitializedEntity Entity = InitializedEntity::InitializeException(
734 OpLoc, ExceptionObjectTy,
735 /*NRVO=*/NRVOVariable != nullptr);
736 ExprResult Res = PerformMoveOrCopyInitialization(
737 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
738 if (Res.isInvalid())
739 return ExprError();
740 Ex = Res.get();
741 }
742
743 return new (Context)
744 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
745}
746
747static void
748collectPublicBases(CXXRecordDecl *RD,
749 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
750 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
751 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
752 bool ParentIsPublic) {
753 for (const CXXBaseSpecifier &BS : RD->bases()) {
754 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
755 bool NewSubobject;
756 // Virtual bases constitute the same subobject. Non-virtual bases are
757 // always distinct subobjects.
758 if (BS.isVirtual())
759 NewSubobject = VBases.insert(BaseDecl).second;
760 else
761 NewSubobject = true;
762
763 if (NewSubobject)
764 ++SubobjectsSeen[BaseDecl];
765
766 // Only add subobjects which have public access throughout the entire chain.
767 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
768 if (PublicPath)
769 PublicSubobjectsSeen.insert(BaseDecl);
770
771 // Recurse on to each base subobject.
772 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
773 PublicPath);
774 }
775}
776
777static void getUnambiguousPublicSubobjects(
778 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
779 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
780 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
781 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
782 SubobjectsSeen[RD] = 1;
783 PublicSubobjectsSeen.insert(RD);
784 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
785 /*ParentIsPublic=*/true);
786
787 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
788 // Skip ambiguous objects.
789 if (SubobjectsSeen[PublicSubobject] > 1)
790 continue;
791
792 Objects.push_back(PublicSubobject);
793 }
794}
795
796/// CheckCXXThrowOperand - Validate the operand of a throw.
797bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
798 QualType ExceptionObjectTy, Expr *E) {
799 // If the type of the exception would be an incomplete type or a pointer
800 // to an incomplete type other than (cv) void the program is ill-formed.
801 QualType Ty = ExceptionObjectTy;
802 bool isPointer = false;
803 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
804 Ty = Ptr->getPointeeType();
805 isPointer = true;
806 }
807 if (!isPointer || !Ty->isVoidType()) {
808 if (RequireCompleteType(ThrowLoc, Ty,
809 isPointer ? diag::err_throw_incomplete_ptr
810 : diag::err_throw_incomplete,
811 E->getSourceRange()))
812 return true;
813
814 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
815 diag::err_throw_abstract_type, E))
816 return true;
817 }
818
819 // If the exception has class type, we need additional handling.
820 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
821 if (!RD)
822 return false;
823
824 // If we are throwing a polymorphic class type or pointer thereof,
825 // exception handling will make use of the vtable.
826 MarkVTableUsed(ThrowLoc, RD);
827
828 // If a pointer is thrown, the referenced object will not be destroyed.
829 if (isPointer)
830 return false;
831
832 // If the class has a destructor, we must be able to call it.
833 if (!RD->hasIrrelevantDestructor()) {
834 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
835 MarkFunctionReferenced(E->getExprLoc(), Destructor);
836 CheckDestructorAccess(E->getExprLoc(), Destructor,
837 PDiag(diag::err_access_dtor_exception) << Ty);
838 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
839 return true;
840 }
841 }
842
843 // The MSVC ABI creates a list of all types which can catch the exception
844 // object. This list also references the appropriate copy constructor to call
845 // if the object is caught by value and has a non-trivial copy constructor.
846 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
847 // We are only interested in the public, unambiguous bases contained within
848 // the exception object. Bases which are ambiguous or otherwise
849 // inaccessible are not catchable types.
850 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
851 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
852
853 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
854 // Attempt to lookup the copy constructor. Various pieces of machinery
855 // will spring into action, like template instantiation, which means this
856 // cannot be a simple walk of the class's decls. Instead, we must perform
857 // lookup and overload resolution.
858 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
859 if (!CD)
860 continue;
861
862 // Mark the constructor referenced as it is used by this throw expression.
863 MarkFunctionReferenced(E->getExprLoc(), CD);
864
865 // Skip this copy constructor if it is trivial, we don't need to record it
866 // in the catchable type data.
867 if (CD->isTrivial())
868 continue;
869
870 // The copy constructor is non-trivial, create a mapping from this class
871 // type to this constructor.
872 // N.B. The selection of copy constructor is not sensitive to this
873 // particular throw-site. Lookup will be performed at the catch-site to
874 // ensure that the copy constructor is, in fact, accessible (via
875 // friendship or any other means).
876 Context.addCopyConstructorForExceptionObject(Subobject, CD);
877
878 // We don't keep the instantiated default argument expressions around so
879 // we must rebuild them here.
880 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
881 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
882 return true;
883 }
884 }
885 }
886
887 return false;
888}
889
890static QualType adjustCVQualifiersForCXXThisWithinLambda(
891 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
892 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
893
894 QualType ClassType = ThisTy->getPointeeType();
895 LambdaScopeInfo *CurLSI = nullptr;
896 DeclContext *CurDC = CurSemaContext;
897
898 // Iterate through the stack of lambdas starting from the innermost lambda to
899 // the outermost lambda, checking if '*this' is ever captured by copy - since
900 // that could change the cv-qualifiers of the '*this' object.
901 // The object referred to by '*this' starts out with the cv-qualifiers of its
902 // member function. We then start with the innermost lambda and iterate
903 // outward checking to see if any lambda performs a by-copy capture of '*this'
904 // - and if so, any nested lambda must respect the 'constness' of that
905 // capturing lamdbda's call operator.
906 //
907
908 // Since the FunctionScopeInfo stack is representative of the lexical
909 // nesting of the lambda expressions during initial parsing (and is the best
910 // place for querying information about captures about lambdas that are
911 // partially processed) and perhaps during instantiation of function templates
912 // that contain lambda expressions that need to be transformed BUT not
913 // necessarily during instantiation of a nested generic lambda's function call
914 // operator (which might even be instantiated at the end of the TU) - at which
915 // time the DeclContext tree is mature enough to query capture information
916 // reliably - we use a two pronged approach to walk through all the lexically
917 // enclosing lambda expressions:
918 //
919 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
920 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
921 // enclosed by the call-operator of the LSI below it on the stack (while
922 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
923 // the stack represents the innermost lambda.
924 //
925 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
926 // represents a lambda's call operator. If it does, we must be instantiating
927 // a generic lambda's call operator (represented by the Current LSI, and
928 // should be the only scenario where an inconsistency between the LSI and the
929 // DeclContext should occur), so climb out the DeclContexts if they
930 // represent lambdas, while querying the corresponding closure types
931 // regarding capture information.
932
933 // 1) Climb down the function scope info stack.
934 for (int I = FunctionScopes.size();
935 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
936 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
937 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
938 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
939 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
940
941 if (!CurLSI->isCXXThisCaptured())
942 continue;
943
944 auto C = CurLSI->getCXXThisCapture();
945
946 if (C.isCopyCapture()) {
947 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
948 if (CurLSI->CallOperator->isConst())
949 ClassType.addConst();
950 return ASTCtx.getPointerType(ClassType);
951 }
952 }
953
954 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
955 // happen during instantiation of its nested generic lambda call operator)
956 if (isLambdaCallOperator(CurDC)) {
957 assert(CurLSI && "While computing 'this' capture-type for a generic "(static_cast <bool> (CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? void
(0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 958, __extension__ __PRETTY_FUNCTION__))
958 "lambda, we must have a corresponding LambdaScopeInfo")(static_cast <bool> (CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? void
(0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 958, __extension__ __PRETTY_FUNCTION__))
;
959 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
960 "While computing 'this' capture-type for a generic lambda, when we "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
961 "run out of enclosing LSI's, yet the enclosing DC is a "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
962 "lambda-call-operator we must be (i.e. Current LSI) in a generic "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
963 "lambda call oeprator")(static_cast <bool> (isGenericLambdaCallOperatorSpecialization
(CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
;
964 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))(static_cast <bool> (CurDC == getLambdaAwareParentOfDeclContext
(CurLSI->CallOperator)) ? void (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 964, __extension__ __PRETTY_FUNCTION__))
;
965
966 auto IsThisCaptured =
967 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
968 IsConst = false;
969 IsByCopy = false;
970 for (auto &&C : Closure->captures()) {
971 if (C.capturesThis()) {
972 if (C.getCaptureKind() == LCK_StarThis)
973 IsByCopy = true;
974 if (Closure->getLambdaCallOperator()->isConst())
975 IsConst = true;
976 return true;
977 }
978 }
979 return false;
980 };
981
982 bool IsByCopyCapture = false;
983 bool IsConstCapture = false;
984 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
985 while (Closure &&
986 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
987 if (IsByCopyCapture) {
988 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
989 if (IsConstCapture)
990 ClassType.addConst();
991 return ASTCtx.getPointerType(ClassType);
992 }
993 Closure = isLambdaCallOperator(Closure->getParent())
994 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
995 : nullptr;
996 }
997 }
998 return ASTCtx.getPointerType(ClassType);
999}
1000
1001QualType Sema::getCurrentThisType() {
1002 DeclContext *DC = getFunctionLevelDeclContext();
1003 QualType ThisTy = CXXThisTypeOverride;
1004
1005 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1006 if (method && method->isInstance())
1007 ThisTy = method->getThisType(Context);
1008 }
1009
1010 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1011 inTemplateInstantiation()) {
1012
1013 assert(isa<CXXRecordDecl>(DC) &&(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"Trying to get 'this' type from static method?") ? void (0) :
__assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1014, __extension__ __PRETTY_FUNCTION__))
1014 "Trying to get 'this' type from static method?")(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"Trying to get 'this' type from static method?") ? void (0) :
__assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1014, __extension__ __PRETTY_FUNCTION__))
;
1015
1016 // This is a lambda call operator that is being instantiated as a default
1017 // initializer. DC must point to the enclosing class type, so we can recover
1018 // the 'this' type from it.
1019
1020 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1021 // There are no cv-qualifiers for 'this' within default initializers,
1022 // per [expr.prim.general]p4.
1023 ThisTy = Context.getPointerType(ClassTy);
1024 }
1025
1026 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1027 // might need to be adjusted if the lambda or any of its enclosing lambda's
1028 // captures '*this' by copy.
1029 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1030 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1031 CurContext, Context);
1032 return ThisTy;
1033}
1034
1035Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1036 Decl *ContextDecl,
1037 unsigned CXXThisTypeQuals,
1038 bool Enabled)
1039 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1040{
1041 if (!Enabled || !ContextDecl)
1042 return;
1043
1044 CXXRecordDecl *Record = nullptr;
1045 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1046 Record = Template->getTemplatedDecl();
1047 else
1048 Record = cast<CXXRecordDecl>(ContextDecl);
1049
1050 // We care only for CVR qualifiers here, so cut everything else.
1051 CXXThisTypeQuals &= Qualifiers::FastMask;
1052 S.CXXThisTypeOverride
1053 = S.Context.getPointerType(
1054 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1055
1056 this->Enabled = true;
1057}
1058
1059
1060Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1061 if (Enabled) {
1062 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1063 }
1064}
1065
1066static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1067 QualType ThisTy, SourceLocation Loc,
1068 const bool ByCopy) {
1069
1070 QualType AdjustedThisTy = ThisTy;
1071 // The type of the corresponding data member (not a 'this' pointer if 'by
1072 // copy').
1073 QualType CaptureThisFieldTy = ThisTy;
1074 if (ByCopy) {
1075 // If we are capturing the object referred to by '*this' by copy, ignore any
1076 // cv qualifiers inherited from the type of the member function for the type
1077 // of the closure-type's corresponding data member and any use of 'this'.
1078 CaptureThisFieldTy = ThisTy->getPointeeType();
1079 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1080 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1081 }
1082
1083 FieldDecl *Field = FieldDecl::Create(
1084 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1085 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1086 ICIS_NoInit);
1087
1088 Field->setImplicit(true);
1089 Field->setAccess(AS_private);
1090 RD->addDecl(Field);
1091 Expr *This =
1092 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1093 if (ByCopy) {
1094 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1095 UO_Deref,
1096 This).get();
1097 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1098 nullptr, CaptureThisFieldTy, Loc);
1099 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1100 InitializationSequence Init(S, Entity, InitKind, StarThis);
1101 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1102 if (ER.isInvalid()) return nullptr;
1103 return ER.get();
1104 }
1105 return This;
1106}
1107
1108bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1109 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1110 const bool ByCopy) {
1111 // We don't need to capture this in an unevaluated context.
1112 if (isUnevaluatedContext() && !Explicit)
1113 return true;
1114
1115 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(static_cast <bool> ((!ByCopy || Explicit) && "cannot implicitly capture *this by value"
) ? void (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1115, __extension__ __PRETTY_FUNCTION__))
;
1116
1117 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
1118 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
1119
1120 // Check that we can capture the *enclosing object* (referred to by '*this')
1121 // by the capturing-entity/closure (lambda/block/etc) at
1122 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1123
1124 // Note: The *enclosing object* can only be captured by-value by a
1125 // closure that is a lambda, using the explicit notation:
1126 // [*this] { ... }.
1127 // Every other capture of the *enclosing object* results in its by-reference
1128 // capture.
1129
1130 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1131 // stack), we can capture the *enclosing object* only if:
1132 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1133 // - or, 'L' has an implicit capture.
1134 // AND
1135 // -- there is no enclosing closure
1136 // -- or, there is some enclosing closure 'E' that has already captured the
1137 // *enclosing object*, and every intervening closure (if any) between 'E'
1138 // and 'L' can implicitly capture the *enclosing object*.
1139 // -- or, every enclosing closure can implicitly capture the
1140 // *enclosing object*
1141
1142
1143 unsigned NumCapturingClosures = 0;
1144 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
1145 if (CapturingScopeInfo *CSI =
1146 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1147 if (CSI->CXXThisCaptureIndex != 0) {
1148 // 'this' is already being captured; there isn't anything more to do.
1149 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1150 break;
1151 }
1152 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1153 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1154 // This context can't implicitly capture 'this'; fail out.
1155 if (BuildAndDiagnose)
1156 Diag(Loc, diag::err_this_capture)
1157 << (Explicit && idx == MaxFunctionScopesIndex);
1158 return true;
1159 }
1160 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1161 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1162 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1163 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1164 (Explicit && idx == MaxFunctionScopesIndex)) {
1165 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1166 // iteration through can be an explicit capture, all enclosing closures,
1167 // if any, must perform implicit captures.
1168
1169 // This closure can capture 'this'; continue looking upwards.
1170 NumCapturingClosures++;
1171 continue;
1172 }
1173 // This context can't implicitly capture 'this'; fail out.
1174 if (BuildAndDiagnose)
1175 Diag(Loc, diag::err_this_capture)
1176 << (Explicit && idx == MaxFunctionScopesIndex);
1177 return true;
1178 }
1179 break;
1180 }
1181 if (!BuildAndDiagnose) return false;
1182
1183 // If we got here, then the closure at MaxFunctionScopesIndex on the
1184 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1185 // (including implicit by-reference captures in any enclosing closures).
1186
1187 // In the loop below, respect the ByCopy flag only for the closure requesting
1188 // the capture (i.e. first iteration through the loop below). Ignore it for
1189 // all enclosing closure's up to NumCapturingClosures (since they must be
1190 // implicitly capturing the *enclosing object* by reference (see loop
1191 // above)).
1192 assert((!ByCopy ||(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1195, __extension__ __PRETTY_FUNCTION__))
1193 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1195, __extension__ __PRETTY_FUNCTION__))
1194 "Only a lambda can capture the enclosing object (referred to by "(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1195, __extension__ __PRETTY_FUNCTION__))
1195 "*this) by copy")(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1195, __extension__ __PRETTY_FUNCTION__))
;
1196 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1197 // contexts.
1198 QualType ThisTy = getCurrentThisType();
1199 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
1200 --idx, --NumCapturingClosures) {
1201 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1202 Expr *ThisExpr = nullptr;
1203
1204 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1205 // For lambda expressions, build a field and an initializing expression,
1206 // and capture the *enclosing object* by copy only if this is the first
1207 // iteration.
1208 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1209 ByCopy && idx == MaxFunctionScopesIndex);
1210
1211 } else if (CapturedRegionScopeInfo *RSI
1212 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1213 ThisExpr =
1214 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1215 false/*ByCopy*/);
1216
1217 bool isNested = NumCapturingClosures > 1;
1218 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1219 }
1220 return false;
1221}
1222
1223ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1224 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1225 /// is a non-lvalue expression whose value is the address of the object for
1226 /// which the function is called.
1227
1228 QualType ThisTy = getCurrentThisType();
1229 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1230
1231 CheckCXXThisCapture(Loc);
1232 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1233}
1234
1235bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1236 // If we're outside the body of a member function, then we'll have a specified
1237 // type for 'this'.
1238 if (CXXThisTypeOverride.isNull())
1239 return false;
1240
1241 // Determine whether we're looking into a class that's currently being
1242 // defined.
1243 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1244 return Class && Class->isBeingDefined();
1245}
1246
1247/// Parse construction of a specified type.
1248/// Can be interpreted either as function-style casting ("int(x)")
1249/// or class type construction ("ClassType(x,y,z)")
1250/// or creation of a value-initialized type ("int()").
1251ExprResult
1252Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1253 SourceLocation LParenOrBraceLoc,
1254 MultiExprArg exprs,
1255 SourceLocation RParenOrBraceLoc,
1256 bool ListInitialization) {
1257 if (!TypeRep)
1258 return ExprError();
1259
1260 TypeSourceInfo *TInfo;
1261 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1262 if (!TInfo)
1263 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1264
1265 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1266 RParenOrBraceLoc, ListInitialization);
1267 // Avoid creating a non-type-dependent expression that contains typos.
1268 // Non-type-dependent expressions are liable to be discarded without
1269 // checking for embedded typos.
1270 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1271 !Result.get()->isTypeDependent())
1272 Result = CorrectDelayedTyposInExpr(Result.get());
1273 return Result;
1274}
1275
1276ExprResult
1277Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1278 SourceLocation LParenOrBraceLoc,
1279 MultiExprArg Exprs,
1280 SourceLocation RParenOrBraceLoc,
1281 bool ListInitialization) {
1282 QualType Ty = TInfo->getType();
1283 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1284
1285 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1286 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1287 // directly. We work around this by dropping the locations of the braces.
1288 SourceRange Locs = ListInitialization
1289 ? SourceRange()
1290 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1291 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1292 Exprs, Locs.getEnd());
1293 }
1294
1295 assert((!ListInitialization ||(static_cast <bool> ((!ListInitialization || (Exprs.size
() == 1 && isa<InitListExpr>(Exprs[0]))) &&
"List initialization must have initializer list as expression."
) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
1296 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&(static_cast <bool> ((!ListInitialization || (Exprs.size
() == 1 && isa<InitListExpr>(Exprs[0]))) &&
"List initialization must have initializer list as expression."
) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
1297 "List initialization must have initializer list as expression.")(static_cast <bool> ((!ListInitialization || (Exprs.size
() == 1 && isa<InitListExpr>(Exprs[0]))) &&
"List initialization must have initializer list as expression."
) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
;
1298 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1299
1300 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1301 InitializationKind Kind =
1302 Exprs.size()
1303 ? ListInitialization
1304 ? InitializationKind::CreateDirectList(
1305 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1306 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1307 RParenOrBraceLoc)
1308 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1309 RParenOrBraceLoc);
1310
1311 // C++1z [expr.type.conv]p1:
1312 // If the type is a placeholder for a deduced class type, [...perform class
1313 // template argument deduction...]
1314 DeducedType *Deduced = Ty->getContainedDeducedType();
1315 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1316 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1317 Kind, Exprs);
1318 if (Ty.isNull())
1319 return ExprError();
1320 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1321 }
1322
1323 // C++ [expr.type.conv]p1:
1324 // If the expression list is a parenthesized single expression, the type
1325 // conversion expression is equivalent (in definedness, and if defined in
1326 // meaning) to the corresponding cast expression.
1327 if (Exprs.size() == 1 && !ListInitialization &&
1328 !isa<InitListExpr>(Exprs[0])) {
1329 Expr *Arg = Exprs[0];
1330 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1331 RParenOrBraceLoc);
1332 }
1333
1334 // For an expression of the form T(), T shall not be an array type.
1335 QualType ElemTy = Ty;
1336 if (Ty->isArrayType()) {
1337 if (!ListInitialization)
1338 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1339 << FullRange);
1340 ElemTy = Context.getBaseElementType(Ty);
1341 }
1342
1343 // There doesn't seem to be an explicit rule against this but sanity demands
1344 // we only construct objects with object types.
1345 if (Ty->isFunctionType())
1346 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1347 << Ty << FullRange);
1348
1349 // C++17 [expr.type.conv]p2:
1350 // If the type is cv void and the initializer is (), the expression is a
1351 // prvalue of the specified type that performs no initialization.
1352 if (!Ty->isVoidType() &&
1353 RequireCompleteType(TyBeginLoc, ElemTy,
1354 diag::err_invalid_incomplete_type_use, FullRange))
1355 return ExprError();
1356
1357 // Otherwise, the expression is a prvalue of the specified type whose
1358 // result object is direct-initialized (11.6) with the initializer.
1359 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1360 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1361
1362 if (Result.isInvalid())
1363 return Result;
1364
1365 Expr *Inner = Result.get();
1366 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1367 Inner = BTE->getSubExpr();
1368 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1369 !isa<CXXScalarValueInitExpr>(Inner)) {
1370 // If we created a CXXTemporaryObjectExpr, that node also represents the
1371 // functional cast. Otherwise, create an explicit cast to represent
1372 // the syntactic form of a functional-style cast that was used here.
1373 //
1374 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1375 // would give a more consistent AST representation than using a
1376 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1377 // is sometimes handled by initialization and sometimes not.
1378 QualType ResultType = Result.get()->getType();
1379 SourceRange Locs = ListInitialization
1380 ? SourceRange()
1381 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1382 Result = CXXFunctionalCastExpr::Create(
1383 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1384 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1385 }
1386
1387 return Result;
1388}
1389
1390/// \brief Determine whether the given function is a non-placement
1391/// deallocation function.
1392static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1393 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1394 return Method->isUsualDeallocationFunction();
1395
1396 if (FD->getOverloadedOperator() != OO_Delete &&
1397 FD->getOverloadedOperator() != OO_Array_Delete)
1398 return false;
1399
1400 unsigned UsualParams = 1;
1401
1402 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1403 S.Context.hasSameUnqualifiedType(
1404 FD->getParamDecl(UsualParams)->getType(),
1405 S.Context.getSizeType()))
1406 ++UsualParams;
1407
1408 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1409 S.Context.hasSameUnqualifiedType(
1410 FD->getParamDecl(UsualParams)->getType(),
1411 S.Context.getTypeDeclType(S.getStdAlignValT())))
1412 ++UsualParams;
1413
1414 return UsualParams == FD->getNumParams();
1415}
1416
1417namespace {
1418 struct UsualDeallocFnInfo {
1419 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1420 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1421 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1422 Destroying(false), HasSizeT(false), HasAlignValT(false),
1423 CUDAPref(Sema::CFP_Native) {
1424 // A function template declaration is never a usual deallocation function.
1425 if (!FD)
1426 return;
1427 unsigned NumBaseParams = 1;
1428 if (FD->isDestroyingOperatorDelete()) {
1429 Destroying = true;
1430 ++NumBaseParams;
1431 }
1432 if (FD->getNumParams() == NumBaseParams + 2)
1433 HasAlignValT = HasSizeT = true;
1434 else if (FD->getNumParams() == NumBaseParams + 1) {
1435 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
1436 HasAlignValT = !HasSizeT;
1437 }
1438
1439 // In CUDA, determine how much we'd like / dislike to call this.
1440 if (S.getLangOpts().CUDA)
1441 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1442 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1443 }
1444
1445 operator bool() const { return FD; }
1446
1447 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1448 bool WantAlign) const {
1449 // C++ P0722:
1450 // A destroying operator delete is preferred over a non-destroying
1451 // operator delete.
1452 if (Destroying != Other.Destroying)
1453 return Destroying;
1454
1455 // C++17 [expr.delete]p10:
1456 // If the type has new-extended alignment, a function with a parameter
1457 // of type std::align_val_t is preferred; otherwise a function without
1458 // such a parameter is preferred
1459 if (HasAlignValT != Other.HasAlignValT)
1460 return HasAlignValT == WantAlign;
1461
1462 if (HasSizeT != Other.HasSizeT)
1463 return HasSizeT == WantSize;
1464
1465 // Use CUDA call preference as a tiebreaker.
1466 return CUDAPref > Other.CUDAPref;
1467 }
1468
1469 DeclAccessPair Found;
1470 FunctionDecl *FD;
1471 bool Destroying, HasSizeT, HasAlignValT;
1472 Sema::CUDAFunctionPreference CUDAPref;
1473 };
1474}
1475
1476/// Determine whether a type has new-extended alignment. This may be called when
1477/// the type is incomplete (for a delete-expression with an incomplete pointee
1478/// type), in which case it will conservatively return false if the alignment is
1479/// not known.
1480static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1481 return S.getLangOpts().AlignedAllocation &&
1482 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1483 S.getASTContext().getTargetInfo().getNewAlign();
1484}
1485
1486/// Select the correct "usual" deallocation function to use from a selection of
1487/// deallocation functions (either global or class-scope).
1488static UsualDeallocFnInfo resolveDeallocationOverload(
1489 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1490 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1491 UsualDeallocFnInfo Best;
1492
1493 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1494 UsualDeallocFnInfo Info(S, I.getPair());
1495 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1496 Info.CUDAPref == Sema::CFP_Never)
1497 continue;
1498
1499 if (!Best) {
1500 Best = Info;
1501 if (BestFns)
1502 BestFns->push_back(Info);
1503 continue;
1504 }
1505
1506 if (Best.isBetterThan(Info, WantSize, WantAlign))
1507 continue;
1508
1509 // If more than one preferred function is found, all non-preferred
1510 // functions are eliminated from further consideration.
1511 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1512 BestFns->clear();
1513
1514 Best = Info;
1515 if (BestFns)
1516 BestFns->push_back(Info);
1517 }
1518
1519 return Best;
1520}
1521
1522/// Determine whether a given type is a class for which 'delete[]' would call
1523/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1524/// we need to store the array size (even if the type is
1525/// trivially-destructible).
1526static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1527 QualType allocType) {
1528 const RecordType *record =
1529 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1530 if (!record) return false;
1531
1532 // Try to find an operator delete[] in class scope.
1533
1534 DeclarationName deleteName =
1535 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1536 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1537 S.LookupQualifiedName(ops, record->getDecl());
1538
1539 // We're just doing this for information.
1540 ops.suppressDiagnostics();
1541
1542 // Very likely: there's no operator delete[].
1543 if (ops.empty()) return false;
1544
1545 // If it's ambiguous, it should be illegal to call operator delete[]
1546 // on this thing, so it doesn't matter if we allocate extra space or not.
1547 if (ops.isAmbiguous()) return false;
1548
1549 // C++17 [expr.delete]p10:
1550 // If the deallocation functions have class scope, the one without a
1551 // parameter of type std::size_t is selected.
1552 auto Best = resolveDeallocationOverload(
1553 S, ops, /*WantSize*/false,
1554 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1555 return Best && Best.HasSizeT;
1556}
1557
1558/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1559///
1560/// E.g.:
1561/// @code new (memory) int[size][4] @endcode
1562/// or
1563/// @code ::new Foo(23, "hello") @endcode
1564///
1565/// \param StartLoc The first location of the expression.
1566/// \param UseGlobal True if 'new' was prefixed with '::'.
1567/// \param PlacementLParen Opening paren of the placement arguments.
1568/// \param PlacementArgs Placement new arguments.
1569/// \param PlacementRParen Closing paren of the placement arguments.
1570/// \param TypeIdParens If the type is in parens, the source range.
1571/// \param D The type to be allocated, as well as array dimensions.
1572/// \param Initializer The initializing expression or initializer-list, or null
1573/// if there is none.
1574ExprResult
1575Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1576 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1577 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1578 Declarator &D, Expr *Initializer) {
1579 Expr *ArraySize = nullptr;
1580 // If the specified type is an array, unwrap it and save the expression.
1581 if (D.getNumTypeObjects() > 0 &&
1582 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1583 DeclaratorChunk &Chunk = D.getTypeObject(0);
1584 if (D.getDeclSpec().hasAutoTypeSpec())
1585 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1586 << D.getSourceRange());
1587 if (Chunk.Arr.hasStatic)
1588 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1589 << D.getSourceRange());
1590 if (!Chunk.Arr.NumElts)
1591 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1592 << D.getSourceRange());
1593
1594 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1595 D.DropFirstTypeObject();
1596 }
1597
1598 // Every dimension shall be of constant size.
1599 if (ArraySize) {
1600 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1601 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1602 break;
1603
1604 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1605 if (Expr *NumElts = (Expr *)Array.NumElts) {
1606 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1607 if (getLangOpts().CPlusPlus14) {
1608 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1609 // shall be a converted constant expression (5.19) of type std::size_t
1610 // and shall evaluate to a strictly positive value.
1611 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1612 assert(IntWidth && "Builtin type of size 0?")(static_cast <bool> (IntWidth && "Builtin type of size 0?"
) ? void (0) : __assert_fail ("IntWidth && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1612, __extension__ __PRETTY_FUNCTION__))
;
1613 llvm::APSInt Value(IntWidth);
1614 Array.NumElts
1615 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1616 CCEK_NewExpr)
1617 .get();
1618 } else {
1619 Array.NumElts
1620 = VerifyIntegerConstantExpression(NumElts, nullptr,
1621 diag::err_new_array_nonconst)
1622 .get();
1623 }
1624 if (!Array.NumElts)
1625 return ExprError();
1626 }
1627 }
1628 }
1629 }
1630
1631 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1632 QualType AllocType = TInfo->getType();
1633 if (D.isInvalidType())
1634 return ExprError();
1635
1636 SourceRange DirectInitRange;
1637 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1638 DirectInitRange = List->getSourceRange();
1639
1640 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1641 PlacementLParen,
1642 PlacementArgs,
1643 PlacementRParen,
1644 TypeIdParens,
1645 AllocType,
1646 TInfo,
1647 ArraySize,
1648 DirectInitRange,
1649 Initializer);
1650}
1651
1652static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1653 Expr *Init) {
1654 if (!Init)
1655 return true;
1656 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1657 return PLE->getNumExprs() == 0;
1658 if (isa<ImplicitValueInitExpr>(Init))
1659 return true;
1660 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1661 return !CCE->isListInitialization() &&
1662 CCE->getConstructor()->isDefaultConstructor();
1663 else if (Style == CXXNewExpr::ListInit) {
1664 assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) &&
"Shouldn't create list CXXConstructExprs for arrays.") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1665, __extension__ __PRETTY_FUNCTION__))
1665 "Shouldn't create list CXXConstructExprs for arrays.")(static_cast <bool> (isa<InitListExpr>(Init) &&
"Shouldn't create list CXXConstructExprs for arrays.") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1665, __extension__ __PRETTY_FUNCTION__))
;
1666 return true;
1667 }
1668 return false;
1669}
1670
1671// Emit a diagnostic if an aligned allocation/deallocation function that is not
1672// implemented in the standard library is selected.
1673static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1674 SourceLocation Loc, bool IsDelete,
1675 Sema &S) {
1676 if (!S.getLangOpts().AlignedAllocationUnavailable)
1677 return;
1678
1679 // Return if there is a definition.
1680 if (FD.isDefined())
1681 return;
1682
1683 bool IsAligned = false;
1684 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
1685 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1686 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1687 S.getASTContext().getTargetInfo().getPlatformName());
1688
1689 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
1690 << IsDelete << FD.getType().getAsString() << OSName
1691 << alignedAllocMinVersion(T.getOS()).getAsString();
1692 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1693 }
1694}
1695
1696ExprResult
1697Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1698 SourceLocation PlacementLParen,
1699 MultiExprArg PlacementArgs,
1700 SourceLocation PlacementRParen,
1701 SourceRange TypeIdParens,
1702 QualType AllocType,
1703 TypeSourceInfo *AllocTypeInfo,
1704 Expr *ArraySize,
1705 SourceRange DirectInitRange,
1706 Expr *Initializer) {
1707 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1708 SourceLocation StartLoc = Range.getBegin();
1709
1710 CXXNewExpr::InitializationStyle initStyle;
1711 if (DirectInitRange.isValid()) {
1712 assert(Initializer && "Have parens but no initializer.")(static_cast <bool> (Initializer && "Have parens but no initializer."
) ? void (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1712, __extension__ __PRETTY_FUNCTION__))
;
1713 initStyle = CXXNewExpr::CallInit;
1714 } else if (Initializer && isa<InitListExpr>(Initializer))
1715 initStyle = CXXNewExpr::ListInit;
1716 else {
1717 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1719, __extension__ __PRETTY_FUNCTION__))
1718 isa<CXXConstructExpr>(Initializer)) &&(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1719, __extension__ __PRETTY_FUNCTION__))
1719 "Initializer expression that cannot have been implicitly created.")(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1719, __extension__ __PRETTY_FUNCTION__))
;
1720 initStyle = CXXNewExpr::NoInit;
1721 }
1722
1723 Expr **Inits = &Initializer;
1724 unsigned NumInits = Initializer ? 1 : 0;
1725 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1726 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")(static_cast <bool> (initStyle == CXXNewExpr::CallInit &&
"paren init for non-call init") ? void (0) : __assert_fail (
"initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1726, __extension__ __PRETTY_FUNCTION__))
;
1727 Inits = List->getExprs();
1728 NumInits = List->getNumExprs();
1729 }
1730
1731 // C++11 [expr.new]p15:
1732 // A new-expression that creates an object of type T initializes that
1733 // object as follows:
1734 InitializationKind Kind
1735 // - If the new-initializer is omitted, the object is default-
1736 // initialized (8.5); if no initialization is performed,
1737 // the object has indeterminate value
1738 = initStyle == CXXNewExpr::NoInit
1739 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1740 // - Otherwise, the new-initializer is interpreted according to the
1741 // initialization rules of 8.5 for direct-initialization.
1742 : initStyle == CXXNewExpr::ListInit
1743 ? InitializationKind::CreateDirectList(TypeRange.getBegin(),
1744 Initializer->getLocStart(),
1745 Initializer->getLocEnd())
1746 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1747 DirectInitRange.getBegin(),
1748 DirectInitRange.getEnd());
1749
1750 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1751 auto *Deduced = AllocType->getContainedDeducedType();
1752 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1753 if (ArraySize)
1754 return ExprError(Diag(ArraySize->getExprLoc(),
1755 diag::err_deduced_class_template_compound_type)
1756 << /*array*/ 2 << ArraySize->getSourceRange());
1757
1758 InitializedEntity Entity
1759 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1760 AllocType = DeduceTemplateSpecializationFromInitializer(
1761 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1762 if (AllocType.isNull())
1763 return ExprError();
1764 } else if (Deduced) {
1765 bool Braced = (initStyle == CXXNewExpr::ListInit);
1766 if (NumInits == 1) {
1767 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1768 Inits = p->getInits();
1769 NumInits = p->getNumInits();
1770 Braced = true;
1771 }
1772 }
1773
1774 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1775 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1776 << AllocType << TypeRange);
1777 if (NumInits > 1) {
1778 Expr *FirstBad = Inits[1];
1779 return ExprError(Diag(FirstBad->getLocStart(),
1780 diag::err_auto_new_ctor_multiple_expressions)
1781 << AllocType << TypeRange);
1782 }
1783 if (Braced && !getLangOpts().CPlusPlus17)
1784 Diag(Initializer->getLocStart(), diag::ext_auto_new_list_init)
1785 << AllocType << TypeRange;
1786 Expr *Deduce = Inits[0];
1787 QualType DeducedType;
1788 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1789 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1790 << AllocType << Deduce->getType()
1791 << TypeRange << Deduce->getSourceRange());
1792 if (DeducedType.isNull())
1793 return ExprError();
1794 AllocType = DeducedType;
1795 }
1796
1797 // Per C++0x [expr.new]p5, the type being constructed may be a
1798 // typedef of an array type.
1799 if (!ArraySize) {
1800 if (const ConstantArrayType *Array
1801 = Context.getAsConstantArrayType(AllocType)) {
1802 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1803 Context.getSizeType(),
1804 TypeRange.getEnd());
1805 AllocType = Array->getElementType();
1806 }
1807 }
1808
1809 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1810 return ExprError();
1811
1812 if (initStyle == CXXNewExpr::ListInit &&
1813 isStdInitializerList(AllocType, nullptr)) {
1814 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1815 diag::warn_dangling_std_initializer_list)
1816 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1817 }
1818
1819 // In ARC, infer 'retaining' for the allocated
1820 if (getLangOpts().ObjCAutoRefCount &&
1821 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1822 AllocType->isObjCLifetimeType()) {
1823 AllocType = Context.getLifetimeQualifiedType(AllocType,
1824 AllocType->getObjCARCImplicitLifetime());
1825 }
1826
1827 QualType ResultType = Context.getPointerType(AllocType);
1828
1829 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1830 ExprResult result = CheckPlaceholderExpr(ArraySize);
1831 if (result.isInvalid()) return ExprError();
1832 ArraySize = result.get();
1833 }
1834 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1835 // integral or enumeration type with a non-negative value."
1836 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1837 // enumeration type, or a class type for which a single non-explicit
1838 // conversion function to integral or unscoped enumeration type exists.
1839 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1840 // std::size_t.
1841 llvm::Optional<uint64_t> KnownArraySize;
1842 if (ArraySize && !ArraySize->isTypeDependent()) {
1843 ExprResult ConvertedSize;
1844 if (getLangOpts().CPlusPlus14) {
1845 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")(static_cast <bool> (Context.getTargetInfo().getIntWidth
() && "Builtin type of size 0?") ? void (0) : __assert_fail
("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1845, __extension__ __PRETTY_FUNCTION__))
;
1846
1847 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1848 AA_Converting);
1849
1850 if (!ConvertedSize.isInvalid() &&
1851 ArraySize->getType()->getAs<RecordType>())
1852 // Diagnose the compatibility of this conversion.
1853 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1854 << ArraySize->getType() << 0 << "'size_t'";
1855 } else {
1856 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1857 protected:
1858 Expr *ArraySize;
1859
1860 public:
1861 SizeConvertDiagnoser(Expr *ArraySize)
1862 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1863 ArraySize(ArraySize) {}
1864
1865 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1866 QualType T) override {
1867 return S.Diag(Loc, diag::err_array_size_not_integral)
1868 << S.getLangOpts().CPlusPlus11 << T;
1869 }
1870
1871 SemaDiagnosticBuilder diagnoseIncomplete(
1872 Sema &S, SourceLocation Loc, QualType T) override {
1873 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1874 << T << ArraySize->getSourceRange();
1875 }
1876
1877 SemaDiagnosticBuilder diagnoseExplicitConv(
1878 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1879 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1880 }
1881
1882 SemaDiagnosticBuilder noteExplicitConv(
1883 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1884 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1885 << ConvTy->isEnumeralType() << ConvTy;
1886 }
1887
1888 SemaDiagnosticBuilder diagnoseAmbiguous(
1889 Sema &S, SourceLocation Loc, QualType T) override {
1890 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1891 }
1892
1893 SemaDiagnosticBuilder noteAmbiguous(
1894 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1895 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1896 << ConvTy->isEnumeralType() << ConvTy;
1897 }
1898
1899 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1900 QualType T,
1901 QualType ConvTy) override {
1902 return S.Diag(Loc,
1903 S.getLangOpts().CPlusPlus11
1904 ? diag::warn_cxx98_compat_array_size_conversion
1905 : diag::ext_array_size_conversion)
1906 << T << ConvTy->isEnumeralType() << ConvTy;
1907 }
1908 } SizeDiagnoser(ArraySize);
1909
1910 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1911 SizeDiagnoser);
1912 }
1913 if (ConvertedSize.isInvalid())
1914 return ExprError();
1915
1916 ArraySize = ConvertedSize.get();
1917 QualType SizeType = ArraySize->getType();
1918
1919 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1920 return ExprError();
1921
1922 // C++98 [expr.new]p7:
1923 // The expression in a direct-new-declarator shall have integral type
1924 // with a non-negative value.
1925 //
1926 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1927 // per CWG1464. Otherwise, if it's not a constant, we must have an
1928 // unparenthesized array type.
1929 if (!ArraySize->isValueDependent()) {
1930 llvm::APSInt Value;
1931 // We've already performed any required implicit conversion to integer or
1932 // unscoped enumeration type.
1933 // FIXME: Per CWG1464, we are required to check the value prior to
1934 // converting to size_t. This will never find a negative array size in
1935 // C++14 onwards, because Value is always unsigned here!
1936 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1937 if (Value.isSigned() && Value.isNegative()) {
1938 return ExprError(Diag(ArraySize->getLocStart(),
1939 diag::err_typecheck_negative_array_size)
1940 << ArraySize->getSourceRange());
1941 }
1942
1943 if (!AllocType->isDependentType()) {
1944 unsigned ActiveSizeBits =
1945 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1946 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1947 return ExprError(Diag(ArraySize->getLocStart(),
1948 diag::err_array_too_large)
1949 << Value.toString(10)
1950 << ArraySize->getSourceRange());
1951 }
1952
1953 KnownArraySize = Value.getZExtValue();
1954 } else if (TypeIdParens.isValid()) {
1955 // Can't have dynamic array size when the type-id is in parentheses.
1956 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1957 << ArraySize->getSourceRange()
1958 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1959 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1960
1961 TypeIdParens = SourceRange();
1962 }
1963 }
1964
1965 // Note that we do *not* convert the argument in any way. It can
1966 // be signed, larger than size_t, whatever.
1967 }
1968
1969 FunctionDecl *OperatorNew = nullptr;
1970 FunctionDecl *OperatorDelete = nullptr;
1971 unsigned Alignment =
1972 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1973 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1974 bool PassAlignment = getLangOpts().AlignedAllocation &&
1975 Alignment > NewAlignment;
1976
1977 if (!AllocType->isDependentType() &&
1978 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1979 FindAllocationFunctions(StartLoc,
1980 SourceRange(PlacementLParen, PlacementRParen),
1981 UseGlobal, AllocType, ArraySize, PassAlignment,
1982 PlacementArgs, OperatorNew, OperatorDelete))
1983 return ExprError();
1984
1985 // If this is an array allocation, compute whether the usual array
1986 // deallocation function for the type has a size_t parameter.
1987 bool UsualArrayDeleteWantsSize = false;
1988 if (ArraySize && !AllocType->isDependentType())
1989 UsualArrayDeleteWantsSize =
1990 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1991
1992 SmallVector<Expr *, 8> AllPlaceArgs;
1993 if (OperatorNew) {
1994 const FunctionProtoType *Proto =
1995 OperatorNew->getType()->getAs<FunctionProtoType>();
1996 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1997 : VariadicDoesNotApply;
1998
1999 // We've already converted the placement args, just fill in any default
2000 // arguments. Skip the first parameter because we don't have a corresponding
2001 // argument. Skip the second parameter too if we're passing in the
2002 // alignment; we've already filled it in.
2003 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2004 PassAlignment ? 2 : 1, PlacementArgs,
2005 AllPlaceArgs, CallType))
2006 return ExprError();
2007
2008 if (!AllPlaceArgs.empty())
2009 PlacementArgs = AllPlaceArgs;
2010
2011 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2012 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2013
2014 // FIXME: Missing call to CheckFunctionCall or equivalent
2015
2016 // Warn if the type is over-aligned and is being allocated by (unaligned)
2017 // global operator new.
2018 if (PlacementArgs.empty() && !PassAlignment &&
2019 (OperatorNew->isImplicit() ||
2020 (OperatorNew->getLocStart().isValid() &&
2021 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
2022 if (Alignment > NewAlignment)
2023 Diag(StartLoc, diag::warn_overaligned_type)
2024 << AllocType
2025 << unsigned(Alignment / Context.getCharWidth())
2026 << unsigned(NewAlignment / Context.getCharWidth());
2027 }
2028 }
2029
2030 // Array 'new' can't have any initializers except empty parentheses.
2031 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2032 // dialect distinction.
2033 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2034 SourceRange InitRange(Inits[0]->getLocStart(),
2035 Inits[NumInits - 1]->getLocEnd());
2036 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2037 return ExprError();
2038 }
2039
2040 // If we can perform the initialization, and we've not already done so,
2041 // do it now.
2042 if (!AllocType->isDependentType() &&
2043 !Expr::hasAnyTypeDependentArguments(
2044 llvm::makeArrayRef(Inits, NumInits))) {
2045 // The type we initialize is the complete type, including the array bound.
2046 QualType InitType;
2047 if (KnownArraySize)
2048 InitType = Context.getConstantArrayType(
2049 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2050 *KnownArraySize),
2051 ArrayType::Normal, 0);
2052 else if (ArraySize)
2053 InitType =
2054 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2055 else
2056 InitType = AllocType;
2057
2058 InitializedEntity Entity
2059 = InitializedEntity::InitializeNew(StartLoc, InitType);
2060 InitializationSequence InitSeq(*this, Entity, Kind,
2061 MultiExprArg(Inits, NumInits));
2062 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2063 MultiExprArg(Inits, NumInits));
2064 if (FullInit.isInvalid())
2065 return ExprError();
2066
2067 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2068 // we don't want the initialized object to be destructed.
2069 // FIXME: We should not create these in the first place.
2070 if (CXXBindTemporaryExpr *Binder =
2071 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2072 FullInit = Binder->getSubExpr();
2073
2074 Initializer = FullInit.get();
2075 }
2076
2077 // Mark the new and delete operators as referenced.
2078 if (OperatorNew) {
2079 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2080 return ExprError();
2081 MarkFunctionReferenced(StartLoc, OperatorNew);
2082 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
2083 }
2084 if (OperatorDelete) {
2085 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2086 return ExprError();
2087 MarkFunctionReferenced(StartLoc, OperatorDelete);
2088 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
2089 }
2090
2091 // C++0x [expr.new]p17:
2092 // If the new expression creates an array of objects of class type,
2093 // access and ambiguity control are done for the destructor.
2094 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2095 if (ArraySize && !BaseAllocType->isDependentType()) {
2096 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2097 if (CXXDestructorDecl *dtor = LookupDestructor(
2098 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2099 MarkFunctionReferenced(StartLoc, dtor);
2100 CheckDestructorAccess(StartLoc, dtor,
2101 PDiag(diag::err_access_dtor)
2102 << BaseAllocType);
2103 if (DiagnoseUseOfDecl(dtor, StartLoc))
2104 return ExprError();
2105 }
2106 }
2107 }
2108
2109 return new (Context)
2110 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2111 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2112 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2113 Range, DirectInitRange);
2114}
2115
2116/// \brief Checks that a type is suitable as the allocated type
2117/// in a new-expression.
2118bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2119 SourceRange R) {
2120 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2121 // abstract class type or array thereof.
2122 if (AllocType->isFunctionType())
2123 return Diag(Loc, diag::err_bad_new_type)
2124 << AllocType << 0 << R;
2125 else if (AllocType->isReferenceType())
2126 return Diag(Loc, diag::err_bad_new_type)
2127 << AllocType << 1 << R;
2128 else if (!AllocType->isDependentType() &&
2129 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2130 return true;
2131 else if (RequireNonAbstractType(Loc, AllocType,
2132 diag::err_allocation_of_abstract_type))
2133 return true;
2134 else if (AllocType->isVariablyModifiedType())
2135 return Diag(Loc, diag::err_variably_modified_new_type)
2136 << AllocType;
2137 else if (AllocType.getAddressSpace() != LangAS::Default)
2138 return Diag(Loc, diag::err_address_space_qualified_new)
2139 << AllocType.getUnqualifiedType()
2140 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2141 else if (getLangOpts().ObjCAutoRefCount) {
2142 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2143 QualType BaseAllocType = Context.getBaseElementType(AT);
2144 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2145 BaseAllocType->isObjCLifetimeType())
2146 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2147 << BaseAllocType;
2148 }
2149 }
2150
2151 return false;
2152}
2153
2154static bool resolveAllocationOverload(
2155 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2156 bool &PassAlignment, FunctionDecl *&Operator,
2157 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2158 OverloadCandidateSet Candidates(R.getNameLoc(),
2159 OverloadCandidateSet::CSK_Normal);
2160 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2161 Alloc != AllocEnd; ++Alloc) {
2162 // Even member operator new/delete are implicitly treated as
2163 // static, so don't use AddMemberCandidate.
2164 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2165
2166 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2167 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2168 /*ExplicitTemplateArgs=*/nullptr, Args,
2169 Candidates,
2170 /*SuppressUserConversions=*/false);
2171 continue;
2172 }
2173
2174 FunctionDecl *Fn = cast<FunctionDecl>(D);
2175 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2176 /*SuppressUserConversions=*/false);
2177 }
2178
2179 // Do the resolution.
2180 OverloadCandidateSet::iterator Best;
2181 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2182 case OR_Success: {
2183 // Got one!
2184 FunctionDecl *FnDecl = Best->Function;
2185 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2186 Best->FoundDecl) == Sema::AR_inaccessible)
2187 return true;
2188
2189 Operator = FnDecl;
2190 return false;
2191 }
2192
2193 case OR_No_Viable_Function:
2194 // C++17 [expr.new]p13:
2195 // If no matching function is found and the allocated object type has
2196 // new-extended alignment, the alignment argument is removed from the
2197 // argument list, and overload resolution is performed again.
2198 if (PassAlignment) {
2199 PassAlignment = false;
2200 AlignArg = Args[1];
2201 Args.erase(Args.begin() + 1);
2202 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2203 Operator, &Candidates, AlignArg,
2204 Diagnose);
2205 }
2206
2207 // MSVC will fall back on trying to find a matching global operator new
2208 // if operator new[] cannot be found. Also, MSVC will leak by not
2209 // generating a call to operator delete or operator delete[], but we
2210 // will not replicate that bug.
2211 // FIXME: Find out how this interacts with the std::align_val_t fallback
2212 // once MSVC implements it.
2213 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2214 S.Context.getLangOpts().MSVCCompat) {
2215 R.clear();
2216 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2217 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2218 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2219 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2220 Operator, /*Candidates=*/nullptr,
2221 /*AlignArg=*/nullptr, Diagnose);
2222 }
2223
2224 if (Diagnose) {
2225 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2226 << R.getLookupName() << Range;
2227
2228 // If we have aligned candidates, only note the align_val_t candidates
2229 // from AlignedCandidates and the non-align_val_t candidates from
2230 // Candidates.
2231 if (AlignedCandidates) {
2232 auto IsAligned = [](OverloadCandidate &C) {
2233 return C.Function->getNumParams() > 1 &&
2234 C.Function->getParamDecl(1)->getType()->isAlignValT();
2235 };
2236 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2237
2238 // This was an overaligned allocation, so list the aligned candidates
2239 // first.
2240 Args.insert(Args.begin() + 1, AlignArg);
2241 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2242 R.getNameLoc(), IsAligned);
2243 Args.erase(Args.begin() + 1);
2244 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2245 IsUnaligned);
2246 } else {
2247 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2248 }
2249 }
2250 return true;
2251
2252 case OR_Ambiguous:
2253 if (Diagnose) {
2254 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2255 << R.getLookupName() << Range;
2256 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2257 }
2258 return true;
2259
2260 case OR_Deleted: {
2261 if (Diagnose) {
2262 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2263 << Best->Function->isDeleted() << R.getLookupName()
2264 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2265 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2266 }
2267 return true;
2268 }
2269 }
2270 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2270)
;
2271}
2272
2273
2274/// FindAllocationFunctions - Finds the overloads of operator new and delete
2275/// that are appropriate for the allocation.
2276bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2277 bool UseGlobal, QualType AllocType,
2278 bool IsArray, bool &PassAlignment,
2279 MultiExprArg PlaceArgs,
2280 FunctionDecl *&OperatorNew,
2281 FunctionDecl *&OperatorDelete,
2282 bool Diagnose) {
2283 // --- Choosing an allocation function ---
2284 // C++ 5.3.4p8 - 14 & 18
2285 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2286 // in the scope of the allocated class.
2287 // 2) If an array size is given, look for operator new[], else look for
2288 // operator new.
2289 // 3) The first argument is always size_t. Append the arguments from the
2290 // placement form.
2291
2292 SmallVector<Expr*, 8> AllocArgs;
2293 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2294
2295 // We don't care about the actual value of these arguments.
2296 // FIXME: Should the Sema create the expression and embed it in the syntax
2297 // tree? Or should the consumer just recalculate the value?
2298 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2299 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2300 Context.getTargetInfo().getPointerWidth(0)),
2301 Context.getSizeType(),
2302 SourceLocation());
2303 AllocArgs.push_back(&Size);
2304
2305 QualType AlignValT = Context.VoidTy;
2306 if (PassAlignment) {
2307 DeclareGlobalNewDelete();
2308 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2309 }
2310 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2311 if (PassAlignment)
2312 AllocArgs.push_back(&Align);
2313
2314 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2315
2316 // C++ [expr.new]p8:
2317 // If the allocated type is a non-array type, the allocation
2318 // function's name is operator new and the deallocation function's
2319 // name is operator delete. If the allocated type is an array
2320 // type, the allocation function's name is operator new[] and the
2321 // deallocation function's name is operator delete[].
2322 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2323 IsArray ? OO_Array_New : OO_New);
2324
2325 QualType AllocElemType = Context.getBaseElementType(AllocType);
2326
2327 // Find the allocation function.
2328 {
2329 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2330
2331 // C++1z [expr.new]p9:
2332 // If the new-expression begins with a unary :: operator, the allocation
2333 // function's name is looked up in the global scope. Otherwise, if the
2334 // allocated type is a class type T or array thereof, the allocation
2335 // function's name is looked up in the scope of T.
2336 if (AllocElemType->isRecordType() && !UseGlobal)
2337 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2338
2339 // We can see ambiguity here if the allocation function is found in
2340 // multiple base classes.
2341 if (R.isAmbiguous())
2342 return true;
2343
2344 // If this lookup fails to find the name, or if the allocated type is not
2345 // a class type, the allocation function's name is looked up in the
2346 // global scope.
2347 if (R.empty())
2348 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2349
2350 assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found"
) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2350, __extension__ __PRETTY_FUNCTION__))
;
2351 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2351, __extension__ __PRETTY_FUNCTION__))
;
2352
2353 // We do our own custom access checks below.
2354 R.suppressDiagnostics();
2355
2356 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2357 OperatorNew, /*Candidates=*/nullptr,
2358 /*AlignArg=*/nullptr, Diagnose))
2359 return true;
2360 }
2361
2362 // We don't need an operator delete if we're running under -fno-exceptions.
2363 if (!getLangOpts().Exceptions) {
2364 OperatorDelete = nullptr;
2365 return false;
2366 }
2367
2368 // Note, the name of OperatorNew might have been changed from array to
2369 // non-array by resolveAllocationOverload.
2370 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2371 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2372 ? OO_Array_Delete
2373 : OO_Delete);
2374
2375 // C++ [expr.new]p19:
2376 //
2377 // If the new-expression begins with a unary :: operator, the
2378 // deallocation function's name is looked up in the global
2379 // scope. Otherwise, if the allocated type is a class type T or an
2380 // array thereof, the deallocation function's name is looked up in
2381 // the scope of T. If this lookup fails to find the name, or if
2382 // the allocated type is not a class type or array thereof, the
2383 // deallocation function's name is looked up in the global scope.
2384 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2385 if (AllocElemType->isRecordType() && !UseGlobal) {
2386 CXXRecordDecl *RD
2387 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2388 LookupQualifiedName(FoundDelete, RD);
2389 }
2390 if (FoundDelete.isAmbiguous())
2391 return true; // FIXME: clean up expressions?
2392
2393 bool FoundGlobalDelete = FoundDelete.empty();
2394 if (FoundDelete.empty()) {
2395 DeclareGlobalNewDelete();
2396 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2397 }
2398
2399 FoundDelete.suppressDiagnostics();
2400
2401 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2402
2403 // Whether we're looking for a placement operator delete is dictated
2404 // by whether we selected a placement operator new, not by whether
2405 // we had explicit placement arguments. This matters for things like
2406 // struct A { void *operator new(size_t, int = 0); ... };
2407 // A *a = new A()
2408 //
2409 // We don't have any definition for what a "placement allocation function"
2410 // is, but we assume it's any allocation function whose
2411 // parameter-declaration-clause is anything other than (size_t).
2412 //
2413 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2414 // This affects whether an exception from the constructor of an overaligned
2415 // type uses the sized or non-sized form of aligned operator delete.
2416 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2417 OperatorNew->isVariadic();
2418
2419 if (isPlacementNew) {
2420 // C++ [expr.new]p20:
2421 // A declaration of a placement deallocation function matches the
2422 // declaration of a placement allocation function if it has the
2423 // same number of parameters and, after parameter transformations
2424 // (8.3.5), all parameter types except the first are
2425 // identical. [...]
2426 //
2427 // To perform this comparison, we compute the function type that
2428 // the deallocation function should have, and use that type both
2429 // for template argument deduction and for comparison purposes.
2430 QualType ExpectedFunctionType;
2431 {
2432 const FunctionProtoType *Proto
2433 = OperatorNew->getType()->getAs<FunctionProtoType>();
2434
2435 SmallVector<QualType, 4> ArgTypes;
2436 ArgTypes.push_back(Context.VoidPtrTy);
2437 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2438 ArgTypes.push_back(Proto->getParamType(I));
2439
2440 FunctionProtoType::ExtProtoInfo EPI;
2441 // FIXME: This is not part of the standard's rule.
2442 EPI.Variadic = Proto->isVariadic();
2443
2444 ExpectedFunctionType
2445 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2446 }
2447
2448 for (LookupResult::iterator D = FoundDelete.begin(),
2449 DEnd = FoundDelete.end();
2450 D != DEnd; ++D) {
2451 FunctionDecl *Fn = nullptr;
2452 if (FunctionTemplateDecl *FnTmpl =
2453 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2454 // Perform template argument deduction to try to match the
2455 // expected function type.
2456 TemplateDeductionInfo Info(StartLoc);
2457 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2458 Info))
2459 continue;
2460 } else
2461 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2462
2463 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2464 ExpectedFunctionType,
2465 /*AdjustExcpetionSpec*/true),
2466 ExpectedFunctionType))
2467 Matches.push_back(std::make_pair(D.getPair(), Fn));
2468 }
2469
2470 if (getLangOpts().CUDA)
2471 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2472 } else {
2473 // C++1y [expr.new]p22:
2474 // For a non-placement allocation function, the normal deallocation
2475 // function lookup is used
2476 //
2477 // Per [expr.delete]p10, this lookup prefers a member operator delete
2478 // without a size_t argument, but prefers a non-member operator delete
2479 // with a size_t where possible (which it always is in this case).
2480 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2481 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2482 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2483 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2484 &BestDeallocFns);
2485 if (Selected)
2486 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2487 else {
2488 // If we failed to select an operator, all remaining functions are viable
2489 // but ambiguous.
2490 for (auto Fn : BestDeallocFns)
2491 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2492 }
2493 }
2494
2495 // C++ [expr.new]p20:
2496 // [...] If the lookup finds a single matching deallocation
2497 // function, that function will be called; otherwise, no
2498 // deallocation function will be called.
2499 if (Matches.size() == 1) {
2500 OperatorDelete = Matches[0].second;
2501
2502 // C++1z [expr.new]p23:
2503 // If the lookup finds a usual deallocation function (3.7.4.2)
2504 // with a parameter of type std::size_t and that function, considered
2505 // as a placement deallocation function, would have been
2506 // selected as a match for the allocation function, the program
2507 // is ill-formed.
2508 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2509 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2510 UsualDeallocFnInfo Info(*this,
2511 DeclAccessPair::make(OperatorDelete, AS_public));
2512 // Core issue, per mail to core reflector, 2016-10-09:
2513 // If this is a member operator delete, and there is a corresponding
2514 // non-sized member operator delete, this isn't /really/ a sized
2515 // deallocation function, it just happens to have a size_t parameter.
2516 bool IsSizedDelete = Info.HasSizeT;
2517 if (IsSizedDelete && !FoundGlobalDelete) {
2518 auto NonSizedDelete =
2519 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2520 /*WantAlign*/Info.HasAlignValT);
2521 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2522 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2523 IsSizedDelete = false;
2524 }
2525
2526 if (IsSizedDelete) {
2527 SourceRange R = PlaceArgs.empty()
2528 ? SourceRange()
2529 : SourceRange(PlaceArgs.front()->getLocStart(),
2530 PlaceArgs.back()->getLocEnd());
2531 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2532 if (!OperatorDelete->isImplicit())
2533 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2534 << DeleteName;
2535 }
2536 }
2537
2538 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2539 Matches[0].first);
2540 } else if (!Matches.empty()) {
2541 // We found multiple suitable operators. Per [expr.new]p20, that means we
2542 // call no 'operator delete' function, but we should at least warn the user.
2543 // FIXME: Suppress this warning if the construction cannot throw.
2544 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2545 << DeleteName << AllocElemType;
2546
2547 for (auto &Match : Matches)
2548 Diag(Match.second->getLocation(),
2549 diag::note_member_declared_here) << DeleteName;
2550 }
2551
2552 return false;
2553}
2554
2555/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2556/// delete. These are:
2557/// @code
2558/// // C++03:
2559/// void* operator new(std::size_t) throw(std::bad_alloc);
2560/// void* operator new[](std::size_t) throw(std::bad_alloc);
2561/// void operator delete(void *) throw();
2562/// void operator delete[](void *) throw();
2563/// // C++11:
2564/// void* operator new(std::size_t);
2565/// void* operator new[](std::size_t);
2566/// void operator delete(void *) noexcept;
2567/// void operator delete[](void *) noexcept;
2568/// // C++1y:
2569/// void* operator new(std::size_t);
2570/// void* operator new[](std::size_t);
2571/// void operator delete(void *) noexcept;
2572/// void operator delete[](void *) noexcept;
2573/// void operator delete(void *, std::size_t) noexcept;
2574/// void operator delete[](void *, std::size_t) noexcept;
2575/// @endcode
2576/// Note that the placement and nothrow forms of new are *not* implicitly
2577/// declared. Their use requires including \<new\>.
2578void Sema::DeclareGlobalNewDelete() {
2579 if (GlobalNewDeleteDeclared)
2580 return;
2581
2582 // C++ [basic.std.dynamic]p2:
2583 // [...] The following allocation and deallocation functions (18.4) are
2584 // implicitly declared in global scope in each translation unit of a
2585 // program
2586 //
2587 // C++03:
2588 // void* operator new(std::size_t) throw(std::bad_alloc);
2589 // void* operator new[](std::size_t) throw(std::bad_alloc);
2590 // void operator delete(void*) throw();
2591 // void operator delete[](void*) throw();
2592 // C++11:
2593 // void* operator new(std::size_t);
2594 // void* operator new[](std::size_t);
2595 // void operator delete(void*) noexcept;
2596 // void operator delete[](void*) noexcept;
2597 // C++1y:
2598 // void* operator new(std::size_t);
2599 // void* operator new[](std::size_t);
2600 // void operator delete(void*) noexcept;
2601 // void operator delete[](void*) noexcept;
2602 // void operator delete(void*, std::size_t) noexcept;
2603 // void operator delete[](void*, std::size_t) noexcept;
2604 //
2605 // These implicit declarations introduce only the function names operator
2606 // new, operator new[], operator delete, operator delete[].
2607 //
2608 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2609 // "std" or "bad_alloc" as necessary to form the exception specification.
2610 // However, we do not make these implicit declarations visible to name
2611 // lookup.
2612 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2613 // The "std::bad_alloc" class has not yet been declared, so build it
2614 // implicitly.
2615 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2616 getOrCreateStdNamespace(),
2617 SourceLocation(), SourceLocation(),
2618 &PP.getIdentifierTable().get("bad_alloc"),
2619 nullptr);
2620 getStdBadAlloc()->setImplicit(true);
2621 }
2622 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2623 // The "std::align_val_t" enum class has not yet been declared, so build it
2624 // implicitly.
2625 auto *AlignValT = EnumDecl::Create(
2626 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2627 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2628 AlignValT->setIntegerType(Context.getSizeType());
2629 AlignValT->setPromotionType(Context.getSizeType());
2630 AlignValT->setImplicit(true);
2631 StdAlignValT = AlignValT;
2632 }
2633
2634 GlobalNewDeleteDeclared = true;
2635
2636 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2637 QualType SizeT = Context.getSizeType();
2638
2639 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2640 QualType Return, QualType Param) {
2641 llvm::SmallVector<QualType, 3> Params;
2642 Params.push_back(Param);
2643
2644 // Create up to four variants of the function (sized/aligned).
2645 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2646 (Kind == OO_Delete || Kind == OO_Array_Delete);
2647 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2648
2649 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2650 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2651 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2652 if (Sized)
2653 Params.push_back(SizeT);
2654
2655 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2656 if (Aligned)
2657 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2658
2659 DeclareGlobalAllocationFunction(
2660 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2661
2662 if (Aligned)
2663 Params.pop_back();
2664 }
2665 }
2666 };
2667
2668 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2669 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2670 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2671 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2672}
2673
2674/// DeclareGlobalAllocationFunction - Declares a single implicit global
2675/// allocation function if it doesn't already exist.
2676void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2677 QualType Return,
2678 ArrayRef<QualType> Params) {
2679 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2680
2681 // Check if this function is already declared.
2682 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2683 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2684 Alloc != AllocEnd; ++Alloc) {
2685 // Only look at non-template functions, as it is the predefined,
2686 // non-templated allocation function we are trying to declare here.
2687 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2688 if (Func->getNumParams() == Params.size()) {
2689 llvm::SmallVector<QualType, 3> FuncParams;
2690 for (auto *P : Func->parameters())
2691 FuncParams.push_back(
2692 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2693 if (llvm::makeArrayRef(FuncParams) == Params) {
2694 // Make the function visible to name lookup, even if we found it in
2695 // an unimported module. It either is an implicitly-declared global
2696 // allocation function, or is suppressing that function.
2697 Func->setVisibleDespiteOwningModule();
2698 return;
2699 }
2700 }
2701 }
2702 }
2703
2704 FunctionProtoType::ExtProtoInfo EPI;
2705
2706 QualType BadAllocType;
2707 bool HasBadAllocExceptionSpec
2708 = (Name.getCXXOverloadedOperator() == OO_New ||
2709 Name.getCXXOverloadedOperator() == OO_Array_New);
2710 if (HasBadAllocExceptionSpec) {
2711 if (!getLangOpts().CPlusPlus11) {
2712 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2713 assert(StdBadAlloc && "Must have std::bad_alloc declared")(static_cast <bool> (StdBadAlloc && "Must have std::bad_alloc declared"
) ? void (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2713, __extension__ __PRETTY_FUNCTION__))
;
2714 EPI.ExceptionSpec.Type = EST_Dynamic;
2715 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2716 }
2717 } else {
2718 EPI.ExceptionSpec =
2719 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2720 }
2721
2722 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2723 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2724 FunctionDecl *Alloc = FunctionDecl::Create(
2725 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2726 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2727 Alloc->setImplicit();
2728 // Global allocation functions should always be visible.
2729 Alloc->setVisibleDespiteOwningModule();
2730
2731 // Implicit sized deallocation functions always have default visibility.
2732 Alloc->addAttr(
2733 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
2734
2735 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2736 for (QualType T : Params) {
2737 ParamDecls.push_back(ParmVarDecl::Create(
2738 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2739 /*TInfo=*/nullptr, SC_None, nullptr));
2740 ParamDecls.back()->setImplicit();
2741 }
2742 Alloc->setParams(ParamDecls);
2743 if (ExtraAttr)
2744 Alloc->addAttr(ExtraAttr);
2745 Context.getTranslationUnitDecl()->addDecl(Alloc);
2746 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2747 };
2748
2749 if (!LangOpts.CUDA)
2750 CreateAllocationFunctionDecl(nullptr);
2751 else {
2752 // Host and device get their own declaration so each can be
2753 // defined or re-declared independently.
2754 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2755 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2756 }
2757}
2758
2759FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2760 bool CanProvideSize,
2761 bool Overaligned,
2762 DeclarationName Name) {
2763 DeclareGlobalNewDelete();
2764
2765 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2766 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2767
2768 // FIXME: It's possible for this to result in ambiguity, through a
2769 // user-declared variadic operator delete or the enable_if attribute. We
2770 // should probably not consider those cases to be usual deallocation
2771 // functions. But for now we just make an arbitrary choice in that case.
2772 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2773 Overaligned);
2774 assert(Result.FD && "operator delete missing from global scope?")(static_cast <bool> (Result.FD && "operator delete missing from global scope?"
) ? void (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2774, __extension__ __PRETTY_FUNCTION__))
;
2775 return Result.FD;
2776}
2777
2778FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2779 CXXRecordDecl *RD) {
2780 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2781
2782 FunctionDecl *OperatorDelete = nullptr;
2783 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2784 return nullptr;
2785 if (OperatorDelete)
2786 return OperatorDelete;
2787
2788 // If there's no class-specific operator delete, look up the global
2789 // non-array delete.
2790 return FindUsualDeallocationFunction(
2791 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2792 Name);
2793}
2794
2795bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2796 DeclarationName Name,
2797 FunctionDecl *&Operator, bool Diagnose) {
2798 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2799 // Try to find operator delete/operator delete[] in class scope.
2800 LookupQualifiedName(Found, RD);
2801
2802 if (Found.isAmbiguous())
2803 return true;
2804
2805 Found.suppressDiagnostics();
2806
2807 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2808
2809 // C++17 [expr.delete]p10:
2810 // If the deallocation functions have class scope, the one without a
2811 // parameter of type std::size_t is selected.
2812 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2813 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2814 /*WantAlign*/ Overaligned, &Matches);
2815
2816 // If we could find an overload, use it.
2817 if (Matches.size() == 1) {
2818 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2819
2820 // FIXME: DiagnoseUseOfDecl?
2821 if (Operator->isDeleted()) {
2822 if (Diagnose) {
2823 Diag(StartLoc, diag::err_deleted_function_use);
2824 NoteDeletedFunction(Operator);
2825 }
2826 return true;
2827 }
2828
2829 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2830 Matches[0].Found, Diagnose) == AR_inaccessible)
2831 return true;
2832
2833 return false;
2834 }
2835
2836 // We found multiple suitable operators; complain about the ambiguity.
2837 // FIXME: The standard doesn't say to do this; it appears that the intent
2838 // is that this should never happen.
2839 if (!Matches.empty()) {
2840 if (Diagnose) {
2841 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2842 << Name << RD;
2843 for (auto &Match : Matches)
2844 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2845 }
2846 return true;
2847 }
2848
2849 // We did find operator delete/operator delete[] declarations, but
2850 // none of them were suitable.
2851 if (!Found.empty()) {
2852 if (Diagnose) {
2853 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2854 << Name << RD;
2855
2856 for (NamedDecl *D : Found)
2857 Diag(D->getUnderlyingDecl()->getLocation(),
2858 diag::note_member_declared_here) << Name;
2859 }
2860 return true;
2861 }
2862
2863 Operator = nullptr;
2864 return false;
2865}
2866
2867namespace {
2868/// \brief Checks whether delete-expression, and new-expression used for
2869/// initializing deletee have the same array form.
2870class MismatchingNewDeleteDetector {
2871public:
2872 enum MismatchResult {
2873 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2874 NoMismatch,
2875 /// Indicates that variable is initialized with mismatching form of \a new.
2876 VarInitMismatches,
2877 /// Indicates that member is initialized with mismatching form of \a new.
2878 MemberInitMismatches,
2879 /// Indicates that 1 or more constructors' definitions could not been
2880 /// analyzed, and they will be checked again at the end of translation unit.
2881 AnalyzeLater
2882 };
2883
2884 /// \param EndOfTU True, if this is the final analysis at the end of
2885 /// translation unit. False, if this is the initial analysis at the point
2886 /// delete-expression was encountered.
2887 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2888 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2889 HasUndefinedConstructors(false) {}
2890
2891 /// \brief Checks whether pointee of a delete-expression is initialized with
2892 /// matching form of new-expression.
2893 ///
2894 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2895 /// point where delete-expression is encountered, then a warning will be
2896 /// issued immediately. If return value is \c AnalyzeLater at the point where
2897 /// delete-expression is seen, then member will be analyzed at the end of
2898 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2899 /// couldn't be analyzed. If at least one constructor initializes the member
2900 /// with matching type of new, the return value is \c NoMismatch.
2901 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2902 /// \brief Analyzes a class member.
2903 /// \param Field Class member to analyze.
2904 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2905 /// for deleting the \p Field.
2906 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2907 FieldDecl *Field;
2908 /// List of mismatching new-expressions used for initialization of the pointee
2909 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2910 /// Indicates whether delete-expression was in array form.
2911 bool IsArrayForm;
2912
2913private:
2914 const bool EndOfTU;
2915 /// \brief Indicates that there is at least one constructor without body.
2916 bool HasUndefinedConstructors;
2917 /// \brief Returns \c CXXNewExpr from given initialization expression.
2918 /// \param E Expression used for initializing pointee in delete-expression.
2919 /// E can be a single-element \c InitListExpr consisting of new-expression.
2920 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2921 /// \brief Returns whether member is initialized with mismatching form of
2922 /// \c new either by the member initializer or in-class initialization.
2923 ///
2924 /// If bodies of all constructors are not visible at the end of translation
2925 /// unit or at least one constructor initializes member with the matching
2926 /// form of \c new, mismatch cannot be proven, and this function will return
2927 /// \c NoMismatch.
2928 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2929 /// \brief Returns whether variable is initialized with mismatching form of
2930 /// \c new.
2931 ///
2932 /// If variable is initialized with matching form of \c new or variable is not
2933 /// initialized with a \c new expression, this function will return true.
2934 /// If variable is initialized with mismatching form of \c new, returns false.
2935 /// \param D Variable to analyze.
2936 bool hasMatchingVarInit(const DeclRefExpr *D);
2937 /// \brief Checks whether the constructor initializes pointee with mismatching
2938 /// form of \c new.
2939 ///
2940 /// Returns true, if member is initialized with matching form of \c new in
2941 /// member initializer list. Returns false, if member is initialized with the
2942 /// matching form of \c new in this constructor's initializer or given
2943 /// constructor isn't defined at the point where delete-expression is seen, or
2944 /// member isn't initialized by the constructor.
2945 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2946 /// \brief Checks whether member is initialized with matching form of
2947 /// \c new in member initializer list.
2948 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2949 /// Checks whether member is initialized with mismatching form of \c new by
2950 /// in-class initializer.
2951 MismatchResult analyzeInClassInitializer();
2952};
2953}
2954
2955MismatchingNewDeleteDetector::MismatchResult
2956MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2957 NewExprs.clear();
2958 assert(DE && "Expected delete-expression")(static_cast <bool> (DE && "Expected delete-expression"
) ? void (0) : __assert_fail ("DE && \"Expected delete-expression\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2958, __extension__ __PRETTY_FUNCTION__))
;
2959 IsArrayForm = DE->isArrayForm();
2960 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2961 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2962 return analyzeMemberExpr(ME);
2963 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2964 if (!hasMatchingVarInit(D))
2965 return VarInitMismatches;
2966 }
2967 return NoMismatch;
2968}
2969
2970const CXXNewExpr *
2971MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2972 assert(E != nullptr && "Expected a valid initializer expression")(static_cast <bool> (E != nullptr && "Expected a valid initializer expression"
) ? void (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2972, __extension__ __PRETTY_FUNCTION__))
;
2973 E = E->IgnoreParenImpCasts();
2974 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2975 if (ILE->getNumInits() == 1)
2976 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2977 }
2978
2979 return dyn_cast_or_null<const CXXNewExpr>(E);
2980}
2981
2982bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2983 const CXXCtorInitializer *CI) {
2984 const CXXNewExpr *NE = nullptr;
2985 if (Field == CI->getMember() &&
2986 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2987 if (NE->isArray() == IsArrayForm)
2988 return true;
2989 else
2990 NewExprs.push_back(NE);
2991 }
2992 return false;
2993}
2994
2995bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2996 const CXXConstructorDecl *CD) {
2997 if (CD->isImplicit())
2998 return false;
2999 const FunctionDecl *Definition = CD;
3000 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3001 HasUndefinedConstructors = true;
3002 return EndOfTU;
3003 }
3004 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3005 if (hasMatchingNewInCtorInit(CI))
3006 return true;
3007 }
3008 return false;
3009}
3010
3011MismatchingNewDeleteDetector::MismatchResult
3012MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3013 assert(Field != nullptr && "This should be called only for members")(static_cast <bool> (Field != nullptr && "This should be called only for members"
) ? void (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3013, __extension__ __PRETTY_FUNCTION__))
;
3014 const Expr *InitExpr = Field->getInClassInitializer();
3015 if (!InitExpr)
3016 return EndOfTU ? NoMismatch : AnalyzeLater;
3017 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3018 if (NE->isArray() != IsArrayForm) {
3019 NewExprs.push_back(NE);
3020 return MemberInitMismatches;
3021 }
3022 }
3023 return NoMismatch;
3024}
3025
3026MismatchingNewDeleteDetector::MismatchResult
3027MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3028 bool DeleteWasArrayForm) {
3029 assert(Field != nullptr && "Analysis requires a valid class member.")(static_cast <bool> (Field != nullptr && "Analysis requires a valid class member."
) ? void (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3029, __extension__ __PRETTY_FUNCTION__))
;
3030 this->Field = Field;
3031 IsArrayForm = DeleteWasArrayForm;
3032 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3033 for (const auto *CD : RD->ctors()) {
3034 if (hasMatchingNewInCtor(CD))
3035 return NoMismatch;
3036 }
3037 if (HasUndefinedConstructors)
3038 return EndOfTU ? NoMismatch : AnalyzeLater;
3039 if (!NewExprs.empty())
3040 return MemberInitMismatches;
3041 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3042 : NoMismatch;
3043}
3044
3045MismatchingNewDeleteDetector::MismatchResult
3046MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3047 assert(ME != nullptr && "Expected a member expression")(static_cast <bool> (ME != nullptr && "Expected a member expression"
) ? void (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3047, __extension__ __PRETTY_FUNCTION__))
;
3048 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3049 return analyzeField(F, IsArrayForm);
3050 return NoMismatch;
3051}
3052
3053bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3054 const CXXNewExpr *NE = nullptr;
3055 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3056 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3057 NE->isArray() != IsArrayForm) {
3058 NewExprs.push_back(NE);
3059 }
3060 }
3061 return NewExprs.empty();
3062}
3063
3064static void
3065DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3066 const MismatchingNewDeleteDetector &Detector) {
3067 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3068 FixItHint H;
3069 if (!Detector.IsArrayForm)
3070 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3071 else {
3072 SourceLocation RSquare = Lexer::findLocationAfterToken(
3073 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3074 SemaRef.getLangOpts(), true);
3075 if (RSquare.isValid())
3076 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3077 }
3078 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3079 << Detector.IsArrayForm << H;
3080
3081 for (const auto *NE : Detector.NewExprs)
3082 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3083 << Detector.IsArrayForm;
3084}
3085
3086void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3087 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3088 return;
3089 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3090 switch (Detector.analyzeDeleteExpr(DE)) {
3091 case MismatchingNewDeleteDetector::VarInitMismatches:
3092 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3093 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3094 break;
3095 }
3096 case MismatchingNewDeleteDetector::AnalyzeLater: {
3097 DeleteExprs[Detector.Field].push_back(
3098 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3099 break;
3100 }
3101 case MismatchingNewDeleteDetector::NoMismatch:
3102 break;
3103 }
3104}
3105
3106void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3107 bool DeleteWasArrayForm) {
3108 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3109 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3110 case MismatchingNewDeleteDetector::VarInitMismatches:
3111 llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members."
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3111)
;
3112 case MismatchingNewDeleteDetector::AnalyzeLater:
3113 llvm_unreachable("Analysis cannot be postponed any point beyond end of "::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3114)
3114 "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3114)
;
3115 case MismatchingNewDeleteDetector::MemberInitMismatches:
3116 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3117 break;
3118 case MismatchingNewDeleteDetector::NoMismatch:
3119 break;
3120 }
3121}
3122
3123/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3124/// @code ::delete ptr; @endcode
3125/// or
3126/// @code delete [] ptr; @endcode
3127ExprResult
3128Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3129 bool ArrayForm, Expr *ExE) {
3130 // C++ [expr.delete]p1:
3131 // The operand shall have a pointer type, or a class type having a single
3132 // non-explicit conversion function to a pointer type. The result has type
3133 // void.
3134 //
3135 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3136
3137 ExprResult Ex = ExE;
3138 FunctionDecl *OperatorDelete = nullptr;
3139 bool ArrayFormAsWritten = ArrayForm;
3140 bool UsualArrayDeleteWantsSize = false;
3141
3142 if (!Ex.get()->isTypeDependent()) {
3143 // Perform lvalue-to-rvalue cast, if needed.
3144 Ex = DefaultLvalueConversion(Ex.get());
3145 if (Ex.isInvalid())
3146 return ExprError();
3147
3148 QualType Type = Ex.get()->getType();
3149
3150 class DeleteConverter : public ContextualImplicitConverter {
3151 public:
3152 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3153
3154 bool match(QualType ConvType) override {
3155 // FIXME: If we have an operator T* and an operator void*, we must pick
3156 // the operator T*.
3157 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3158 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3159 return true;
3160 return false;
3161 }
3162
3163 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3164 QualType T) override {
3165 return S.Diag(Loc, diag::err_delete_operand) << T;
3166 }
3167
3168 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3169 QualType T) override {
3170 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3171 }
3172
3173 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3174 QualType T,
3175 QualType ConvTy) override {
3176 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3177 }
3178
3179 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3180 QualType ConvTy) override {
3181 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3182 << ConvTy;
3183 }
3184
3185 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3186 QualType T) override {
3187 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3188 }
3189
3190 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3191 QualType ConvTy) override {
3192 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3193 << ConvTy;
3194 }
3195
3196 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3197 QualType T,
3198 QualType ConvTy) override {
3199 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3199)
;
3200 }
3201 } Converter;
3202
3203 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3204 if (Ex.isInvalid())
3205 return ExprError();
3206 Type = Ex.get()->getType();
3207 if (!Converter.match(Type))
3208 // FIXME: PerformContextualImplicitConversion should return ExprError
3209 // itself in this case.
3210 return ExprError();
3211
3212 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3213 QualType PointeeElem = Context.getBaseElementType(Pointee);
3214
3215 if (Pointee.getAddressSpace() != LangAS::Default)
3216 return Diag(Ex.get()->getLocStart(),
3217 diag::err_address_space_qualified_delete)
3218 << Pointee.getUnqualifiedType()
3219 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3220
3221 CXXRecordDecl *PointeeRD = nullptr;
3222 if (Pointee->isVoidType() && !isSFINAEContext()) {
3223 // The C++ standard bans deleting a pointer to a non-object type, which
3224 // effectively bans deletion of "void*". However, most compilers support
3225 // this, so we treat it as a warning unless we're in a SFINAE context.
3226 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3227 << Type << Ex.get()->getSourceRange();
3228 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3229 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3230 << Type << Ex.get()->getSourceRange());
3231 } else if (!Pointee->isDependentType()) {
3232 // FIXME: This can result in errors if the definition was imported from a
3233 // module but is hidden.
3234 if (!RequireCompleteType(StartLoc, Pointee,
3235 diag::warn_delete_incomplete, Ex.get())) {
3236 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3237 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3238 }
3239 }
3240
3241 if (Pointee->isArrayType() && !ArrayForm) {
3242 Diag(StartLoc, diag::warn_delete_array_type)
3243 << Type << Ex.get()->getSourceRange()
3244 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3245 ArrayForm = true;
3246 }
3247
3248 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3249 ArrayForm ? OO_Array_Delete : OO_Delete);
3250
3251 if (PointeeRD) {
3252 if (!UseGlobal &&
3253 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3254 OperatorDelete))
3255 return ExprError();
3256
3257 // If we're allocating an array of records, check whether the
3258 // usual operator delete[] has a size_t parameter.
3259 if (ArrayForm) {
3260 // If the user specifically asked to use the global allocator,
3261 // we'll need to do the lookup into the class.
3262 if (UseGlobal)
3263 UsualArrayDeleteWantsSize =
3264 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3265
3266 // Otherwise, the usual operator delete[] should be the
3267 // function we just found.
3268 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3269 UsualArrayDeleteWantsSize =
3270 UsualDeallocFnInfo(*this,
3271 DeclAccessPair::make(OperatorDelete, AS_public))
3272 .HasSizeT;
3273 }
3274
3275 if (!PointeeRD->hasIrrelevantDestructor())
3276 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3277 MarkFunctionReferenced(StartLoc,
3278 const_cast<CXXDestructorDecl*>(Dtor));
3279 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3280 return ExprError();
3281 }
3282
3283 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3284 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3285 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3286 SourceLocation());
3287 }
3288
3289 if (!OperatorDelete) {
3290 bool IsComplete = isCompleteType(StartLoc, Pointee);
3291 bool CanProvideSize =
3292 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3293 Pointee.isDestructedType());
3294 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3295
3296 // Look for a global declaration.
3297 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3298 Overaligned, DeleteName);
3299 }
3300
3301 MarkFunctionReferenced(StartLoc, OperatorDelete);
3302
3303 // Check access and ambiguity of destructor if we're going to call it.
3304 // Note that this is required even for a virtual delete.
3305 bool IsVirtualDelete = false;
3306 if (PointeeRD) {
3307 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3308 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3309 PDiag(diag::err_access_dtor) << PointeeElem);
3310 IsVirtualDelete = Dtor->isVirtual();
3311 }
3312 }
3313
3314 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3315 *this);
3316
3317 // Convert the operand to the type of the first parameter of operator
3318 // delete. This is only necessary if we selected a destroying operator
3319 // delete that we are going to call (non-virtually); converting to void*
3320 // is trivial and left to AST consumers to handle.
3321 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3322 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3323 Qualifiers Qs = Pointee.getQualifiers();
3324 if (Qs.hasCVRQualifiers()) {
3325 // Qualifiers are irrelevant to this conversion; we're only looking
3326 // for access and ambiguity.
3327 Qs.removeCVRQualifiers();
3328 QualType Unqual = Context.getPointerType(
3329 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3330 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3331 }
3332 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3333 if (Ex.isInvalid())
3334 return ExprError();
3335 }
3336 }
3337
3338 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3339 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3340 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3341 AnalyzeDeleteExprMismatch(Result);
3342 return Result;
3343}
3344
3345void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3346 bool IsDelete, bool CallCanBeVirtual,
3347 bool WarnOnNonAbstractTypes,
3348 SourceLocation DtorLoc) {
3349 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3350 return;
3351
3352 // C++ [expr.delete]p3:
3353 // In the first alternative (delete object), if the static type of the
3354 // object to be deleted is different from its dynamic type, the static
3355 // type shall be a base class of the dynamic type of the object to be
3356 // deleted and the static type shall have a virtual destructor or the
3357 // behavior is undefined.
3358 //
3359 const CXXRecordDecl *PointeeRD = dtor->getParent();
3360 // Note: a final class cannot be derived from, no issue there
3361 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3362 return;
3363
3364 // If the superclass is in a system header, there's nothing that can be done.
3365 // The `delete` (where we emit the warning) can be in a system header,
3366 // what matters for this warning is where the deleted type is defined.
3367 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3368 return;
3369
3370 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3371 if (PointeeRD->isAbstract()) {
3372 // If the class is abstract, we warn by default, because we're
3373 // sure the code has undefined behavior.
3374 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3375 << ClassType;
3376 } else if (WarnOnNonAbstractTypes) {
3377 // Otherwise, if this is not an array delete, it's a bit suspect,
3378 // but not necessarily wrong.
3379 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3380 << ClassType;
3381 }
3382 if (!IsDelete) {
3383 std::string TypeStr;
3384 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3385 Diag(DtorLoc, diag::note_delete_non_virtual)
3386 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3387 }
3388}
3389
3390Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3391 SourceLocation StmtLoc,
3392 ConditionKind CK) {
3393 ExprResult E =
3394 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3395 if (E.isInvalid())
3396 return ConditionError();
3397 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3398 CK == ConditionKind::ConstexprIf);
3399}
3400
3401/// \brief Check the use of the given variable as a C++ condition in an if,
3402/// while, do-while, or switch statement.
3403ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3404 SourceLocation StmtLoc,
3405 ConditionKind CK) {
3406 if (ConditionVar->isInvalidDecl())
3407 return ExprError();
3408
3409 QualType T = ConditionVar->getType();
3410
3411 // C++ [stmt.select]p2:
3412 // The declarator shall not specify a function or an array.
3413 if (T->isFunctionType())
3414 return ExprError(Diag(ConditionVar->getLocation(),
3415 diag::err_invalid_use_of_function_type)
3416 << ConditionVar->getSourceRange());
3417 else if (T->isArrayType())
3418 return ExprError(Diag(ConditionVar->getLocation(),
3419 diag::err_invalid_use_of_array_type)
3420 << ConditionVar->getSourceRange());
3421
3422 ExprResult Condition = DeclRefExpr::Create(
3423 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3424 /*enclosing*/ false, ConditionVar->getLocation(),
3425 ConditionVar->getType().getNonReferenceType(), VK_LValue);
3426
3427 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3428
3429 switch (CK) {
3430 case ConditionKind::Boolean:
3431 return CheckBooleanCondition(StmtLoc, Condition.get());
3432
3433 case ConditionKind::ConstexprIf:
3434 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3435
3436 case ConditionKind::Switch:
3437 return CheckSwitchCondition(StmtLoc, Condition.get());
3438 }
3439
3440 llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3440)
;
3441}
3442
3443/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3444ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3445 // C++ 6.4p4:
3446 // The value of a condition that is an initialized declaration in a statement
3447 // other than a switch statement is the value of the declared variable
3448 // implicitly converted to type bool. If that conversion is ill-formed, the
3449 // program is ill-formed.
3450 // The value of a condition that is an expression is the value of the
3451 // expression, implicitly converted to bool.
3452 //
3453 // FIXME: Return this value to the caller so they don't need to recompute it.
3454 llvm::APSInt Value(/*BitWidth*/1);
3455 return (IsConstexpr && !CondExpr->isValueDependent())
3456 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3457 CCEK_ConstexprIf)
3458 : PerformContextuallyConvertToBool(CondExpr);
3459}
3460
3461/// Helper function to determine whether this is the (deprecated) C++
3462/// conversion from a string literal to a pointer to non-const char or
3463/// non-const wchar_t (for narrow and wide string literals,
3464/// respectively).
3465bool
3466Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3467 // Look inside the implicit cast, if it exists.
3468 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3469 From = Cast->getSubExpr();
3470
3471 // A string literal (2.13.4) that is not a wide string literal can
3472 // be converted to an rvalue of type "pointer to char"; a wide
3473 // string literal can be converted to an rvalue of type "pointer
3474 // to wchar_t" (C++ 4.2p2).
3475 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3476 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3477 if (const BuiltinType *ToPointeeType
3478 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3479 // This conversion is considered only when there is an
3480 // explicit appropriate pointer target type (C++ 4.2p2).
3481 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3482 switch (StrLit->getKind()) {
3483 case StringLiteral::UTF8:
3484 case StringLiteral::UTF16:
3485 case StringLiteral::UTF32:
3486 // We don't allow UTF literals to be implicitly converted
3487 break;
3488 case StringLiteral::Ascii:
3489 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3490 ToPointeeType->getKind() == BuiltinType::Char_S);
3491 case StringLiteral::Wide:
3492 return Context.typesAreCompatible(Context.getWideCharType(),
3493 QualType(ToPointeeType, 0));
3494 }
3495 }
3496 }
3497
3498 return false;
3499}
3500
3501static ExprResult BuildCXXCastArgument(Sema &S,
3502 SourceLocation CastLoc,
3503 QualType Ty,
3504 CastKind Kind,
3505 CXXMethodDecl *Method,
3506 DeclAccessPair FoundDecl,
3507 bool HadMultipleCandidates,
3508 Expr *From) {
3509 switch (Kind) {
3510 default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3510)
;
3511 case CK_ConstructorConversion: {
3512 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3513 SmallVector<Expr*, 8> ConstructorArgs;
3514
3515 if (S.RequireNonAbstractType(CastLoc, Ty,
3516 diag::err_allocation_of_abstract_type))
3517 return ExprError();
3518
3519 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3520 return ExprError();
3521
3522 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3523 InitializedEntity::InitializeTemporary(Ty));
3524 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3525 return ExprError();
3526
3527 ExprResult Result = S.BuildCXXConstructExpr(
3528 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3529 ConstructorArgs, HadMultipleCandidates,
3530 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3531 CXXConstructExpr::CK_Complete, SourceRange());
3532 if (Result.isInvalid())
3533 return ExprError();
3534
3535 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3536 }
3537
3538 case CK_UserDefinedConversion: {
3539 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")(static_cast <bool> (!From->getType()->isPointerType
() && "Arg can't have pointer type!") ? void (0) : __assert_fail
("!From->getType()->isPointerType() && \"Arg can't have pointer type!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3539, __extension__ __PRETTY_FUNCTION__))
;
3540
3541 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3542 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3543 return ExprError();
3544
3545 // Create an implicit call expr that calls it.
3546 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3547 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3548 HadMultipleCandidates);
3549 if (Result.isInvalid())
3550 return ExprError();
3551 // Record usage of conversion in an implicit cast.
3552 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3553 CK_UserDefinedConversion, Result.get(),
3554 nullptr, Result.get()->getValueKind());
3555
3556 return S.MaybeBindToTemporary(Result.get());
3557 }
3558 }
3559}
3560
3561/// PerformImplicitConversion - Perform an implicit conversion of the
3562/// expression From to the type ToType using the pre-computed implicit
3563/// conversion sequence ICS. Returns the converted
3564/// expression. Action is the kind of conversion we're performing,
3565/// used in the error message.
3566ExprResult
3567Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3568 const ImplicitConversionSequence &ICS,
3569 AssignmentAction Action,
3570 CheckedConversionKind CCK) {
3571 switch (ICS.getKind()) {
3572 case ImplicitConversionSequence::StandardConversion: {
3573 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3574 Action, CCK);
3575 if (Res.isInvalid())
3576 return ExprError();
3577 From = Res.get();
3578 break;
3579 }
3580
3581 case ImplicitConversionSequence::UserDefinedConversion: {
3582
3583 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3584 CastKind CastKind;
3585 QualType BeforeToType;
3586 assert(FD && "no conversion function for user-defined conversion seq")(static_cast <bool> (FD && "no conversion function for user-defined conversion seq"
) ? void (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3586, __extension__ __PRETTY_FUNCTION__))
;
3587 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3588 CastKind = CK_UserDefinedConversion;
3589
3590 // If the user-defined conversion is specified by a conversion function,
3591 // the initial standard conversion sequence converts the source type to
3592 // the implicit object parameter of the conversion function.
3593 BeforeToType = Context.getTagDeclType(Conv->getParent());
3594 } else {
3595 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3596 CastKind = CK_ConstructorConversion;
3597 // Do no conversion if dealing with ... for the first conversion.
3598 if (!ICS.UserDefined.EllipsisConversion) {
3599 // If the user-defined conversion is specified by a constructor, the
3600 // initial standard conversion sequence converts the source type to
3601 // the type required by the argument of the constructor
3602 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3603 }
3604 }
3605 // Watch out for ellipsis conversion.
3606 if (!ICS.UserDefined.EllipsisConversion) {
3607 ExprResult Res =
3608 PerformImplicitConversion(From, BeforeToType,
3609 ICS.UserDefined.Before, AA_Converting,
3610 CCK);
3611 if (Res.isInvalid())
3612 return ExprError();
3613 From = Res.get();
3614 }
3615
3616 ExprResult CastArg
3617 = BuildCXXCastArgument(*this,
3618 From->getLocStart(),
3619 ToType.getNonReferenceType(),
3620 CastKind, cast<CXXMethodDecl>(FD),
3621 ICS.UserDefined.FoundConversionFunction,
3622 ICS.UserDefined.HadMultipleCandidates,
3623 From);
3624
3625 if (CastArg.isInvalid())
3626 return ExprError();
3627
3628 From = CastArg.get();
3629
3630 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3631 AA_Converting, CCK);
3632 }
3633
3634 case ImplicitConversionSequence::AmbiguousConversion:
3635 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3636 PDiag(diag::err_typecheck_ambiguous_condition)
3637 << From->getSourceRange());
3638 return ExprError();
3639
3640 case ImplicitConversionSequence::EllipsisConversion:
3641 llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3641)
;
3642
3643 case ImplicitConversionSequence::BadConversion:
3644 bool Diagnosed =
3645 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3646 From->getType(), From, Action);
3647 assert(Diagnosed && "failed to diagnose bad conversion")(static_cast <bool> (Diagnosed && "failed to diagnose bad conversion"
) ? void (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3647, __extension__ __PRETTY_FUNCTION__))
; (void)Diagnosed;
3648 return ExprError();
3649 }
3650
3651 // Everything went well.
3652 return From;
3653}
3654
3655/// PerformImplicitConversion - Perform an implicit conversion of the
3656/// expression From to the type ToType by following the standard
3657/// conversion sequence SCS. Returns the converted
3658/// expression. Flavor is the context in which we're performing this
3659/// conversion, for use in error messages.
3660ExprResult
3661Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3662 const StandardConversionSequence& SCS,
3663 AssignmentAction Action,
3664 CheckedConversionKind CCK) {
3665 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3666
3667 // Overall FIXME: we are recomputing too many types here and doing far too
3668 // much extra work. What this means is that we need to keep track of more
3669 // information that is computed when we try the implicit conversion initially,
3670 // so that we don't need to recompute anything here.
3671 QualType FromType = From->getType();
3672
3673 if (SCS.CopyConstructor) {
3674 // FIXME: When can ToType be a reference type?
3675 assert(!ToType->isReferenceType())(static_cast <bool> (!ToType->isReferenceType()) ? void
(0) : __assert_fail ("!ToType->isReferenceType()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3675, __extension__ __PRETTY_FUNCTION__))
;
3676 if (SCS.Second == ICK_Derived_To_Base) {
3677 SmallVector<Expr*, 8> ConstructorArgs;
3678 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3679 From, /*FIXME:ConstructLoc*/SourceLocation(),
3680 ConstructorArgs))
3681 return ExprError();
3682 return BuildCXXConstructExpr(
3683 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3684 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3685 ConstructorArgs, /*HadMultipleCandidates*/ false,
3686 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3687 CXXConstructExpr::CK_Complete, SourceRange());
3688 }
3689 return BuildCXXConstructExpr(
3690 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3691 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3692 From, /*HadMultipleCandidates*/ false,
3693 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3694 CXXConstructExpr::CK_Complete, SourceRange());
3695 }
3696
3697 // Resolve overloaded function references.
3698 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3699 DeclAccessPair Found;
3700 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3701 true, Found);
3702 if (!Fn)
3703 return ExprError();
3704
3705 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
3706 return ExprError();
3707
3708 From = FixOverloadedFunctionReference(From, Found, Fn);
3709 FromType = From->getType();
3710 }
3711
3712 // If we're converting to an atomic type, first convert to the corresponding
3713 // non-atomic type.
3714 QualType ToAtomicType;
3715 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3716 ToAtomicType = ToType;
3717 ToType = ToAtomic->getValueType();
3718 }
3719
3720 QualType InitialFromType = FromType;
3721 // Perform the first implicit conversion.
3722 switch (SCS.First) {
3723 case ICK_Identity:
3724 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3725 FromType = FromAtomic->getValueType().getUnqualifiedType();
3726 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3727 From, /*BasePath=*/nullptr, VK_RValue);
3728 }
3729 break;
3730
3731 case ICK_Lvalue_To_Rvalue: {
3732 assert(From->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (From->getObjectKind() != OK_ObjCProperty
) ? void (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3732, __extension__ __PRETTY_FUNCTION__))
;
3733 ExprResult FromRes = DefaultLvalueConversion(From);
3734 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!")(static_cast <bool> (!FromRes.isInvalid() && "Can't perform deduced conversion?!"
) ? void (0) : __assert_fail ("!FromRes.isInvalid() && \"Can't perform deduced conversion?!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3734, __extension__ __PRETTY_FUNCTION__))
;
3735 From = FromRes.get();
3736 FromType = From->getType();
3737 break;
3738 }
3739
3740 case ICK_Array_To_Pointer:
3741 FromType = Context.getArrayDecayedType(FromType);
3742 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3743 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3744 break;
3745
3746 case ICK_Function_To_Pointer:
3747 FromType = Context.getPointerType(FromType);
3748 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3749 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3750 break;
3751
3752 default:
3753 llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3753)
;
3754 }
3755
3756 // Perform the second implicit conversion
3757 switch (SCS.Second) {
3758 case ICK_Identity:
3759 // C++ [except.spec]p5:
3760 // [For] assignment to and initialization of pointers to functions,
3761 // pointers to member functions, and references to functions: the
3762 // target entity shall allow at least the exceptions allowed by the
3763 // source value in the assignment or initialization.
3764 switch (Action) {
3765 case AA_Assigning:
3766 case AA_Initializing:
3767 // Note, function argument passing and returning are initialization.
3768 case AA_Passing:
3769 case AA_Returning:
3770 case AA_Sending:
3771 case AA_Passing_CFAudited:
3772 if (CheckExceptionSpecCompatibility(From, ToType))
3773 return ExprError();
3774 break;
3775
3776 case AA_Casting:
3777 case AA_Converting:
3778 // Casts and implicit conversions are not initialization, so are not
3779 // checked for exception specification mismatches.
3780 break;
3781 }
3782 // Nothing else to do.
3783 break;
3784
3785 case ICK_Integral_Promotion:
3786 case ICK_Integral_Conversion:
3787 if (ToType->isBooleanType()) {
3788 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3790, __extension__ __PRETTY_FUNCTION__))
3789 SCS.Second == ICK_Integral_Promotion &&(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3790, __extension__ __PRETTY_FUNCTION__))
3790 "only enums with fixed underlying type can promote to bool")(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3790, __extension__ __PRETTY_FUNCTION__))
;
3791 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
3792 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3793 } else {
3794 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
3795 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3796 }
3797 break;
3798
3799 case ICK_Floating_Promotion:
3800 case ICK_Floating_Conversion:
3801 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
3802 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3803 break;
3804
3805 case ICK_Complex_Promotion:
3806 case ICK_Complex_Conversion: {
3807 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3808 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3809 CastKind CK;
3810 if (FromEl->isRealFloatingType()) {
3811 if (ToEl->isRealFloatingType())
3812 CK = CK_FloatingComplexCast;
3813 else
3814 CK = CK_FloatingComplexToIntegralComplex;
3815 } else if (ToEl->isRealFloatingType()) {
3816 CK = CK_IntegralComplexToFloatingComplex;
3817 } else {
3818 CK = CK_IntegralComplexCast;
3819 }
3820 From = ImpCastExprToType(From, ToType, CK,
3821 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3822 break;
3823 }
3824
3825 case ICK_Floating_Integral:
3826 if (ToType->isRealFloatingType())
3827 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
3828 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3829 else
3830 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
3831 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3832 break;
3833
3834 case ICK_Compatible_Conversion:
3835 From = ImpCastExprToType(From, ToType, CK_NoOp,
3836 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3837 break;
3838
3839 case ICK_Writeback_Conversion:
3840 case ICK_Pointer_Conversion: {
3841 if (SCS.IncompatibleObjC && Action != AA_Casting) {
3842 // Diagnose incompatible Objective-C conversions
3843 if (Action == AA_Initializing || Action == AA_Assigning)
3844 Diag(From->getLocStart(),
3845 diag::ext_typecheck_convert_incompatible_pointer)
3846 << ToType << From->getType() << Action
3847 << From->getSourceRange() << 0;
3848 else
3849 Diag(From->getLocStart(),
3850 diag::ext_typecheck_convert_incompatible_pointer)
3851 << From->getType() << ToType << Action
3852 << From->getSourceRange() << 0;
3853
3854 if (From->getType()->isObjCObjectPointerType() &&
3855 ToType->isObjCObjectPointerType())
3856 EmitRelatedResultTypeNote(From);
3857 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3858 !CheckObjCARCUnavailableWeakConversion(ToType,
3859 From->getType())) {
3860 if (Action == AA_Initializing)
3861 Diag(From->getLocStart(),
3862 diag::err_arc_weak_unavailable_assign);
3863 else
3864 Diag(From->getLocStart(),
3865 diag::err_arc_convesion_of_weak_unavailable)
3866 << (Action == AA_Casting) << From->getType() << ToType
3867 << From->getSourceRange();
3868 }
3869
3870 CastKind Kind;
3871 CXXCastPath BasePath;
3872 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
3873 return ExprError();
3874
3875 // Make sure we extend blocks if necessary.
3876 // FIXME: doing this here is really ugly.
3877 if (Kind == CK_BlockPointerToObjCPointerCast) {
3878 ExprResult E = From;
3879 (void) PrepareCastToObjCObjectPointer(E);
3880 From = E.get();
3881 }
3882 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3883 CheckObjCConversion(SourceRange(), ToType, From, CCK);
3884 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3885 .get();
3886 break;
3887 }
3888
3889 case ICK_Pointer_Member: {
3890 CastKind Kind;
3891 CXXCastPath BasePath;
3892 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
3893 return ExprError();
3894 if (CheckExceptionSpecCompatibility(From, ToType))
3895 return ExprError();
3896
3897 // We may not have been able to figure out what this member pointer resolved
3898 // to up until this exact point. Attempt to lock-in it's inheritance model.
3899 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3900 (void)isCompleteType(From->getExprLoc(), From->getType());
3901 (void)isCompleteType(From->getExprLoc(), ToType);
3902 }
3903
3904 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3905 .get();
3906 break;
3907 }
3908
3909 case ICK_Boolean_Conversion:
3910 // Perform half-to-boolean conversion via float.
3911 if (From->getType()->isHalfType()) {
3912 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
3913 FromType = Context.FloatTy;
3914 }
3915
3916 From = ImpCastExprToType(From, Context.BoolTy,
3917 ScalarTypeToBooleanCastKind(FromType),
3918 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3919 break;
3920
3921 case ICK_Derived_To_Base: {
3922 CXXCastPath BasePath;
3923 if (CheckDerivedToBaseConversion(From->getType(),
3924 ToType.getNonReferenceType(),
3925 From->getLocStart(),
3926 From->getSourceRange(),
3927 &BasePath,
3928 CStyle))
3929 return ExprError();
3930
3931 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3932 CK_DerivedToBase, From->getValueKind(),
3933 &BasePath, CCK).get();
3934 break;
3935 }
3936
3937 case ICK_Vector_Conversion:
3938 From = ImpCastExprToType(From, ToType, CK_BitCast,
3939 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3940 break;
3941
3942 case ICK_Vector_Splat: {
3943 // Vector splat from any arithmetic type to a vector.
3944 Expr *Elem = prepareVectorSplat(ToType, From).get();
3945 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3946 /*BasePath=*/nullptr, CCK).get();
3947 break;
3948 }
3949
3950 case ICK_Complex_Real:
3951 // Case 1. x -> _Complex y
3952 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3953 QualType ElType = ToComplex->getElementType();
3954 bool isFloatingComplex = ElType->isRealFloatingType();
3955
3956 // x -> y
3957 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3958 // do nothing
3959 } else if (From->getType()->isRealFloatingType()) {
3960 From = ImpCastExprToType(From, ElType,
3961 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
3962 } else {
3963 assert(From->getType()->isIntegerType())(static_cast <bool> (From->getType()->isIntegerType
()) ? void (0) : __assert_fail ("From->getType()->isIntegerType()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3963, __extension__ __PRETTY_FUNCTION__))
;
3964 From = ImpCastExprToType(From, ElType,
3965 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
3966 }
3967 // y -> _Complex y
3968 From = ImpCastExprToType(From, ToType,
3969 isFloatingComplex ? CK_FloatingRealToComplex
3970 : CK_IntegralRealToComplex).get();
3971
3972 // Case 2. _Complex x -> y
3973 } else {
3974 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3975 assert(FromComplex)(static_cast <bool> (FromComplex) ? void (0) : __assert_fail
("FromComplex", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3975, __extension__ __PRETTY_FUNCTION__))
;
3976
3977 QualType ElType = FromComplex->getElementType();
3978 bool isFloatingComplex = ElType->isRealFloatingType();
3979
3980 // _Complex x -> x
3981 From = ImpCastExprToType(From, ElType,
3982 isFloatingComplex ? CK_FloatingComplexToReal
3983 : CK_IntegralComplexToReal,
3984 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3985
3986 // x -> y
3987 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3988 // do nothing
3989 } else if (ToType->isRealFloatingType()) {
3990 From = ImpCastExprToType(From, ToType,
3991 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
3992 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3993 } else {
3994 assert(ToType->isIntegerType())(static_cast <bool> (ToType->isIntegerType()) ? void
(0) : __assert_fail ("ToType->isIntegerType()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3994, __extension__ __PRETTY_FUNCTION__))
;
3995 From = ImpCastExprToType(From, ToType,
3996 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3997 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3998 }
3999 }
4000 break;
4001
4002 case ICK_Block_Pointer_Conversion: {
4003 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
4004 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4005 break;
4006 }
4007
4008 case ICK_TransparentUnionConversion: {
4009 ExprResult FromRes = From;
4010 Sema::AssignConvertType ConvTy =
4011 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4012 if (FromRes.isInvalid())
4013 return ExprError();
4014 From = FromRes.get();
4015 assert ((ConvTy == Sema::Compatible) &&(static_cast <bool> ((ConvTy == Sema::Compatible) &&
"Improper transparent union conversion") ? void (0) : __assert_fail
("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4016, __extension__ __PRETTY_FUNCTION__))
4016 "Improper transparent union conversion")(static_cast <bool> ((ConvTy == Sema::Compatible) &&
"Improper transparent union conversion") ? void (0) : __assert_fail
("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4016, __extension__ __PRETTY_FUNCTION__))
;
4017 (void)ConvTy;
4018 break;
4019 }
4020
4021 case ICK_Zero_Event_Conversion:
4022 From = ImpCastExprToType(From, ToType,
4023 CK_ZeroToOCLEvent,
4024 From->getValueKind()).get();
4025 break;
4026
4027 case ICK_Zero_Queue_Conversion:
4028 From = ImpCastExprToType(From, ToType,
4029 CK_ZeroToOCLQueue,
4030 From->getValueKind()).get();
4031 break;
4032
4033 case ICK_Lvalue_To_Rvalue:
4034 case ICK_Array_To_Pointer:
4035 case ICK_Function_To_Pointer:
4036 case ICK_Function_Conversion:
4037 case ICK_Qualification:
4038 case ICK_Num_Conversion_Kinds:
4039 case ICK_C_Only_Conversion:
4040 case ICK_Incompatible_Pointer_Conversion:
4041 llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4041)
;
4042 }
4043
4044 switch (SCS.Third) {
4045 case ICK_Identity:
4046 // Nothing to do.
4047 break;
4048
4049 case ICK_Function_Conversion:
4050 // If both sides are functions (or pointers/references to them), there could
4051 // be incompatible exception declarations.
4052 if (CheckExceptionSpecCompatibility(From, ToType))
4053 return ExprError();
4054
4055 From = ImpCastExprToType(From, ToType, CK_NoOp,
4056 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4057 break;
4058
4059 case ICK_Qualification: {
4060 // The qualification keeps the category of the inner expression, unless the
4061 // target type isn't a reference.
4062 ExprValueKind VK = ToType->isReferenceType() ?
4063 From->getValueKind() : VK_RValue;
4064 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
4065 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
4066
4067 if (SCS.DeprecatedStringLiteralToCharPtr &&
4068 !getLangOpts().WritableStrings) {
4069 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4070 ? diag::ext_deprecated_string_literal_conversion
4071 : diag::warn_deprecated_string_literal_conversion)
4072 << ToType.getNonReferenceType();
4073 }
4074
4075 break;
4076 }
4077
4078 default:
4079 llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4079)
;
4080 }
4081
4082 // If this conversion sequence involved a scalar -> atomic conversion, perform
4083 // that conversion now.
4084 if (!ToAtomicType.isNull()) {
4085 assert(Context.hasSameType((static_cast <bool> (Context.hasSameType( ToAtomicType->
castAs<AtomicType>()->getValueType(), From->getType
())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4086, __extension__ __PRETTY_FUNCTION__))
4086 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))(static_cast <bool> (Context.hasSameType( ToAtomicType->
castAs<AtomicType>()->getValueType(), From->getType
())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4086, __extension__ __PRETTY_FUNCTION__))
;
4087 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4088 VK_RValue, nullptr, CCK).get();
4089 }
4090
4091 // If this conversion sequence succeeded and involved implicitly converting a
4092 // _Nullable type to a _Nonnull one, complain.
4093 if (CCK == CCK_ImplicitConversion)
4094 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4095 From->getLocStart());
4096
4097 return From;
4098}
4099
4100/// \brief Check the completeness of a type in a unary type trait.
4101///
4102/// If the particular type trait requires a complete type, tries to complete
4103/// it. If completing the type fails, a diagnostic is emitted and false
4104/// returned. If completing the type succeeds or no completion was required,
4105/// returns true.
4106static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4107 SourceLocation Loc,
4108 QualType ArgTy) {
4109 // C++0x [meta.unary.prop]p3:
4110 // For all of the class templates X declared in this Clause, instantiating
4111 // that template with a template argument that is a class template
4112 // specialization may result in the implicit instantiation of the template
4113 // argument if and only if the semantics of X require that the argument
4114 // must be a complete type.
4115 // We apply this rule to all the type trait expressions used to implement
4116 // these class templates. We also try to follow any GCC documented behavior
4117 // in these expressions to ensure portability of standard libraries.
4118 switch (UTT) {
4119 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4119)
;
4120 // is_complete_type somewhat obviously cannot require a complete type.
4121 case UTT_IsCompleteType:
4122 // Fall-through
4123
4124 // These traits are modeled on the type predicates in C++0x
4125 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4126 // requiring a complete type, as whether or not they return true cannot be
4127 // impacted by the completeness of the type.
4128 case UTT_IsVoid:
4129 case UTT_IsIntegral:
4130 case UTT_IsFloatingPoint:
4131 case UTT_IsArray:
4132 case UTT_IsPointer:
4133 case UTT_IsLvalueReference:
4134 case UTT_IsRvalueReference:
4135 case UTT_IsMemberFunctionPointer:
4136 case UTT_IsMemberObjectPointer:
4137 case UTT_IsEnum:
4138 case UTT_IsUnion:
4139 case UTT_IsClass:
4140 case UTT_IsFunction:
4141 case UTT_IsReference:
4142 case UTT_IsArithmetic:
4143 case UTT_IsFundamental:
4144 case UTT_IsObject:
4145 case UTT_IsScalar:
4146 case UTT_IsCompound:
4147 case UTT_IsMemberPointer:
4148 // Fall-through
4149
4150 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4151 // which requires some of its traits to have the complete type. However,
4152 // the completeness of the type cannot impact these traits' semantics, and
4153 // so they don't require it. This matches the comments on these traits in
4154 // Table 49.
4155 case UTT_IsConst:
4156 case UTT_IsVolatile:
4157 case UTT_IsSigned:
4158 case UTT_IsUnsigned:
4159
4160 // This type trait always returns false, checking the type is moot.
4161 case UTT_IsInterfaceClass:
4162 return true;
4163
4164 // C++14 [meta.unary.prop]:
4165 // If T is a non-union class type, T shall be a complete type.
4166 case UTT_IsEmpty:
4167 case UTT_IsPolymorphic:
4168 case UTT_IsAbstract:
4169 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4170 if (!RD->isUnion())
4171 return !S.RequireCompleteType(
4172 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4173 return true;
4174
4175 // C++14 [meta.unary.prop]:
4176 // If T is a class type, T shall be a complete type.
4177 case UTT_IsFinal:
4178 case UTT_IsSealed:
4179 if (ArgTy->getAsCXXRecordDecl())
4180 return !S.RequireCompleteType(
4181 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4182 return true;
4183
4184 // C++1z [meta.unary.prop]:
4185 // remove_all_extents_t<T> shall be a complete type or cv void.
4186 case UTT_IsAggregate:
4187 case UTT_IsTrivial:
4188 case UTT_IsTriviallyCopyable:
4189 case UTT_IsStandardLayout:
4190 case UTT_IsPOD:
4191 case UTT_IsLiteral:
4192 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4193 // or an array of unknown bound. But GCC actually imposes the same constraints
4194 // as above.
4195 case UTT_HasNothrowAssign:
4196 case UTT_HasNothrowMoveAssign:
4197 case UTT_HasNothrowConstructor:
4198 case UTT_HasNothrowCopy:
4199 case UTT_HasTrivialAssign:
4200 case UTT_HasTrivialMoveAssign:
4201 case UTT_HasTrivialDefaultConstructor:
4202 case UTT_HasTrivialMoveConstructor:
4203 case UTT_HasTrivialCopy:
4204 case UTT_HasTrivialDestructor:
4205 case UTT_HasVirtualDestructor:
4206 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4207 LLVM_FALLTHROUGH[[clang::fallthrough]];
4208
4209 // C++1z [meta.unary.prop]:
4210 // T shall be a complete type, cv void, or an array of unknown bound.
4211 case UTT_IsDestructible:
4212 case UTT_IsNothrowDestructible:
4213 case UTT_IsTriviallyDestructible:
4214 case UTT_HasUniqueObjectRepresentations:
4215 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4216 return true;
4217
4218 return !S.RequireCompleteType(
4219 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4220 }
4221}
4222
4223static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4224 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4225 bool (CXXRecordDecl::*HasTrivial)() const,
4226 bool (CXXRecordDecl::*HasNonTrivial)() const,
4227 bool (CXXMethodDecl::*IsDesiredOp)() const)
4228{
4229 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4230 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4231 return true;
4232
4233 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4234 DeclarationNameInfo NameInfo(Name, KeyLoc);
4235 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4236 if (Self.LookupQualifiedName(Res, RD)) {
4237 bool FoundOperator = false;
4238 Res.suppressDiagnostics();
4239 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4240 Op != OpEnd; ++Op) {
4241 if (isa<FunctionTemplateDecl>(*Op))
4242 continue;
4243
4244 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4245 if((Operator->*IsDesiredOp)()) {
4246 FoundOperator = true;
4247 const FunctionProtoType *CPT =
4248 Operator->getType()->getAs<FunctionProtoType>();
4249 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4250 if (!CPT || !CPT->isNothrow(C))
4251 return false;
4252 }
4253 }
4254 return FoundOperator;
4255 }
4256 return false;
4257}
4258
4259static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4260 SourceLocation KeyLoc, QualType T) {
4261 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() &&
"Cannot evaluate traits of dependent type") ? void (0) : __assert_fail
("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4261, __extension__ __PRETTY_FUNCTION__))
;
4262
4263 ASTContext &C = Self.Context;
4264 switch(UTT) {
4265 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4265)
;
4266 // Type trait expressions corresponding to the primary type category
4267 // predicates in C++0x [meta.unary.cat].
4268 case UTT_IsVoid:
4269 return T->isVoidType();
4270 case UTT_IsIntegral:
4271 return T->isIntegralType(C);
4272 case UTT_IsFloatingPoint:
4273 return T->isFloatingType();
4274 case UTT_IsArray:
4275 return T->isArrayType();
4276 case UTT_IsPointer:
4277 return T->isPointerType();
4278 case UTT_IsLvalueReference:
4279 return T->isLValueReferenceType();
4280 case UTT_IsRvalueReference:
4281 return T->isRValueReferenceType();
4282 case UTT_IsMemberFunctionPointer:
4283 return T->isMemberFunctionPointerType();
4284 case UTT_IsMemberObjectPointer:
4285 return T->isMemberDataPointerType();
4286 case UTT_IsEnum:
4287 return T->isEnumeralType();
4288 case UTT_IsUnion:
4289 return T->isUnionType();
4290 case UTT_IsClass:
4291 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4292 case UTT_IsFunction:
4293 return T->isFunctionType();
4294
4295 // Type trait expressions which correspond to the convenient composition
4296 // predicates in C++0x [meta.unary.comp].
4297 case UTT_IsReference:
4298 return T->isReferenceType();
4299 case UTT_IsArithmetic:
4300 return T->isArithmeticType() && !T->isEnumeralType();
4301 case UTT_IsFundamental:
4302 return T->isFundamentalType();
4303 case UTT_IsObject:
4304 return T->isObjectType();
4305 case UTT_IsScalar:
4306 // Note: semantic analysis depends on Objective-C lifetime types to be
4307 // considered scalar types. However, such types do not actually behave
4308 // like scalar types at run time (since they may require retain/release
4309 // operations), so we report them as non-scalar.
4310 if (T->isObjCLifetimeType()) {
4311 switch (T.getObjCLifetime()) {
4312 case Qualifiers::OCL_None:
4313 case Qualifiers::OCL_ExplicitNone:
4314 return true;
4315
4316 case Qualifiers::OCL_Strong:
4317 case Qualifiers::OCL_Weak:
4318 case Qualifiers::OCL_Autoreleasing:
4319 return false;
4320 }
4321 }
4322
4323 return T->isScalarType();
4324 case UTT_IsCompound:
4325 return T->isCompoundType();
4326 case UTT_IsMemberPointer:
4327 return T->isMemberPointerType();
4328
4329 // Type trait expressions which correspond to the type property predicates
4330 // in C++0x [meta.unary.prop].
4331 case UTT_IsConst:
4332 return T.isConstQualified();
4333 case UTT_IsVolatile:
4334 return T.isVolatileQualified();
4335 case UTT_IsTrivial:
4336 return T.isTrivialType(C);
4337 case UTT_IsTriviallyCopyable:
4338 return T.isTriviallyCopyableType(C);
4339 case UTT_IsStandardLayout:
4340 return T->isStandardLayoutType();
4341 case UTT_IsPOD:
4342 return T.isPODType(C);
4343 case UTT_IsLiteral:
4344 return T->isLiteralType(C);
4345 case UTT_IsEmpty:
4346 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4347 return !RD->isUnion() && RD->isEmpty();
4348 return false;
4349 case UTT_IsPolymorphic:
4350 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4351 return !RD->isUnion() && RD->isPolymorphic();
4352 return false;
4353 case UTT_IsAbstract:
4354 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4355 return !RD->isUnion() && RD->isAbstract();
4356 return false;
4357 case UTT_IsAggregate:
4358 // Report vector extensions and complex types as aggregates because they
4359 // support aggregate initialization. GCC mirrors this behavior for vectors
4360 // but not _Complex.
4361 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4362 T->isAnyComplexType();
4363 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4364 // even then only when it is used with the 'interface struct ...' syntax
4365 // Clang doesn't support /CLR which makes this type trait moot.
4366 case UTT_IsInterfaceClass:
4367 return false;
4368 case UTT_IsFinal:
4369 case UTT_IsSealed:
4370 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4371 return RD->hasAttr<FinalAttr>();
4372 return false;
4373 case UTT_IsSigned:
4374 return T->isSignedIntegerType();
4375 case UTT_IsUnsigned:
4376 return T->isUnsignedIntegerType();
4377
4378 // Type trait expressions which query classes regarding their construction,
4379 // destruction, and copying. Rather than being based directly on the
4380 // related type predicates in the standard, they are specified by both
4381 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4382 // specifications.
4383 //
4384 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4385 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4386 //
4387 // Note that these builtins do not behave as documented in g++: if a class
4388 // has both a trivial and a non-trivial special member of a particular kind,
4389 // they return false! For now, we emulate this behavior.
4390 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4391 // does not correctly compute triviality in the presence of multiple special
4392 // members of the same kind. Revisit this once the g++ bug is fixed.
4393 case UTT_HasTrivialDefaultConstructor:
4394 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4395 // If __is_pod (type) is true then the trait is true, else if type is
4396 // a cv class or union type (or array thereof) with a trivial default
4397 // constructor ([class.ctor]) then the trait is true, else it is false.
4398 if (T.isPODType(C))
4399 return true;
4400 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4401 return RD->hasTrivialDefaultConstructor() &&
4402 !RD->hasNonTrivialDefaultConstructor();
4403 return false;
4404 case UTT_HasTrivialMoveConstructor:
4405 // This trait is implemented by MSVC 2012 and needed to parse the
4406 // standard library headers. Specifically this is used as the logic
4407 // behind std::is_trivially_move_constructible (20.9.4.3).
4408 if (T.isPODType(C))
4409 return true;
4410 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4411 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4412 return false;
4413 case UTT_HasTrivialCopy:
4414 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4415 // If __is_pod (type) is true or type is a reference type then
4416 // the trait is true, else if type is a cv class or union type
4417 // with a trivial copy constructor ([class.copy]) then the trait
4418 // is true, else it is false.
4419 if (T.isPODType(C) || T->isReferenceType())
4420 return true;
4421 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4422 return RD->hasTrivialCopyConstructor() &&
4423 !RD->hasNonTrivialCopyConstructor();
4424 return false;
4425 case UTT_HasTrivialMoveAssign:
4426 // This trait is implemented by MSVC 2012 and needed to parse the
4427 // standard library headers. Specifically it is used as the logic
4428 // behind std::is_trivially_move_assignable (20.9.4.3)
4429 if (T.isPODType(C))
4430 return true;
4431 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4432 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4433 return false;
4434 case UTT_HasTrivialAssign:
4435 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4436 // If type is const qualified or is a reference type then the
4437 // trait is false. Otherwise if __is_pod (type) is true then the
4438 // trait is true, else if type is a cv class or union type with
4439 // a trivial copy assignment ([class.copy]) then the trait is
4440 // true, else it is false.
4441 // Note: the const and reference restrictions are interesting,
4442 // given that const and reference members don't prevent a class
4443 // from having a trivial copy assignment operator (but do cause
4444 // errors if the copy assignment operator is actually used, q.v.
4445 // [class.copy]p12).
4446
4447 if (T.isConstQualified())
4448 return false;
4449 if (T.isPODType(C))
4450 return true;
4451 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4452 return RD->hasTrivialCopyAssignment() &&
4453 !RD->hasNonTrivialCopyAssignment();
4454 return false;
4455 case UTT_IsDestructible:
4456 case UTT_IsTriviallyDestructible:
4457 case UTT_IsNothrowDestructible:
4458 // C++14 [meta.unary.prop]:
4459 // For reference types, is_destructible<T>::value is true.
4460 if (T->isReferenceType())
4461 return true;
4462
4463 // Objective-C++ ARC: autorelease types don't require destruction.
4464 if (T->isObjCLifetimeType() &&
4465 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4466 return true;
4467
4468 // C++14 [meta.unary.prop]:
4469 // For incomplete types and function types, is_destructible<T>::value is
4470 // false.
4471 if (T->isIncompleteType() || T->isFunctionType())
4472 return false;
4473
4474 // A type that requires destruction (via a non-trivial destructor or ARC
4475 // lifetime semantics) is not trivially-destructible.
4476 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4477 return false;
4478
4479 // C++14 [meta.unary.prop]:
4480 // For object types and given U equal to remove_all_extents_t<T>, if the
4481 // expression std::declval<U&>().~U() is well-formed when treated as an
4482 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4483 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4484 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4485 if (!Destructor)
4486 return false;
4487 // C++14 [dcl.fct.def.delete]p2:
4488 // A program that refers to a deleted function implicitly or
4489 // explicitly, other than to declare it, is ill-formed.
4490 if (Destructor->isDeleted())
4491 return false;
4492 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4493 return false;
4494 if (UTT == UTT_IsNothrowDestructible) {
4495 const FunctionProtoType *CPT =
4496 Destructor->getType()->getAs<FunctionProtoType>();
4497 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4498 if (!CPT || !CPT->isNothrow(C))
4499 return false;
4500 }
4501 }
4502 return true;
4503
4504 case UTT_HasTrivialDestructor:
4505 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4506 // If __is_pod (type) is true or type is a reference type
4507 // then the trait is true, else if type is a cv class or union
4508 // type (or array thereof) with a trivial destructor
4509 // ([class.dtor]) then the trait is true, else it is
4510 // false.
4511 if (T.isPODType(C) || T->isReferenceType())
4512 return true;
4513
4514 // Objective-C++ ARC: autorelease types don't require destruction.
4515 if (T->isObjCLifetimeType() &&
4516 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4517 return true;
4518
4519 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4520 return RD->hasTrivialDestructor();
4521 return false;
4522 // TODO: Propagate nothrowness for implicitly declared special members.
4523 case UTT_HasNothrowAssign:
4524 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4525 // If type is const qualified or is a reference type then the
4526 // trait is false. Otherwise if __has_trivial_assign (type)
4527 // is true then the trait is true, else if type is a cv class
4528 // or union type with copy assignment operators that are known
4529 // not to throw an exception then the trait is true, else it is
4530 // false.
4531 if (C.getBaseElementType(T).isConstQualified())
4532 return false;
4533 if (T->isReferenceType())
4534 return false;
4535 if (T.isPODType(C) || T->isObjCLifetimeType())
4536 return true;
4537
4538 if (const RecordType *RT = T->getAs<RecordType>())
4539 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4540 &CXXRecordDecl::hasTrivialCopyAssignment,
4541 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4542 &CXXMethodDecl::isCopyAssignmentOperator);
4543 return false;
4544 case UTT_HasNothrowMoveAssign:
4545 // This trait is implemented by MSVC 2012 and needed to parse the
4546 // standard library headers. Specifically this is used as the logic
4547 // behind std::is_nothrow_move_assignable (20.9.4.3).
4548 if (T.isPODType(C))
4549 return true;
4550
4551 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4552 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4553 &CXXRecordDecl::hasTrivialMoveAssignment,
4554 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4555 &CXXMethodDecl::isMoveAssignmentOperator);
4556 return false;
4557 case UTT_HasNothrowCopy:
4558 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4559 // If __has_trivial_copy (type) is true then the trait is true, else
4560 // if type is a cv class or union type with copy constructors that are
4561 // known not to throw an exception then the trait is true, else it is
4562 // false.
4563 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4564 return true;
4565 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4566 if (RD->hasTrivialCopyConstructor() &&
4567 !RD->hasNonTrivialCopyConstructor())
4568 return true;
4569
4570 bool FoundConstructor = false;
4571 unsigned FoundTQs;
4572 for (const auto *ND : Self.LookupConstructors(RD)) {
4573 // A template constructor is never a copy constructor.
4574 // FIXME: However, it may actually be selected at the actual overload
4575 // resolution point.
4576 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4577 continue;
4578 // UsingDecl itself is not a constructor
4579 if (isa<UsingDecl>(ND))
4580 continue;
4581 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4582 if (Constructor->isCopyConstructor(FoundTQs)) {
4583 FoundConstructor = true;
4584 const FunctionProtoType *CPT
4585 = Constructor->getType()->getAs<FunctionProtoType>();
4586 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4587 if (!CPT)
4588 return false;
4589 // TODO: check whether evaluating default arguments can throw.
4590 // For now, we'll be conservative and assume that they can throw.
4591 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
4592 return false;
4593 }
4594 }
4595
4596 return FoundConstructor;
4597 }
4598 return false;
4599 case UTT_HasNothrowConstructor:
4600 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4601 // If __has_trivial_constructor (type) is true then the trait is
4602 // true, else if type is a cv class or union type (or array
4603 // thereof) with a default constructor that is known not to
4604 // throw an exception then the trait is true, else it is false.
4605 if (T.isPODType(C) || T->isObjCLifetimeType())
4606 return true;
4607 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4608 if (RD->hasTrivialDefaultConstructor() &&
4609 !RD->hasNonTrivialDefaultConstructor())
4610 return true;
4611
4612 bool FoundConstructor = false;
4613 for (const auto *ND : Self.LookupConstructors(RD)) {
4614 // FIXME: In C++0x, a constructor template can be a default constructor.
4615 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4616 continue;
4617 // UsingDecl itself is not a constructor
4618 if (isa<UsingDecl>(ND))
4619 continue;
4620 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4621 if (Constructor->isDefaultConstructor()) {
4622 FoundConstructor = true;
4623 const FunctionProtoType *CPT
4624 = Constructor->getType()->getAs<FunctionProtoType>();
4625 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4626 if (!CPT)
4627 return false;
4628 // FIXME: check whether evaluating default arguments can throw.
4629 // For now, we'll be conservative and assume that they can throw.
4630 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
4631 return false;
4632 }
4633 }
4634 return FoundConstructor;
4635 }
4636 return false;
4637 case UTT_HasVirtualDestructor:
4638 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4639 // If type is a class type with a virtual destructor ([class.dtor])
4640 // then the trait is true, else it is false.
4641 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4642 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4643 return Destructor->isVirtual();
4644 return false;
4645
4646 // These type trait expressions are modeled on the specifications for the
4647 // Embarcadero C++0x type trait functions:
4648 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4649 case UTT_IsCompleteType:
4650 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4651 // Returns True if and only if T is a complete type at the point of the
4652 // function call.
4653 return !T->isIncompleteType();
4654 case UTT_HasUniqueObjectRepresentations:
4655 return C.hasUniqueObjectRepresentations(T);
4656 }
4657}
4658
4659static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4660 QualType RhsT, SourceLocation KeyLoc);
4661
4662static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4663 ArrayRef<TypeSourceInfo *> Args,
4664 SourceLocation RParenLoc) {
4665 if (Kind <= UTT_Last)
4666 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4667
4668 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4669 // traits to avoid duplication.
4670 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4671 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4672 Args[1]->getType(), RParenLoc);
4673
4674 switch (Kind) {
4675 case clang::BTT_ReferenceBindsToTemporary:
4676 case clang::TT_IsConstructible:
4677 case clang::TT_IsNothrowConstructible:
4678 case clang::TT_IsTriviallyConstructible: {
4679 // C++11 [meta.unary.prop]:
4680 // is_trivially_constructible is defined as:
4681 //
4682 // is_constructible<T, Args...>::value is true and the variable
4683 // definition for is_constructible, as defined below, is known to call
4684 // no operation that is not trivial.
4685 //
4686 // The predicate condition for a template specialization
4687 // is_constructible<T, Args...> shall be satisfied if and only if the
4688 // following variable definition would be well-formed for some invented
4689 // variable t:
4690 //
4691 // T t(create<Args>()...);
4692 assert(!Args.empty())(static_cast <bool> (!Args.empty()) ? void (0) : __assert_fail
("!Args.empty()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4692, __extension__ __PRETTY_FUNCTION__))
;
4693
4694 // Precondition: T and all types in the parameter pack Args shall be
4695 // complete types, (possibly cv-qualified) void, or arrays of
4696 // unknown bound.
4697 for (const auto *TSI : Args) {
4698 QualType ArgTy = TSI->getType();
4699 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4700 continue;
4701
4702 if (S.RequireCompleteType(KWLoc, ArgTy,
4703 diag::err_incomplete_type_used_in_type_trait_expr))
4704 return false;
4705 }
4706
4707 // Make sure the first argument is not incomplete nor a function type.
4708 QualType T = Args[0]->getType();
4709 if (T->isIncompleteType() || T->isFunctionType())
4710 return false;
4711
4712 // Make sure the first argument is not an abstract type.
4713 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4714 if (RD && RD->isAbstract())
4715 return false;
4716
4717 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4718 SmallVector<Expr *, 2> ArgExprs;
4719 ArgExprs.reserve(Args.size() - 1);
4720 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4721 QualType ArgTy = Args[I]->getType();
4722 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4723 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4724 OpaqueArgExprs.push_back(
4725 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4726 ArgTy.getNonLValueExprType(S.Context),
4727 Expr::getValueKindForType(ArgTy)));
4728 }
4729 for (Expr &E : OpaqueArgExprs)
4730 ArgExprs.push_back(&E);
4731
4732 // Perform the initialization in an unevaluated context within a SFINAE
4733 // trap at translation unit scope.
4734 EnterExpressionEvaluationContext Unevaluated(
4735 S, Sema::ExpressionEvaluationContext::Unevaluated);
4736 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4737 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4738 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4739 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4740 RParenLoc));
4741 InitializationSequence Init(S, To, InitKind, ArgExprs);
4742 if (Init.Failed())
4743 return false;
4744
4745 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4746 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4747 return false;
4748
4749 if (Kind == clang::TT_IsConstructible)
4750 return true;
4751
4752 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4753 if (!T->isReferenceType())
4754 return false;
4755
4756 return !Init.isDirectReferenceBinding();
4757 }
4758
4759 if (Kind == clang::TT_IsNothrowConstructible)
4760 return S.canThrow(Result.get()) == CT_Cannot;
4761
4762 if (Kind == clang::TT_IsTriviallyConstructible) {
4763 // Under Objective-C ARC and Weak, if the destination has non-trivial
4764 // Objective-C lifetime, this is a non-trivial construction.
4765 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
4766 return false;
4767
4768 // The initialization succeeded; now make sure there are no non-trivial
4769 // calls.
4770 return !Result.get()->hasNonTrivialCall(S.Context);
4771 }
4772
4773 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4773)
;
4774 return false;
4775 }
4776 default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4776)
;
4777 }
4778
4779 return false;
4780}
4781
4782ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4783 ArrayRef<TypeSourceInfo *> Args,
4784 SourceLocation RParenLoc) {
4785 QualType ResultType = Context.getLogicalOperationType();
4786
4787 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4788 *this, Kind, KWLoc, Args[0]->getType()))
4789 return ExprError();
4790
4791 bool Dependent = false;
4792 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4793 if (Args[I]->getType()->isDependentType()) {
4794 Dependent = true;
4795 break;
4796 }
4797 }
4798
4799 bool Result = false;
4800 if (!Dependent)
4801 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4802
4803 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4804 RParenLoc, Result);
4805}
4806
4807ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4808 ArrayRef<ParsedType> Args,
4809 SourceLocation RParenLoc) {
4810 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
4811 ConvertedArgs.reserve(Args.size());
4812
4813 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4814 TypeSourceInfo *TInfo;
4815 QualType T = GetTypeFromParser(Args[I], &TInfo);
4816 if (!TInfo)
4817 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4818
4819 ConvertedArgs.push_back(TInfo);
4820 }
4821
4822 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4823}
4824
4825static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4826 QualType RhsT, SourceLocation KeyLoc) {
4827 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&(static_cast <bool> (!LhsT->isDependentType() &&
!RhsT->isDependentType() && "Cannot evaluate traits of dependent types"
) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4828, __extension__ __PRETTY_FUNCTION__))
4828 "Cannot evaluate traits of dependent types")(static_cast <bool> (!LhsT->isDependentType() &&
!RhsT->isDependentType() && "Cannot evaluate traits of dependent types"
) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4828, __extension__ __PRETTY_FUNCTION__))
;
4829
4830 switch(BTT) {
4831 case BTT_IsBaseOf: {
4832 // C++0x [meta.rel]p2
4833 // Base is a base class of Derived without regard to cv-qualifiers or
4834 // Base and Derived are not unions and name the same class type without
4835 // regard to cv-qualifiers.
4836
4837 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4838 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4839 if (!rhsRecord || !lhsRecord) {
4840 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4841 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4842 if (!LHSObjTy || !RHSObjTy)
4843 return false;
4844
4845 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4846 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4847 if (!BaseInterface || !DerivedInterface)
4848 return false;
4849
4850 if (Self.RequireCompleteType(
4851 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4852 return false;
4853
4854 return BaseInterface->isSuperClassOf(DerivedInterface);
4855 }
4856
4857 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)(static_cast <bool> (Self.Context.hasSameUnqualifiedType
(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4858, __extension__ __PRETTY_FUNCTION__))
4858 == (lhsRecord == rhsRecord))(static_cast <bool> (Self.Context.hasSameUnqualifiedType
(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4858, __extension__ __PRETTY_FUNCTION__))
;
4859
4860 if (lhsRecord == rhsRecord)
4861 return !lhsRecord->getDecl()->isUnion();
4862
4863 // C++0x [meta.rel]p2:
4864 // If Base and Derived are class types and are different types
4865 // (ignoring possible cv-qualifiers) then Derived shall be a
4866 // complete type.
4867 if (Self.RequireCompleteType(KeyLoc, RhsT,
4868 diag::err_incomplete_type_used_in_type_trait_expr))
4869 return false;
4870
4871 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4872 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4873 }
4874 case BTT_IsSame:
4875 return Self.Context.hasSameType(LhsT, RhsT);
4876 case BTT_TypeCompatible: {
4877 // GCC ignores cv-qualifiers on arrays for this builtin.
4878 Qualifiers LhsQuals, RhsQuals;
4879 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
4880 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
4881 return Self.Context.typesAreCompatible(Lhs, Rhs);
4882 }
4883 case BTT_IsConvertible:
4884 case BTT_IsConvertibleTo: {
4885 // C++0x [meta.rel]p4:
4886 // Given the following function prototype:
4887 //
4888 // template <class T>
4889 // typename add_rvalue_reference<T>::type create();
4890 //
4891 // the predicate condition for a template specialization
4892 // is_convertible<From, To> shall be satisfied if and only if
4893 // the return expression in the following code would be
4894 // well-formed, including any implicit conversions to the return
4895 // type of the function:
4896 //
4897 // To test() {
4898 // return create<From>();
4899 // }
4900 //
4901 // Access checking is performed as if in a context unrelated to To and
4902 // From. Only the validity of the immediate context of the expression
4903 // of the return-statement (including conversions to the return type)
4904 // is considered.
4905 //
4906 // We model the initialization as a copy-initialization of a temporary
4907 // of the appropriate type, which for this expression is identical to the
4908 // return statement (since NRVO doesn't apply).
4909
4910 // Functions aren't allowed to return function or array types.
4911 if (RhsT->isFunctionType() || RhsT->isArrayType())
4912 return false;
4913
4914 // A return statement in a void function must have void type.
4915 if (RhsT->isVoidType())
4916 return LhsT->isVoidType();
4917
4918 // A function definition requires a complete, non-abstract return type.
4919 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
4920 return false;
4921
4922 // Compute the result of add_rvalue_reference.
4923 if (LhsT->isObjectType() || LhsT->isFunctionType())
4924 LhsT = Self.Context.getRValueReferenceType(LhsT);
4925
4926 // Build a fake source and destination for initialization.
4927 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
4928 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4929 Expr::getValueKindForType(LhsT));
4930 Expr *FromPtr = &From;
4931 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
4932 SourceLocation()));
4933
4934 // Perform the initialization in an unevaluated context within a SFINAE
4935 // trap at translation unit scope.
4936 EnterExpressionEvaluationContext Unevaluated(
4937 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4938 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4939 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4940 InitializationSequence Init(Self, To, Kind, FromPtr);
4941 if (Init.Failed())
4942 return false;
4943
4944 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
4945 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4946 }
4947
4948 case BTT_IsAssignable:
4949 case BTT_IsNothrowAssignable:
4950 case BTT_IsTriviallyAssignable: {
4951 // C++11 [meta.unary.prop]p3:
4952 // is_trivially_assignable is defined as:
4953 // is_assignable<T, U>::value is true and the assignment, as defined by
4954 // is_assignable, is known to call no operation that is not trivial
4955 //
4956 // is_assignable is defined as:
4957 // The expression declval<T>() = declval<U>() is well-formed when
4958 // treated as an unevaluated operand (Clause 5).
4959 //
4960 // For both, T and U shall be complete types, (possibly cv-qualified)
4961 // void, or arrays of unknown bound.
4962 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4963 Self.RequireCompleteType(KeyLoc, LhsT,
4964 diag::err_incomplete_type_used_in_type_trait_expr))
4965 return false;
4966 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4967 Self.RequireCompleteType(KeyLoc, RhsT,
4968 diag::err_incomplete_type_used_in_type_trait_expr))
4969 return false;
4970
4971 // cv void is never assignable.
4972 if (LhsT->isVoidType() || RhsT->isVoidType())
4973 return false;
4974
4975 // Build expressions that emulate the effect of declval<T>() and
4976 // declval<U>().
4977 if (LhsT->isObjectType() || LhsT->isFunctionType())
4978 LhsT = Self.Context.getRValueReferenceType(LhsT);
4979 if (RhsT->isObjectType() || RhsT->isFunctionType())
4980 RhsT = Self.Context.getRValueReferenceType(RhsT);
4981 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4982 Expr::getValueKindForType(LhsT));
4983 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4984 Expr::getValueKindForType(RhsT));
4985
4986 // Attempt the assignment in an unevaluated context within a SFINAE
4987 // trap at translation unit scope.
4988 EnterExpressionEvaluationContext Unevaluated(
4989 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4990 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4991 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4992 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4993 &Rhs);
4994 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4995 return false;
4996
4997 if (BTT == BTT_IsAssignable)
4998 return true;
4999
5000 if (BTT == BTT_IsNothrowAssignable)
5001 return Self.canThrow(Result.get()) == CT_Cannot;
5002
5003 if (BTT == BTT_IsTriviallyAssignable) {
5004 // Under Objective-C ARC and Weak, if the destination has non-trivial
5005 // Objective-C lifetime, this is a non-trivial assignment.
5006 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5007 return false;
5008
5009 return !Result.get()->hasNonTrivialCall(Self.Context);
5010 }
5011
5012 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5012)
;
5013 return false;
5014 }
5015 default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5015)
;
5016 }
5017 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5017)
;
5018}
5019
5020ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5021 SourceLocation KWLoc,
5022 ParsedType Ty,
5023 Expr* DimExpr,
5024 SourceLocation RParen) {
5025 TypeSourceInfo *TSInfo;
5026 QualType T = GetTypeFromParser(Ty, &TSInfo);
5027 if (!TSInfo)
5028 TSInfo = Context.getTrivialTypeSourceInfo(T);
5029
5030 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5031}
5032
5033static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5034 QualType T, Expr *DimExpr,
5035 SourceLocation KeyLoc) {
5036 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() &&
"Cannot evaluate traits of dependent type") ? void (0) : __assert_fail
("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5036, __extension__ __PRETTY_FUNCTION__))
;
5037
5038 switch(ATT) {
5039 case ATT_ArrayRank:
5040 if (T->isArrayType()) {
5041 unsigned Dim = 0;
5042 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5043 ++Dim;
5044 T = AT->getElementType();
5045 }
5046 return Dim;
5047 }
5048 return 0;
5049
5050 case ATT_ArrayExtent: {
5051 llvm::APSInt Value;
5052 uint64_t Dim;
5053 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5054 diag::err_dimension_expr_not_constant_integer,
5055 false).isInvalid())
5056 return 0;
5057 if (Value.isSigned() && Value.isNegative()) {
5058 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5059 << DimExpr->getSourceRange();
5060 return 0;
5061 }
5062 Dim = Value.getLimitedValue();
5063
5064 if (T->isArrayType()) {
5065 unsigned D = 0;
5066 bool Matched = false;
5067 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5068 if (Dim == D) {
5069 Matched = true;
5070 break;
5071 }
5072 ++D;
5073 T = AT->getElementType();
5074 }
5075
5076 if (Matched && T->isArrayType()) {
5077 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5078 return CAT->getSize().getLimitedValue();
5079 }
5080 }
5081 return 0;
5082 }
5083 }
5084 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5084)
;
5085}
5086
5087ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5088 SourceLocation KWLoc,
5089 TypeSourceInfo *TSInfo,
5090 Expr* DimExpr,
5091 SourceLocation RParen) {
5092 QualType T = TSInfo->getType();
5093
5094 // FIXME: This should likely be tracked as an APInt to remove any host
5095 // assumptions about the width of size_t on the target.
5096 uint64_t Value = 0;
5097 if (!T->isDependentType())
5098 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5099
5100 // While the specification for these traits from the Embarcadero C++
5101 // compiler's documentation says the return type is 'unsigned int', Clang
5102 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5103 // compiler, there is no difference. On several other platforms this is an
5104 // important distinction.
5105 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5106 RParen, Context.getSizeType());
5107}
5108
5109ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5110 SourceLocation KWLoc,
5111 Expr *Queried,
5112 SourceLocation RParen) {
5113 // If error parsing the expression, ignore.
5114 if (!Queried)
5115 return ExprError();
5116
5117 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5118
5119 return Result;
5120}
5121
5122static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5123 switch (ET) {
5124 case ET_IsLValueExpr: return E->isLValue();
5125 case ET_IsRValueExpr: return E->isRValue();
5126 }
5127 llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5127)
;
5128}
5129
5130ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5131 SourceLocation KWLoc,
5132 Expr *Queried,
5133 SourceLocation RParen) {
5134 if (Queried->isTypeDependent()) {
5135 // Delay type-checking for type-dependent expressions.
5136 } else if (Queried->getType()->isPlaceholderType()) {
5137 ExprResult PE = CheckPlaceholderExpr(Queried);
5138 if (PE.isInvalid()) return ExprError();
5139 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5140 }
5141
5142 bool Value = EvaluateExpressionTrait(ET, Queried);
5143
5144 return new (Context)
5145 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5146}
5147
5148QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5149 ExprValueKind &VK,
5150 SourceLocation Loc,
5151 bool isIndirect) {
5152 assert(!LHS.get()->getType()->isPlaceholderType() &&(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType
() && !RHS.get()->getType()->isPlaceholderType(
) && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5154, __extension__ __PRETTY_FUNCTION__))
5153 !RHS.get()->getType()->isPlaceholderType() &&(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType
() && !RHS.get()->getType()->isPlaceholderType(
) && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5154, __extension__ __PRETTY_FUNCTION__))
5154 "placeholders should have been weeded out by now")(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType
() && !RHS.get()->getType()->isPlaceholderType(
) && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5154, __extension__ __PRETTY_FUNCTION__))
;
5155
5156 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5157 // temporary materialization conversion otherwise.
5158 if (isIndirect)
5159 LHS = DefaultLvalueConversion(LHS.get());
5160 else if (LHS.get()->isRValue())
5161 LHS = TemporaryMaterializationConversion(LHS.get());
5162 if (LHS.isInvalid())
5163 return QualType();
5164
5165 // The RHS always undergoes lvalue conversions.
5166 RHS = DefaultLvalueConversion(RHS.get());
5167 if (RHS.isInvalid()) return QualType();
5168
5169 const char *OpSpelling = isIndirect ? "->*" : ".*";
5170 // C++ 5.5p2
5171 // The binary operator .* [p3: ->*] binds its second operand, which shall
5172 // be of type "pointer to member of T" (where T is a completely-defined
5173 // class type) [...]
5174 QualType RHSType = RHS.get()->getType();
5175 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5176 if (!MemPtr) {
5177 Diag(Loc, diag::err_bad_memptr_rhs)
5178 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5179 return QualType();
5180 }
5181
5182 QualType Class(MemPtr->getClass(), 0);
5183
5184 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5185 // member pointer points must be completely-defined. However, there is no
5186 // reason for this semantic distinction, and the rule is not enforced by
5187 // other compilers. Therefore, we do not check this property, as it is
5188 // likely to be considered a defect.
5189
5190 // C++ 5.5p2
5191 // [...] to its first operand, which shall be of class T or of a class of
5192 // which T is an unambiguous and accessible base class. [p3: a pointer to
5193 // such a class]
5194 QualType LHSType = LHS.get()->getType();
5195 if (isIndirect) {
5196 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5197 LHSType = Ptr->getPointeeType();
5198 else {
5199 Diag(Loc, diag::err_bad_memptr_lhs)
5200 << OpSpelling << 1 << LHSType
5201 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5202 return QualType();
5203 }
5204 }
5205
5206 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5207 // If we want to check the hierarchy, we need a complete type.
5208 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5209 OpSpelling, (int)isIndirect)) {
5210 return QualType();
5211 }
5212
5213 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5214 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5215 << (int)isIndirect << LHS.get()->getType();
5216 return QualType();
5217 }
5218
5219 CXXCastPath BasePath;
5220 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5221 SourceRange(LHS.get()->getLocStart(),
5222 RHS.get()->getLocEnd()),
5223 &BasePath))
5224 return QualType();
5225
5226 // Cast LHS to type of use.
5227 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5228 if (isIndirect)
5229 UseType = Context.getPointerType(UseType);
5230 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5231 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5232 &BasePath);
5233 }
5234
5235 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5236 // Diagnose use of pointer-to-member type which when used as
5237 // the functional cast in a pointer-to-member expression.
5238 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5239 return QualType();
5240 }
5241
5242 // C++ 5.5p2
5243 // The result is an object or a function of the type specified by the
5244 // second operand.
5245 // The cv qualifiers are the union of those in the pointer and the left side,
5246 // in accordance with 5.5p5 and 5.2.5.
5247 QualType Result = MemPtr->getPointeeType();
5248 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5249
5250 // C++0x [expr.mptr.oper]p6:
5251 // In a .* expression whose object expression is an rvalue, the program is
5252 // ill-formed if the second operand is a pointer to member function with
5253 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5254 // expression is an lvalue, the program is ill-formed if the second operand
5255 // is a pointer to member function with ref-qualifier &&.
5256 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5257 switch (Proto->getRefQualifier()) {
5258 case RQ_None:
5259 // Do nothing
5260 break;
5261
5262 case RQ_LValue:
5263 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5264 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5265 if (Proto->isConst())
5266 Diag(Loc, getLangOpts().CPlusPlus2a
5267 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5268 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5269 else
5270 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5271 << RHSType << 1 << LHS.get()->getSourceRange();
5272 }
5273 break;
5274
5275 case RQ_RValue:
5276 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5277 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5278 << RHSType << 0 << LHS.get()->getSourceRange();
5279 break;
5280 }
5281 }
5282
5283 // C++ [expr.mptr.oper]p6:
5284 // The result of a .* expression whose second operand is a pointer
5285 // to a data member is of the same value category as its
5286 // first operand. The result of a .* expression whose second
5287 // operand is a pointer to a member function is a prvalue. The
5288 // result of an ->* expression is an lvalue if its second operand
5289 // is a pointer to data member and a prvalue otherwise.
5290 if (Result->isFunctionType()) {
5291 VK = VK_RValue;
5292 return Context.BoundMemberTy;
5293 } else if (isIndirect) {
5294 VK = VK_LValue;
5295 } else {
5296 VK = LHS.get()->getValueKind();
5297 }
5298
5299 return Result;
5300}
5301
5302/// \brief Try to convert a type to another according to C++11 5.16p3.
5303///
5304/// This is part of the parameter validation for the ? operator. If either
5305/// value operand is a class type, the two operands are attempted to be
5306/// converted to each other. This function does the conversion in one direction.
5307/// It returns true if the program is ill-formed and has already been diagnosed
5308/// as such.
5309static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5310 SourceLocation QuestionLoc,
5311 bool &HaveConversion,
5312 QualType &ToType) {
5313 HaveConversion = false;
5314 ToType = To->getType();
5315
5316 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
5317 SourceLocation());
5318 // C++11 5.16p3
5319 // The process for determining whether an operand expression E1 of type T1
5320 // can be converted to match an operand expression E2 of type T2 is defined
5321 // as follows:
5322 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5323 // implicitly converted to type "lvalue reference to T2", subject to the
5324 // constraint that in the conversion the reference must bind directly to
5325 // an lvalue.
5326 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5327 // implicitly conveted to the type "rvalue reference to R2", subject to
5328 // the constraint that the reference must bind directly.
5329 if (To->isLValue() || To->isXValue()) {
5330 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5331 : Self.Context.getRValueReferenceType(ToType);
5332
5333 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5334
5335 InitializationSequence InitSeq(Self, Entity, Kind, From);
5336 if (InitSeq.isDirectReferenceBinding()) {
5337 ToType = T;
5338 HaveConversion = true;
5339 return false;
5340 }
5341
5342 if (InitSeq.isAmbiguous())
5343 return InitSeq.Diagnose(Self, Entity, Kind, From);
5344 }
5345
5346 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5347 // -- if E1 and E2 have class type, and the underlying class types are
5348 // the same or one is a base class of the other:
5349 QualType FTy = From->getType();
5350 QualType TTy = To->getType();
5351 const RecordType *FRec = FTy->getAs<RecordType>();
5352 const RecordType *TRec = TTy->getAs<RecordType>();
5353 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5354 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5355 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5356 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5357 // E1 can be converted to match E2 if the class of T2 is the
5358 // same type as, or a base class of, the class of T1, and
5359 // [cv2 > cv1].
5360 if (FRec == TRec || FDerivedFromT) {
5361 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5362 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5363 InitializationSequence InitSeq(Self, Entity, Kind, From);
5364 if (InitSeq) {
5365 HaveConversion = true;
5366 return false;
5367 }
5368
5369 if (InitSeq.isAmbiguous())
5370 return InitSeq.Diagnose(Self, Entity, Kind, From);
5371 }
5372 }
5373
5374 return false;
5375 }
5376
5377 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5378 // implicitly converted to the type that expression E2 would have
5379 // if E2 were converted to an rvalue (or the type it has, if E2 is
5380 // an rvalue).
5381 //
5382 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5383 // to the array-to-pointer or function-to-pointer conversions.
5384 TTy = TTy.getNonLValueExprType(Self.Context);
5385
5386 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5387 InitializationSequence InitSeq(Self, Entity, Kind, From);
5388 HaveConversion = !InitSeq.Failed();
5389 ToType = TTy;
5390 if (InitSeq.isAmbiguous())
5391 return InitSeq.Diagnose(Self, Entity, Kind, From);
5392
5393 return false;
5394}
5395
5396/// \brief Try to find a common type for two according to C++0x 5.16p5.
5397///
5398/// This is part of the parameter validation for the ? operator. If either
5399/// value operand is a class type, overload resolution is used to find a
5400/// conversion to a common type.
5401static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5402 SourceLocation QuestionLoc) {
5403 Expr *Args[2] = { LHS.get(), RHS.get() };
5404 OverloadCandidateSet CandidateSet(QuestionLoc,
5405 OverloadCandidateSet::CSK_Operator);
5406 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5407 CandidateSet);
5408
5409 OverloadCandidateSet::iterator Best;
5410 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5411 case OR_Success: {
5412 // We found a match. Perform the conversions on the arguments and move on.
5413 ExprResult LHSRes = Self.PerformImplicitConversion(
5414 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5415 Sema::AA_Converting);
5416 if (LHSRes.isInvalid())
5417 break;
5418 LHS = LHSRes;
5419
5420 ExprResult RHSRes = Self.PerformImplicitConversion(
5421 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5422 Sema::AA_Converting);
5423 if (RHSRes.isInvalid())
5424 break;
5425 RHS = RHSRes;
5426 if (Best->Function)
5427 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5428 return false;
5429 }
5430
5431 case OR_No_Viable_Function:
5432
5433 // Emit a better diagnostic if one of the expressions is a null pointer
5434 // constant and the other is a pointer type. In this case, the user most
5435 // likely forgot to take the address of the other expression.
5436 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5437 return true;
5438
5439 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5440 << LHS.get()->getType() << RHS.get()->getType()
5441 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5442 return true;
5443
5444 case OR_Ambiguous:
5445 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5446 << LHS.get()->getType() << RHS.get()->getType()
5447 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5448 // FIXME: Print the possible common types by printing the return types of
5449 // the viable candidates.
5450 break;
5451
5452 case OR_Deleted:
5453 llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5453)
;
5454 }
5455 return true;
5456}
5457
5458/// \brief Perform an "extended" implicit conversion as returned by
5459/// TryClassUnification.
5460static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5461 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5462 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
5463 SourceLocation());
5464 Expr *Arg = E.get();
5465 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5466 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5467 if (Result.isInvalid())
5468 return true;
5469
5470 E = Result;
5471 return false;
5472}
5473
5474/// \brief Check the operands of ?: under C++ semantics.
5475///
5476/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5477/// extension. In this case, LHS == Cond. (But they're not aliases.)
5478QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5479 ExprResult &RHS, ExprValueKind &VK,
5480 ExprObjectKind &OK,
5481 SourceLocation QuestionLoc) {
5482 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5483 // interface pointers.
5484
5485 // C++11 [expr.cond]p1
5486 // The first expression is contextually converted to bool.
5487 //
5488 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5489 // a is that of a integer vector with the same number of elements and
5490 // size as the vectors of b and c. If one of either b or c is a scalar
5491 // it is implicitly converted to match the type of the vector.
5492 // Otherwise the expression is ill-formed. If both b and c are scalars,
5493 // then b and c are checked and converted to the type of a if possible.
5494 // Unlike the OpenCL ?: operator, the expression is evaluated as
5495 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5496 if (!Cond.get()->isTypeDependent()) {
5497 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5498 if (CondRes.isInvalid())
5499 return QualType();
5500 Cond = CondRes;
5501 }
5502
5503 // Assume r-value.
5504 VK = VK_RValue;
5505 OK = OK_Ordinary;
5506
5507 // Either of the arguments dependent?
5508 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5509 return Context.DependentTy;
5510
5511 // C++11 [expr.cond]p2
5512 // If either the second or the third operand has type (cv) void, ...
5513 QualType LTy = LHS.get()->getType();
5514 QualType RTy = RHS.get()->getType();
5515 bool LVoid = LTy->isVoidType();
5516 bool RVoid = RTy->isVoidType();
5517 if (LVoid || RVoid) {
5518 // ... one of the following shall hold:
5519 // -- The second or the third operand (but not both) is a (possibly
5520 // parenthesized) throw-expression; the result is of the type
5521 // and value category of the other.
5522 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5523 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5524 if (LThrow != RThrow) {
5525 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5526 VK = NonThrow->getValueKind();
5527 // DR (no number yet): the result is a bit-field if the
5528 // non-throw-expression operand is a bit-field.
5529 OK = NonThrow->getObjectKind();
5530 return NonThrow->getType();
5531 }
5532
5533 // -- Both the second and third operands have type void; the result is of
5534 // type void and is a prvalue.
5535 if (LVoid && RVoid)
5536 return Context.VoidTy;
5537
5538 // Neither holds, error.
5539 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5540 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5541 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5542 return QualType();
5543 }
5544
5545 // Neither is void.
5546
5547 // C++11 [expr.cond]p3
5548 // Otherwise, if the second and third operand have different types, and
5549 // either has (cv) class type [...] an attempt is made to convert each of
5550 // those operands to the type of the other.
5551 if (!Context.hasSameType(LTy, RTy) &&
5552 (LTy->isRecordType() || RTy->isRecordType())) {
5553 // These return true if a single direction is already ambiguous.
5554 QualType L2RType, R2LType;
5555 bool HaveL2R, HaveR2L;
5556 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5557 return QualType();
5558 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5559 return QualType();
5560
5561 // If both can be converted, [...] the program is ill-formed.
5562 if (HaveL2R && HaveR2L) {
5563 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5564 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5565 return QualType();
5566 }
5567
5568 // If exactly one conversion is possible, that conversion is applied to
5569 // the chosen operand and the converted operands are used in place of the
5570 // original operands for the remainder of this section.
5571 if (HaveL2R) {
5572 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5573 return QualType();
5574 LTy = LHS.get()->getType();
5575 } else if (HaveR2L) {
5576 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5577 return QualType();
5578 RTy = RHS.get()->getType();
5579 }
5580 }
5581
5582 // C++11 [expr.cond]p3
5583 // if both are glvalues of the same value category and the same type except
5584 // for cv-qualification, an attempt is made to convert each of those
5585 // operands to the type of the other.
5586 // FIXME:
5587 // Resolving a defect in P0012R1: we extend this to cover all cases where
5588 // one of the operands is reference-compatible with the other, in order
5589 // to support conditionals between functions differing in noexcept.
5590 ExprValueKind LVK = LHS.get()->getValueKind();
5591 ExprValueKind RVK = RHS.get()->getValueKind();
5592 if (!Context.hasSameType(LTy, RTy) &&
5593 LVK == RVK && LVK != VK_RValue) {
5594 // DerivedToBase was already handled by the class-specific case above.
5595 // FIXME: Should we allow ObjC conversions here?
5596 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5597 if (CompareReferenceRelationship(
5598 QuestionLoc, LTy, RTy, DerivedToBase,
5599 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5600 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5601 // [...] subject to the constraint that the reference must bind
5602 // directly [...]
5603 !RHS.get()->refersToBitField() &&
5604 !RHS.get()->refersToVectorElement()) {
5605 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5606 RTy = RHS.get()->getType();
5607 } else if (CompareReferenceRelationship(
5608 QuestionLoc, RTy, LTy, DerivedToBase,
5609 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5610 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5611 !LHS.get()->refersToBitField() &&
5612 !LHS.get()->refersToVectorElement()) {
5613 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5614 LTy = LHS.get()->getType();
5615 }
5616 }
5617
5618 // C++11 [expr.cond]p4
5619 // If the second and third operands are glvalues of the same value
5620 // category and have the same type, the result is of that type and
5621 // value category and it is a bit-field if the second or the third
5622 // operand is a bit-field, or if both are bit-fields.
5623 // We only extend this to bitfields, not to the crazy other kinds of
5624 // l-values.
5625 bool Same = Context.hasSameType(LTy, RTy);
5626 if (Same && LVK == RVK && LVK != VK_RValue &&
5627 LHS.get()->isOrdinaryOrBitFieldObject() &&
5628 RHS.get()->isOrdinaryOrBitFieldObject()) {
5629 VK = LHS.get()->getValueKind();
5630 if (LHS.get()->getObjectKind() == OK_BitField ||
5631 RHS.get()->getObjectKind() == OK_BitField)
5632 OK = OK_BitField;
5633
5634 // If we have function pointer types, unify them anyway to unify their
5635 // exception specifications, if any.
5636 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5637 Qualifiers Qs = LTy.getQualifiers();
5638 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
5639 /*ConvertArgs*/false);
5640 LTy = Context.getQualifiedType(LTy, Qs);
5641
5642 assert(!LTy.isNull() && "failed to find composite pointer type for "(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? void (0) : __assert_fail
("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5643, __extension__ __PRETTY_FUNCTION__))
5643 "canonically equivalent function ptr types")(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? void (0) : __assert_fail
("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5643, __extension__ __PRETTY_FUNCTION__))
;
5644 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type")(static_cast <bool> (Context.hasSameType(LTy, RTy) &&
"bad composite pointer type") ? void (0) : __assert_fail ("Context.hasSameType(LTy, RTy) && \"bad composite pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5644, __extension__ __PRETTY_FUNCTION__))
;
5645 }
5646
5647 return LTy;
5648 }
5649
5650 // C++11 [expr.cond]p5
5651 // Otherwise, the result is a prvalue. If the second and third operands
5652 // do not have the same type, and either has (cv) class type, ...
5653 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5654 // ... overload resolution is used to determine the conversions (if any)
5655 // to be applied to the operands. If the overload resolution fails, the
5656 // program is ill-formed.
5657 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5658 return QualType();
5659 }
5660
5661 // C++11 [expr.cond]p6
5662 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5663 // conversions are performed on the second and third operands.
5664 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5665 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5666 if (LHS.isInvalid() || RHS.isInvalid())
5667 return QualType();
5668 LTy = LHS.get()->getType();
5669 RTy = RHS.get()->getType();
5670
5671 // After those conversions, one of the following shall hold:
5672 // -- The second and third operands have the same type; the result
5673 // is of that type. If the operands have class type, the result
5674 // is a prvalue temporary of the result type, which is
5675 // copy-initialized from either the second operand or the third
5676 // operand depending on the value of the first operand.
5677 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5678 if (LTy->isRecordType()) {
5679 // The operands have class type. Make a temporary copy.
5680 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5681
5682 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5683 SourceLocation(),
5684 LHS);
5685 if (LHSCopy.isInvalid())
5686 return QualType();
5687
5688 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5689 SourceLocation(),
5690 RHS);
5691 if (RHSCopy.isInvalid())
5692 return QualType();
5693
5694 LHS = LHSCopy;
5695 RHS = RHSCopy;
5696 }
5697
5698 // If we have function pointer types, unify them anyway to unify their
5699 // exception specifications, if any.
5700 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5701 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5702 assert(!LTy.isNull() && "failed to find composite pointer type for "(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? void (0) : __assert_fail
("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5703, __extension__ __PRETTY_FUNCTION__))
5703 "canonically equivalent function ptr types")(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? void (0) : __assert_fail
("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5703, __extension__ __PRETTY_FUNCTION__))
;
5704 }
5705
5706 return LTy;
5707 }
5708
5709 // Extension: conditional operator involving vector types.
5710 if (LTy->isVectorType() || RTy->isVectorType())
5711 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5712 /*AllowBothBool*/true,
5713 /*AllowBoolConversions*/false);
5714
5715 // -- The second and third operands have arithmetic or enumeration type;
5716 // the usual arithmetic conversions are performed to bring them to a
5717 // common type, and the result is of that type.
5718 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5719 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5720 if (LHS.isInvalid() || RHS.isInvalid())
5721 return QualType();
5722 if (ResTy.isNull()) {
5723 Diag(QuestionLoc,
5724 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5726 return QualType();
5727 }
5728
5729 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5730 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5731
5732 return ResTy;
5733 }
5734
5735 // -- The second and third operands have pointer type, or one has pointer
5736 // type and the other is a null pointer constant, or both are null
5737 // pointer constants, at least one of which is non-integral; pointer
5738 // conversions and qualification conversions are performed to bring them
5739 // to their composite pointer type. The result is of the composite
5740 // pointer type.
5741 // -- The second and third operands have pointer to member type, or one has
5742 // pointer to member type and the other is a null pointer constant;
5743 // pointer to member conversions and qualification conversions are
5744 // performed to bring them to a common type, whose cv-qualification
5745 // shall match the cv-qualification of either the second or the third
5746 // operand. The result is of the common type.
5747 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5748 if (!Composite.isNull())
5749 return Composite;
5750
5751 // Similarly, attempt to find composite type of two objective-c pointers.
5752 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5753 if (!Composite.isNull())
5754 return Composite;
5755
5756 // Check if we are using a null with a non-pointer type.
5757 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5758 return QualType();
5759
5760 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5761 << LHS.get()->getType() << RHS.get()->getType()
5762 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5763 return QualType();
5764}
5765
5766static FunctionProtoType::ExceptionSpecInfo
5767mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5768 FunctionProtoType::ExceptionSpecInfo ESI2,
5769 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5770 ExceptionSpecificationType EST1 = ESI1.Type;
5771 ExceptionSpecificationType EST2 = ESI2.Type;
5772
5773 // If either of them can throw anything, that is the result.
5774 if (EST1 == EST_None) return ESI1;
5775 if (EST2 == EST_None) return ESI2;
5776 if (EST1 == EST_MSAny) return ESI1;
5777 if (EST2 == EST_MSAny) return ESI2;
5778
5779 // If either of them is non-throwing, the result is the other.
5780 if (EST1 == EST_DynamicNone) return ESI2;
5781 if (EST2 == EST_DynamicNone) return ESI1;
5782 if (EST1 == EST_BasicNoexcept) return ESI2;
5783 if (EST2 == EST_BasicNoexcept) return ESI1;
5784
5785 // If either of them is a non-value-dependent computed noexcept, that
5786 // determines the result.
5787 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5788 !ESI2.NoexceptExpr->isValueDependent())
5789 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5790 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5791 !ESI1.NoexceptExpr->isValueDependent())
5792 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5793 // If we're left with value-dependent computed noexcept expressions, we're
5794 // stuck. Before C++17, we can just drop the exception specification entirely,
5795 // since it's not actually part of the canonical type. And this should never
5796 // happen in C++17, because it would mean we were computing the composite
5797 // pointer type of dependent types, which should never happen.
5798 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5799 assert(!S.getLangOpts().CPlusPlus17 &&(static_cast <bool> (!S.getLangOpts().CPlusPlus17 &&
"computing composite pointer type of dependent types") ? void
(0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5800, __extension__ __PRETTY_FUNCTION__))
5800 "computing composite pointer type of dependent types")(static_cast <bool> (!S.getLangOpts().CPlusPlus17 &&
"computing composite pointer type of dependent types") ? void
(0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5800, __extension__ __PRETTY_FUNCTION__))
;
5801 return FunctionProtoType::ExceptionSpecInfo();
5802 }
5803
5804 // Switch over the possibilities so that people adding new values know to
5805 // update this function.
5806 switch (EST1) {
5807 case EST_None:
5808 case EST_DynamicNone:
5809 case EST_MSAny:
5810 case EST_BasicNoexcept:
5811 case EST_ComputedNoexcept:
5812 llvm_unreachable("handled above")::llvm::llvm_unreachable_internal("handled above", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5812)
;
5813
5814 case EST_Dynamic: {
5815 // This is the fun case: both exception specifications are dynamic. Form
5816 // the union of the two lists.
5817 assert(EST2 == EST_Dynamic && "other cases should already be handled")(static_cast <bool> (EST2 == EST_Dynamic && "other cases should already be handled"
) ? void (0) : __assert_fail ("EST2 == EST_Dynamic && \"other cases should already be handled\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5817, __extension__ __PRETTY_FUNCTION__))
;
5818 llvm::SmallPtrSet<QualType, 8> Found;
5819 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5820 for (QualType E : Exceptions)
5821 if (Found.insert(S.Context.getCanonicalType(E)).second)
5822 ExceptionTypeStorage.push_back(E);
5823
5824 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5825 Result.Exceptions = ExceptionTypeStorage;
5826 return Result;
5827 }
5828
5829 case EST_Unevaluated:
5830 case EST_Uninstantiated:
5831 case EST_Unparsed:
5832 llvm_unreachable("shouldn't see unresolved exception specifications here")::llvm::llvm_unreachable_internal("shouldn't see unresolved exception specifications here"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5832)
;
5833 }
5834
5835 llvm_unreachable("invalid ExceptionSpecificationType")::llvm::llvm_unreachable_internal("invalid ExceptionSpecificationType"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5835)
;
5836}
5837
5838/// \brief Find a merged pointer type and convert the two expressions to it.
5839///
5840/// This finds the composite pointer type (or member pointer type) for @p E1
5841/// and @p E2 according to C++1z 5p14. It converts both expressions to this
5842/// type and returns it.
5843/// It does not emit diagnostics.
5844///
5845/// \param Loc The location of the operator requiring these two expressions to
5846/// be converted to the composite pointer type.
5847///
5848/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
5849QualType Sema::FindCompositePointerType(SourceLocation Loc,
5850 Expr *&E1, Expr *&E2,
5851 bool ConvertArgs) {
5852 assert(getLangOpts().CPlusPlus && "This function assumes C++")(static_cast <bool> (getLangOpts().CPlusPlus &&
"This function assumes C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"This function assumes C++\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5852, __extension__ __PRETTY_FUNCTION__))
;
5853
5854 // C++1z [expr]p14:
5855 // The composite pointer type of two operands p1 and p2 having types T1
5856 // and T2
5857 QualType T1 = E1->getType(), T2 = E2->getType();
5858
5859 // where at least one is a pointer or pointer to member type or
5860 // std::nullptr_t is:
5861 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5862 T1->isNullPtrType();
5863 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5864 T2->isNullPtrType();
5865 if (!T1IsPointerLike && !T2IsPointerLike)
5866 return QualType();
5867
5868 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5869 // This can't actually happen, following the standard, but we also use this
5870 // to implement the end of [expr.conv], which hits this case.
5871 //
5872 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5873 if (T1IsPointerLike &&
5874 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5875 if (ConvertArgs)
5876 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5877 ? CK_NullToMemberPointer
5878 : CK_NullToPointer).get();
5879 return T1;
5880 }
5881 if (T2IsPointerLike &&
5882 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5883 if (ConvertArgs)
5884 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5885 ? CK_NullToMemberPointer
5886 : CK_NullToPointer).get();
5887 return T2;
5888 }
5889
5890 // Now both have to be pointers or member pointers.
5891 if (!T1IsPointerLike || !T2IsPointerLike)
5892 return QualType();
5893 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&(static_cast <bool> (!T1->isNullPtrType() &&
!T2->isNullPtrType() && "nullptr_t should be a null pointer constant"
) ? void (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5894, __extension__ __PRETTY_FUNCTION__))
5894 "nullptr_t should be a null pointer constant")(static_cast <bool> (!T1->isNullPtrType() &&
!T2->isNullPtrType() && "nullptr_t should be a null pointer constant"
) ? void (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5894, __extension__ __PRETTY_FUNCTION__))
;
5895
5896 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5897 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5898 // the union of cv1 and cv2;
5899 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5900 // "pointer to function", where the function types are otherwise the same,
5901 // "pointer to function";
5902 // FIXME: This rule is defective: it should also permit removing noexcept
5903 // from a pointer to member function. As a Clang extension, we also
5904 // permit removing 'noreturn', so we generalize this rule to;
5905 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5906 // "pointer to member function" and the pointee types can be unified
5907 // by a function pointer conversion, that conversion is applied
5908 // before checking the following rules.
5909 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5910 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5911 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5912 // respectively;
5913 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5914 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5915 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5916 // T1 or the cv-combined type of T1 and T2, respectively;
5917 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5918 // T2;
5919 //
5920 // If looked at in the right way, these bullets all do the same thing.
5921 // What we do here is, we build the two possible cv-combined types, and try
5922 // the conversions in both directions. If only one works, or if the two
5923 // composite types are the same, we have succeeded.
5924 // FIXME: extended qualifiers?
5925 //
5926 // Note that this will fail to find a composite pointer type for "pointer
5927 // to void" and "pointer to function". We can't actually perform the final
5928 // conversion in this case, even though a composite pointer type formally
5929 // exists.
5930 SmallVector<unsigned, 4> QualifierUnion;
5931 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
5932 QualType Composite1 = T1;
5933 QualType Composite2 = T2;
5934 unsigned NeedConstBefore = 0;
5935 while (true) {
5936 const PointerType *Ptr1, *Ptr2;
5937 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5938 (Ptr2 = Composite2->getAs<PointerType>())) {
5939 Composite1 = Ptr1->getPointeeType();
5940 Composite2 = Ptr2->getPointeeType();
5941
5942 // If we're allowed to create a non-standard composite type, keep track
5943 // of where we need to fill in additional 'const' qualifiers.
5944 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5945 NeedConstBefore = QualifierUnion.size();
5946
5947 QualifierUnion.push_back(
5948 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5949 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
5950 continue;
5951 }
5952
5953 const MemberPointerType *MemPtr1, *MemPtr2;
5954 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5955 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5956 Composite1 = MemPtr1->getPointeeType();
5957 Composite2 = MemPtr2->getPointeeType();
5958
5959 // If we're allowed to create a non-standard composite type, keep track
5960 // of where we need to fill in additional 'const' qualifiers.
5961 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5962 NeedConstBefore = QualifierUnion.size();
5963
5964 QualifierUnion.push_back(
5965 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5966 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5967 MemPtr2->getClass()));
5968 continue;
5969 }
5970
5971 // FIXME: block pointer types?
5972
5973 // Cannot unwrap any more types.
5974 break;
5975 }
5976
5977 // Apply the function pointer conversion to unify the types. We've already
5978 // unwrapped down to the function types, and we want to merge rather than
5979 // just convert, so do this ourselves rather than calling
5980 // IsFunctionConversion.
5981 //
5982 // FIXME: In order to match the standard wording as closely as possible, we
5983 // currently only do this under a single level of pointers. Ideally, we would
5984 // allow this in general, and set NeedConstBefore to the relevant depth on
5985 // the side(s) where we changed anything.
5986 if (QualifierUnion.size() == 1) {
5987 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5988 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5989 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5990 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5991
5992 // The result is noreturn if both operands are.
5993 bool Noreturn =
5994 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5995 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5996 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5997
5998 // The result is nothrow if both operands are.
5999 SmallVector<QualType, 8> ExceptionTypeStorage;
6000 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6001 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6002 ExceptionTypeStorage);
6003
6004 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6005 FPT1->getParamTypes(), EPI1);
6006 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6007 FPT2->getParamTypes(), EPI2);
6008 }
6009 }
6010 }
6011
6012 if (NeedConstBefore) {
6013 // Extension: Add 'const' to qualifiers that come before the first qualifier
6014 // mismatch, so that our (non-standard!) composite type meets the
6015 // requirements of C++ [conv.qual]p4 bullet 3.
6016 for (unsigned I = 0; I != NeedConstBefore; ++I)
6017 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
6018 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
6019 }
6020
6021 // Rewrap the composites as pointers or member pointers with the union CVRs.
6022 auto MOC = MemberOfClass.rbegin();
6023 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6024 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6025 auto Classes = *MOC++;
6026 if (Classes.first && Classes.second) {
6027 // Rebuild member pointer type
6028 Composite1 = Context.getMemberPointerType(
6029 Context.getQualifiedType(Composite1, Quals), Classes.first);
6030 Composite2 = Context.getMemberPointerType(
6031 Context.getQualifiedType(Composite2, Quals), Classes.second);
6032 } else {
6033 // Rebuild pointer type
6034 Composite1 =
6035 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6036 Composite2 =
6037 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
6038 }
6039 }
6040
6041 struct Conversion {
6042 Sema &S;
6043 Expr *&E1, *&E2;
6044 QualType Composite;
6045 InitializedEntity Entity;
6046 InitializationKind Kind;
6047 InitializationSequence E1ToC, E2ToC;
6048 bool Viable;
6049
6050 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6051 QualType Composite)
6052 : S(S), E1(E1), E2(E2), Composite(Composite),
6053 Entity(InitializedEntity::InitializeTemporary(Composite)),
6054 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6055 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6056 Viable(E1ToC && E2ToC) {}
6057
6058 bool perform() {
6059 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6060 if (E1Result.isInvalid())
6061 return true;
6062 E1 = E1Result.getAs<Expr>();
6063
6064 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6065 if (E2Result.isInvalid())
6066 return true;
6067 E2 = E2Result.getAs<Expr>();
6068
6069 return false;
6070 }
6071 };
6072
6073 // Try to convert to each composite pointer type.
6074 Conversion C1(*this, Loc, E1, E2, Composite1);
6075 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6076 if (ConvertArgs && C1.perform())
6077 return QualType();
6078 return C1.Composite;
6079 }
6080 Conversion C2(*this, Loc, E1, E2, Composite2);
6081
6082 if (C1.Viable == C2.Viable) {
6083 // Either Composite1 and Composite2 are viable and are different, or
6084 // neither is viable.
6085 // FIXME: How both be viable and different?
6086 return QualType();
6087 }
6088
6089 // Convert to the chosen type.
6090 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6091 return QualType();
6092
6093 return C1.Viable ? C1.Composite : C2.Composite;
6094}
6095
6096ExprResult Sema::MaybeBindToTemporary(Expr *E) {
6097 if (!E)
6098 return ExprError();
6099
6100 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?")(static_cast <bool> (!isa<CXXBindTemporaryExpr>(E
) && "Double-bound temporary?") ? void (0) : __assert_fail
("!isa<CXXBindTemporaryExpr>(E) && \"Double-bound temporary?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6100, __extension__ __PRETTY_FUNCTION__))
;
6101
6102 // If the result is a glvalue, we shouldn't bind it.
6103 if (!E->isRValue())
6104 return E;
6105
6106 // In ARC, calls that return a retainable type can return retained,
6107 // in which case we have to insert a consuming cast.
6108 if (getLangOpts().ObjCAutoRefCount &&
6109 E->getType()->isObjCRetainableType()) {
6110
6111 bool ReturnsRetained;
6112
6113 // For actual calls, we compute this by examining the type of the
6114 // called value.
6115 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6116 Expr *Callee = Call->getCallee()->IgnoreParens();
6117 QualType T = Callee->getType();
6118
6119 if (T == Context.BoundMemberTy) {
6120 // Handle pointer-to-members.
6121 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6122 T = BinOp->getRHS()->getType();
6123 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6124 T = Mem->getMemberDecl()->getType();
6125 }
6126
6127 if (const PointerType *Ptr = T->getAs<PointerType>())
6128 T = Ptr->getPointeeType();
6129 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6130 T = Ptr->getPointeeType();
6131 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6132 T = MemPtr->getPointeeType();
6133
6134 const FunctionType *FTy = T->getAs<FunctionType>();
6135 assert(FTy && "call to value not of function type?")(static_cast <bool> (FTy && "call to value not of function type?"
) ? void (0) : __assert_fail ("FTy && \"call to value not of function type?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6135, __extension__ __PRETTY_FUNCTION__))
;
6136 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6137
6138 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6139 // type always produce a +1 object.
6140 } else if (isa<StmtExpr>(E)) {
6141 ReturnsRetained = true;
6142
6143 // We hit this case with the lambda conversion-to-block optimization;
6144 // we don't want any extra casts here.
6145 } else if (isa<CastExpr>(E) &&
6146 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6147 return E;
6148
6149 // For message sends and property references, we try to find an
6150 // actual method. FIXME: we should infer retention by selector in
6151 // cases where we don't have an actual method.
6152 } else {
6153 ObjCMethodDecl *D = nullptr;
6154 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6155 D = Send->getMethodDecl();
6156 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6157 D = BoxedExpr->getBoxingMethod();
6158 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6159 // Don't do reclaims if we're using the zero-element array
6160 // constant.
6161 if (ArrayLit->getNumElements() == 0 &&
6162 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6163 return E;
6164
6165 D = ArrayLit->getArrayWithObjectsMethod();
6166 } else if (ObjCDictionaryLiteral *DictLit
6167 = dyn_cast<ObjCDictionaryLiteral>(E)) {
6168 // Don't do reclaims if we're using the zero-element dictionary
6169 // constant.
6170 if (DictLit->getNumElements() == 0 &&
6171 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6172 return E;
6173
6174 D = DictLit->getDictWithObjectsMethod();
6175 }
6176
6177 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6178
6179 // Don't do reclaims on performSelector calls; despite their
6180 // return type, the invoked method doesn't necessarily actually
6181 // return an object.
6182 if (!ReturnsRetained &&
6183 D && D->getMethodFamily() == OMF_performSelector)
6184 return E;
6185 }
6186
6187 // Don't reclaim an object of Class type.
6188 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6189 return E;
6190
6191 Cleanup.setExprNeedsCleanups(true);
6192
6193 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6194 : CK_ARCReclaimReturnedObject);
6195 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6196 VK_RValue);
6197 }
6198
6199 if (!getLangOpts().CPlusPlus)
6200 return E;
6201
6202 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6203 // a fast path for the common case that the type is directly a RecordType.
6204 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6205 const RecordType *RT = nullptr;
6206 while (!RT) {
6207 switch (T->getTypeClass()) {
6208 case Type::Record:
6209 RT = cast<RecordType>(T);
6210 break;
6211 case Type::ConstantArray:
6212 case Type::IncompleteArray:
6213 case Type::VariableArray:
6214 case Type::DependentSizedArray:
6215 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6216 break;
6217 default:
6218 return E;
6219 }
6220 }
6221
6222 // That should be enough to guarantee that this type is complete, if we're
6223 // not processing a decltype expression.
6224 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6225 if (RD->isInvalidDecl() || RD->isDependentContext())
6226 return E;
6227
6228 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
6229 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6230
6231 if (Destructor) {
6232 MarkFunctionReferenced(E->getExprLoc(), Destructor);
6233 CheckDestructorAccess(E->getExprLoc(), Destructor,
6234 PDiag(diag::err_access_dtor_temp)
6235 << E->getType());
6236 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6237 return ExprError();
6238
6239 // If destructor is trivial, we can avoid the extra copy.
6240 if (Destructor->isTrivial())
6241 return E;
6242
6243 // We need a cleanup, but we don't need to remember the temporary.
6244 Cleanup.setExprNeedsCleanups(true);
6245 }
6246
6247 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6248 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6249
6250 if (IsDecltype)
6251 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6252
6253 return Bind;
6254}
6255
6256ExprResult
6257Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6258 if (SubExpr.isInvalid())
6259 return ExprError();
6260
6261 return MaybeCreateExprWithCleanups(SubExpr.get());
6262}
6263
6264Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6265 assert(SubExpr && "subexpression can't be null!")(static_cast <bool> (SubExpr && "subexpression can't be null!"
) ? void (0) : __assert_fail ("SubExpr && \"subexpression can't be null!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6265, __extension__ __PRETTY_FUNCTION__))
;
6266
6267 CleanupVarDeclMarking();
6268
6269 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6270 assert(ExprCleanupObjects.size() >= FirstCleanup)(static_cast <bool> (ExprCleanupObjects.size() >= FirstCleanup
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() >= FirstCleanup"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6270, __extension__ __PRETTY_FUNCTION__))
;
6271 assert(Cleanup.exprNeedsCleanups() ||(static_cast <bool> (Cleanup.exprNeedsCleanups() || ExprCleanupObjects
.size() == FirstCleanup) ? void (0) : __assert_fail ("Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6272, __extension__ __PRETTY_FUNCTION__))
6272 ExprCleanupObjects.size() == FirstCleanup)(static_cast <bool> (Cleanup.exprNeedsCleanups() || ExprCleanupObjects
.size() == FirstCleanup) ? void (0) : __assert_fail ("Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6272, __extension__ __PRETTY_FUNCTION__))
;
6273 if (!Cleanup.exprNeedsCleanups())
6274 return SubExpr;
6275
6276 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6277 ExprCleanupObjects.size() - FirstCleanup);
6278
6279 auto *E = ExprWithCleanups::Create(
6280 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6281 DiscardCleanupsInEvaluationContext();
6282
6283 return E;
6284}
6285
6286Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6287 assert(SubStmt && "sub-statement can't be null!")(static_cast <bool> (SubStmt && "sub-statement can't be null!"
) ? void (0) : __assert_fail ("SubStmt && \"sub-statement can't be null!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6287, __extension__ __PRETTY_FUNCTION__))
;
6288
6289 CleanupVarDeclMarking();
6290
6291 if (!Cleanup.exprNeedsCleanups())
6292 return SubStmt;
6293
6294 // FIXME: In order to attach the temporaries, wrap the statement into
6295 // a StmtExpr; currently this is only used for asm statements.
6296 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6297 // a new AsmStmtWithTemporaries.
6298 CompoundStmt *CompStmt = CompoundStmt::Create(
6299 Context, SubStmt, SourceLocation(), SourceLocation());
6300 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6301 SourceLocation());
6302 return MaybeCreateExprWithCleanups(E);
6303}
6304
6305/// Process the expression contained within a decltype. For such expressions,
6306/// certain semantic checks on temporaries are delayed until this point, and
6307/// are omitted for the 'topmost' call in the decltype expression. If the
6308/// topmost call bound a temporary, strip that temporary off the expression.
6309ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6310 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression")(static_cast <bool> (ExprEvalContexts.back().IsDecltype
&& "not in a decltype expression") ? void (0) : __assert_fail
("ExprEvalContexts.back().IsDecltype && \"not in a decltype expression\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6310, __extension__ __PRETTY_FUNCTION__))
;
6311
6312 // C++11 [expr.call]p11:
6313 // If a function call is a prvalue of object type,
6314 // -- if the function call is either
6315 // -- the operand of a decltype-specifier, or
6316 // -- the right operand of a comma operator that is the operand of a
6317 // decltype-specifier,
6318 // a temporary object is not introduced for the prvalue.
6319
6320 // Recursively rebuild ParenExprs and comma expressions to strip out the
6321 // outermost CXXBindTemporaryExpr, if any.
6322 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6323 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6324 if (SubExpr.isInvalid())
6325 return ExprError();
6326 if (SubExpr.get() == PE->getSubExpr())
6327 return E;
6328 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6329 }
6330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6331 if (BO->getOpcode() == BO_Comma) {
6332 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6333 if (RHS.isInvalid())
6334 return ExprError();
6335 if (RHS.get() == BO->getRHS())
6336 return E;
6337 return new (Context) BinaryOperator(
6338 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6339 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6340 }
6341 }
6342
6343 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6344 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6345 : nullptr;
6346 if (TopCall)
6347 E = TopCall;
6348 else
6349 TopBind = nullptr;
6350
6351 // Disable the special decltype handling now.
6352 ExprEvalContexts.back().IsDecltype = false;
6353
6354 // In MS mode, don't perform any extra checking of call return types within a
6355 // decltype expression.
6356 if (getLangOpts().MSVCCompat)
6357 return E;
6358
6359 // Perform the semantic checks we delayed until this point.
6360 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6361 I != N; ++I) {
6362 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6363 if (Call == TopCall)
6364 continue;
6365
6366 if (CheckCallReturnType(Call->getCallReturnType(Context),
6367 Call->getLocStart(),
6368 Call, Call->getDirectCallee()))
6369 return ExprError();
6370 }
6371
6372 // Now all relevant types are complete, check the destructors are accessible
6373 // and non-deleted, and annotate them on the temporaries.
6374 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6375 I != N; ++I) {
6376 CXXBindTemporaryExpr *Bind =
6377 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6378 if (Bind == TopBind)
6379 continue;
6380
6381 CXXTemporary *Temp = Bind->getTemporary();
6382
6383 CXXRecordDecl *RD =
6384 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6385 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6386 Temp->setDestructor(Destructor);
6387
6388 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6389 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6390 PDiag(diag::err_access_dtor_temp)
6391 << Bind->getType());
6392 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6393 return ExprError();
6394
6395 // We need a cleanup, but we don't need to remember the temporary.
6396 Cleanup.setExprNeedsCleanups(true);
6397 }
6398
6399 // Possibly strip off the top CXXBindTemporaryExpr.
6400 return E;
6401}
6402
6403/// Note a set of 'operator->' functions that were used for a member access.
6404static void noteOperatorArrows(Sema &S,
6405 ArrayRef<FunctionDecl *> OperatorArrows) {
6406 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6407 // FIXME: Make this configurable?
6408 unsigned Limit = 9;
6409 if (OperatorArrows.size() > Limit) {
6410 // Produce Limit-1 normal notes and one 'skipping' note.
6411 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6412 SkipCount = OperatorArrows.size() - (Limit - 1);
6413 }
6414
6415 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6416 if (I == SkipStart) {
6417 S.Diag(OperatorArrows[I]->getLocation(),
6418 diag::note_operator_arrows_suppressed)
6419 << SkipCount;
6420 I += SkipCount;
6421 } else {
6422 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6423 << OperatorArrows[I]->getCallResultType();
6424 ++I;
6425 }
6426 }
6427}
6428
6429ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6430 SourceLocation OpLoc,
6431 tok::TokenKind OpKind,
6432 ParsedType &ObjectType,
6433 bool &MayBePseudoDestructor) {
6434 // Since this might be a postfix expression, get rid of ParenListExprs.
6435 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
6436 if (Result.isInvalid()) return ExprError();
6437 Base = Result.get();
6438
6439 Result = CheckPlaceholderExpr(Base);
6440 if (Result.isInvalid()) return ExprError();
6441 Base = Result.get();
6442
6443 QualType BaseType = Base->getType();
6444 MayBePseudoDestructor = false;
6445 if (BaseType->isDependentType()) {
6446 // If we have a pointer to a dependent type and are using the -> operator,
6447 // the object type is the type that the pointer points to. We might still
6448 // have enough information about that type to do something useful.
6449 if (OpKind == tok::arrow)
6450 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6451 BaseType = Ptr->getPointeeType();
6452
6453 ObjectType = ParsedType::make(BaseType);
6454 MayBePseudoDestructor = true;
6455 return Base;
6456 }
6457
6458 // C++ [over.match.oper]p8:
6459 // [...] When operator->returns, the operator-> is applied to the value
6460 // returned, with the original second operand.
6461 if (OpKind == tok::arrow) {
6462 QualType StartingType = BaseType;
6463 bool NoArrowOperatorFound = false;
6464 bool FirstIteration = true;
6465 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6466 // The set of types we've considered so far.
6467 llvm::SmallPtrSet<CanQualType,8> CTypes;
6468 SmallVector<FunctionDecl*, 8> OperatorArrows;
6469 CTypes.insert(Context.getCanonicalType(BaseType));
6470
6471 while (BaseType->isRecordType()) {
6472 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6473 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6474 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6475 noteOperatorArrows(*this, OperatorArrows);
6476 Diag(OpLoc, diag::note_operator_arrow_depth)
6477 << getLangOpts().ArrowDepth;
6478 return ExprError();
6479 }
6480
6481 Result = BuildOverloadedArrowExpr(
6482 S, Base, OpLoc,
6483 // When in a template specialization and on the first loop iteration,
6484 // potentially give the default diagnostic (with the fixit in a
6485 // separate note) instead of having the error reported back to here
6486 // and giving a diagnostic with a fixit attached to the error itself.
6487 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6488 ? nullptr
6489 : &NoArrowOperatorFound);
6490 if (Result.isInvalid()) {
6491 if (NoArrowOperatorFound) {
6492 if (FirstIteration) {
6493 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6494 << BaseType << 1 << Base->getSourceRange()
6495 << FixItHint::CreateReplacement(OpLoc, ".");
6496 OpKind = tok::period;
6497 break;
6498 }
6499 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6500 << BaseType << Base->getSourceRange();
6501 CallExpr *CE = dyn_cast<CallExpr>(Base);
6502 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
6503 Diag(CD->getLocStart(),
6504 diag::note_member_reference_arrow_from_operator_arrow);
6505 }
6506 }
6507 return ExprError();
6508 }
6509 Base = Result.get();
6510 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
6511 OperatorArrows.push_back(OpCall->getDirectCallee());
6512 BaseType = Base->getType();
6513 CanQualType CBaseType = Context.getCanonicalType(BaseType);
6514 if (!CTypes.insert(CBaseType).second) {
6515 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6516 noteOperatorArrows(*this, OperatorArrows);
6517 return ExprError();
6518 }
6519 FirstIteration = false;
6520 }
6521
6522 if (OpKind == tok::arrow &&
6523 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6524 BaseType = BaseType->getPointeeType();
6525 }
6526
6527 // Objective-C properties allow "." access on Objective-C pointer types,
6528 // so adjust the base type to the object type itself.
6529 if (BaseType->isObjCObjectPointerType())
6530 BaseType = BaseType->getPointeeType();
6531
6532 // C++ [basic.lookup.classref]p2:
6533 // [...] If the type of the object expression is of pointer to scalar
6534 // type, the unqualified-id is looked up in the context of the complete
6535 // postfix-expression.
6536 //
6537 // This also indicates that we could be parsing a pseudo-destructor-name.
6538 // Note that Objective-C class and object types can be pseudo-destructor
6539 // expressions or normal member (ivar or property) access expressions, and
6540 // it's legal for the type to be incomplete if this is a pseudo-destructor
6541 // call. We'll do more incomplete-type checks later in the lookup process,
6542 // so just skip this check for ObjC types.
6543 if (BaseType->isObjCObjectOrInterfaceType()) {
6544 ObjectType = ParsedType::make(BaseType);
6545 MayBePseudoDestructor = true;
6546 return Base;
6547 } else if (!BaseType->isRecordType()) {
6548 ObjectType = nullptr;
6549 MayBePseudoDestructor = true;
6550 return Base;
6551 }
6552
6553 // The object type must be complete (or dependent), or
6554 // C++11 [expr.prim.general]p3:
6555 // Unlike the object expression in other contexts, *this is not required to
6556 // be of complete type for purposes of class member access (5.2.5) outside
6557 // the member function body.
6558 if (!BaseType->isDependentType() &&
6559 !isThisOutsideMemberFunctionBody(BaseType) &&
6560 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6561 return ExprError();
6562
6563 // C++ [basic.lookup.classref]p2:
6564 // If the id-expression in a class member access (5.2.5) is an
6565 // unqualified-id, and the type of the object expression is of a class
6566 // type C (or of pointer to a class type C), the unqualified-id is looked
6567 // up in the scope of class C. [...]
6568 ObjectType = ParsedType::make(BaseType);
6569 return Base;
6570}
6571
6572static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6573 tok::TokenKind& OpKind, SourceLocation OpLoc) {
6574 if (Base->hasPlaceholderType()) {
6575 ExprResult result = S.CheckPlaceholderExpr(Base);
6576 if (result.isInvalid()) return true;
6577 Base = result.get();
6578 }
6579 ObjectType = Base->getType();
6580
6581 // C++ [expr.pseudo]p2:
6582 // The left-hand side of the dot operator shall be of scalar type. The
6583 // left-hand side of the arrow operator shall be of pointer to scalar type.
6584 // This scalar type is the object type.
6585 // Note that this is rather different from the normal handling for the
6586 // arrow operator.
6587 if (OpKind == tok::arrow) {
6588 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6589 ObjectType = Ptr->getPointeeType();
6590 } else if (!Base->isTypeDependent()) {
6591 // The user wrote "p->" when they probably meant "p."; fix it.
6592 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6593 << ObjectType << true
6594 << FixItHint::CreateReplacement(OpLoc, ".");
6595 if (S.isSFINAEContext())
6596 return true;
6597
6598 OpKind = tok::period;
6599 }
6600 }
6601
6602 return false;
6603}
6604
6605/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6606/// pointer objects.
6607static bool
6608canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6609 QualType DestructedType) {
6610 // If this is a record type, check if its destructor is callable.
6611 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6612 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6613 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6614 return false;
6615 }
6616
6617 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6618 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6619 DestructedType->isVectorType();
6620}
6621
6622ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6623 SourceLocation OpLoc,
6624 tok::TokenKind OpKind,
6625 const CXXScopeSpec &SS,
6626 TypeSourceInfo *ScopeTypeInfo,
6627 SourceLocation CCLoc,
6628 SourceLocation TildeLoc,
6629 PseudoDestructorTypeStorage Destructed) {
6630 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6631
6632 QualType ObjectType;
6633 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6634 return ExprError();
6635
6636 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6637 !ObjectType->isVectorType()) {
6638 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6639 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6640 else {
6641 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6642 << ObjectType << Base->getSourceRange();
6643 return ExprError();
6644 }
6645 }
6646
6647 // C++ [expr.pseudo]p2:
6648 // [...] The cv-unqualified versions of the object type and of the type
6649 // designated by the pseudo-destructor-name shall be the same type.
6650 if (DestructedTypeInfo) {
6651 QualType DestructedType = DestructedTypeInfo->getType();
6652 SourceLocation DestructedTypeStart
6653 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6654 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6655 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6656 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6657 // Foo *foo;
6658 // foo.~Foo();
6659 if (OpKind == tok::period && ObjectType->isPointerType() &&
6660 Context.hasSameUnqualifiedType(DestructedType,
6661 ObjectType->getPointeeType())) {
6662 auto Diagnostic =
6663 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6664 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
6665
6666 // Issue a fixit only when the destructor is valid.
6667 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6668 *this, DestructedType))
6669 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6670
6671 // Recover by setting the object type to the destructed type and the
6672 // operator to '->'.
6673 ObjectType = DestructedType;
6674 OpKind = tok::arrow;
6675 } else {
6676 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6677 << ObjectType << DestructedType << Base->getSourceRange()
6678 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6679
6680 // Recover by setting the destructed type to the object type.
6681 DestructedType = ObjectType;
6682 DestructedTypeInfo =
6683 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6684 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6685 }
6686 } else if (DestructedType.getObjCLifetime() !=
6687 ObjectType.getObjCLifetime()) {
6688
6689 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6690 // Okay: just pretend that the user provided the correctly-qualified
6691 // type.
6692 } else {
6693 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6694 << ObjectType << DestructedType << Base->getSourceRange()
6695 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6696 }
6697
6698 // Recover by setting the destructed type to the object type.
6699 DestructedType = ObjectType;
6700 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6701 DestructedTypeStart);
6702 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6703 }
6704 }
6705 }
6706
6707 // C++ [expr.pseudo]p2:
6708 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6709 // form
6710 //
6711 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6712 //
6713 // shall designate the same scalar type.
6714 if (ScopeTypeInfo) {
6715 QualType ScopeType = ScopeTypeInfo->getType();
6716 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6717 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6718
6719 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6720 diag::err_pseudo_dtor_type_mismatch)
6721 << ObjectType << ScopeType << Base->getSourceRange()
6722 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6723
6724 ScopeType = QualType();
6725 ScopeTypeInfo = nullptr;
6726 }
6727 }
6728
6729 Expr *Result
6730 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6731 OpKind == tok::arrow, OpLoc,
6732 SS.getWithLocInContext(Context),
6733 ScopeTypeInfo,
6734 CCLoc,
6735 TildeLoc,
6736 Destructed);
6737
6738 return Result;
6739}
6740
6741ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6742 SourceLocation OpLoc,
6743 tok::TokenKind OpKind,
6744 CXXScopeSpec &SS,
6745 UnqualifiedId &FirstTypeName,
6746 SourceLocation CCLoc,
6747 SourceLocation TildeLoc,
6748 UnqualifiedId &SecondTypeName) {
6749 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid first type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6751, __extension__ __PRETTY_FUNCTION__))
6750 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid first type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6751, __extension__ __PRETTY_FUNCTION__))
6751 "Invalid first type name in pseudo-destructor")(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid first type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6751, __extension__ __PRETTY_FUNCTION__))
;
6752 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid second type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6754, __extension__ __PRETTY_FUNCTION__))
6753 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid second type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6754, __extension__ __PRETTY_FUNCTION__))
6754 "Invalid second type name in pseudo-destructor")(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid second type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6754, __extension__ __PRETTY_FUNCTION__))
;
6755
6756 QualType ObjectType;
6757 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6758 return ExprError();
6759
6760 // Compute the object type that we should use for name lookup purposes. Only
6761 // record types and dependent types matter.
6762 ParsedType ObjectTypePtrForLookup;
6763 if (!SS.isSet()) {
6764 if (ObjectType->isRecordType())
6765 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
6766 else if (ObjectType->isDependentType())
6767 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
6768 }
6769
6770 // Convert the name of the type being destructed (following the ~) into a
6771 // type (with source-location information).
6772 QualType DestructedType;
6773 TypeSourceInfo *DestructedTypeInfo = nullptr;
6774 PseudoDestructorTypeStorage Destructed;
6775 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
6776 ParsedType T = getTypeName(*SecondTypeName.Identifier,
6777 SecondTypeName.StartLocation,
6778 S, &SS, true, false, ObjectTypePtrForLookup,
6779 /*IsCtorOrDtorName*/true);
6780 if (!T &&
6781 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6782 (!SS.isSet() && ObjectType->isDependentType()))) {
6783 // The name of the type being destroyed is a dependent name, and we
6784 // couldn't find anything useful in scope. Just store the identifier and
6785 // it's location, and we'll perform (qualified) name lookup again at
6786 // template instantiation time.
6787 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6788 SecondTypeName.StartLocation);
6789 } else if (!T) {
6790 Diag(SecondTypeName.StartLocation,
6791 diag::err_pseudo_dtor_destructor_non_type)
6792 << SecondTypeName.Identifier << ObjectType;
6793 if (isSFINAEContext())
6794 return ExprError();
6795
6796 // Recover by assuming we had the right type all along.
6797 DestructedType = ObjectType;
6798 } else
6799 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
6800 } else {
6801 // Resolve the template-id to a type.
6802 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
6803 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6804 TemplateId->NumArgs);
6805 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6806 TemplateId->TemplateKWLoc,
6807 TemplateId->Template,
6808 TemplateId->Name,
6809 TemplateId->TemplateNameLoc,
6810 TemplateId->LAngleLoc,
6811 TemplateArgsPtr,
6812 TemplateId->RAngleLoc,
6813 /*IsCtorOrDtorName*/true);
6814 if (T.isInvalid() || !T.get()) {
6815 // Recover by assuming we had the right type all along.
6816 DestructedType = ObjectType;
6817 } else
6818 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
6819 }
6820
6821 // If we've performed some kind of recovery, (re-)build the type source
6822 // information.
6823 if (!DestructedType.isNull()) {
6824 if (!DestructedTypeInfo)
6825 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
6826 SecondTypeName.StartLocation);
6827 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6828 }
6829
6830 // Convert the name of the scope type (the type prior to '::') into a type.
6831 TypeSourceInfo *ScopeTypeInfo = nullptr;
6832 QualType ScopeType;
6833 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6834 FirstTypeName.Identifier) {
6835 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
6836 ParsedType T = getTypeName(*FirstTypeName.Identifier,
6837 FirstTypeName.StartLocation,
6838 S, &SS, true, false, ObjectTypePtrForLookup,
6839 /*IsCtorOrDtorName*/true);
6840 if (!T) {
6841 Diag(FirstTypeName.StartLocation,
6842 diag::err_pseudo_dtor_destructor_non_type)
6843 << FirstTypeName.Identifier << ObjectType;
6844
6845 if (isSFINAEContext())
6846 return ExprError();
6847
6848 // Just drop this type. It's unnecessary anyway.
6849 ScopeType = QualType();
6850 } else
6851 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
6852 } else {
6853 // Resolve the template-id to a type.
6854 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
6855 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6856 TemplateId->NumArgs);
6857 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6858 TemplateId->TemplateKWLoc,
6859 TemplateId->Template,
6860 TemplateId->Name,
6861 TemplateId->TemplateNameLoc,
6862 TemplateId->LAngleLoc,
6863 TemplateArgsPtr,
6864 TemplateId->RAngleLoc,
6865 /*IsCtorOrDtorName*/true);
6866 if (T.isInvalid() || !T.get()) {
6867 // Recover by dropping this type.
6868 ScopeType = QualType();
6869 } else
6870 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
6871 }
6872 }
6873
6874 if (!ScopeType.isNull() && !ScopeTypeInfo)
6875 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6876 FirstTypeName.StartLocation);
6877
6878
6879 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
6880 ScopeTypeInfo, CCLoc, TildeLoc,
6881 Destructed);
6882}
6883
6884ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6885 SourceLocation OpLoc,
6886 tok::TokenKind OpKind,
6887 SourceLocation TildeLoc,
6888 const DeclSpec& DS) {
6889 QualType ObjectType;
6890 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6891 return ExprError();
6892
6893 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6894 false);
6895
6896 TypeLocBuilder TLB;
6897 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6898 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6899 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6900 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6901
6902 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
6903 nullptr, SourceLocation(), TildeLoc,
6904 Destructed);
6905}
6906
6907ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
6908 CXXConversionDecl *Method,
6909 bool HadMultipleCandidates) {
6910 if (Method->getParent()->isLambda() &&
6911 Method->getConversionType()->isBlockPointerType()) {
6912 // This is a lambda coversion to block pointer; check if the argument
6913 // is a LambdaExpr.
6914 Expr *SubE = E;
6915 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6916 if (CE && CE->getCastKind() == CK_NoOp)
6917 SubE = CE->getSubExpr();
6918 SubE = SubE->IgnoreParens();
6919 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6920 SubE = BE->getSubExpr();
6921 if (isa<LambdaExpr>(SubE)) {
6922 // For the conversion to block pointer on a lambda expression, we
6923 // construct a special BlockLiteral instead; this doesn't really make
6924 // a difference in ARC, but outside of ARC the resulting block literal
6925 // follows the normal lifetime rules for block literals instead of being
6926 // autoreleased.
6927 DiagnosticErrorTrap Trap(Diags);
6928 PushExpressionEvaluationContext(
6929 ExpressionEvaluationContext::PotentiallyEvaluated);
6930 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6931 E->getExprLoc(),
6932 Method, E);
6933 PopExpressionEvaluationContext();
6934
6935 if (Exp.isInvalid())
6936 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6937 return Exp;
6938 }
6939 }
6940
6941 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
6942 FoundDecl, Method);
6943 if (Exp.isInvalid())
6944 return true;
6945
6946 MemberExpr *ME = new (Context) MemberExpr(
6947 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6948 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
6949 if (HadMultipleCandidates)
6950 ME->setHadMultipleCandidates(true);
6951 MarkMemberReferenced(ME);
6952
6953 QualType ResultType = Method->getReturnType();
6954 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6955 ResultType = ResultType.getNonLValueExprType(Context);
6956
6957 CXXMemberCallExpr *CE =
6958 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
6959 Exp.get()->getLocEnd());
6960
6961 if (CheckFunctionCall(Method, CE,
6962 Method->getType()->castAs<FunctionProtoType>()))
6963 return ExprError();
6964
6965 return CE;
6966}
6967
6968ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6969 SourceLocation RParen) {
6970 // If the operand is an unresolved lookup expression, the expression is ill-
6971 // formed per [over.over]p1, because overloaded function names cannot be used
6972 // without arguments except in explicit contexts.
6973 ExprResult R = CheckPlaceholderExpr(Operand);
6974 if (R.isInvalid())
6975 return R;
6976
6977 // The operand may have been modified when checking the placeholder type.
6978 Operand = R.get();
6979
6980 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
6981 // The expression operand for noexcept is in an unevaluated expression
6982 // context, so side effects could result in unintended consequences.
6983 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6984 }
6985
6986 CanThrowResult CanThrow = canThrow(Operand);
6987 return new (Context)
6988 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
6989}
6990
6991ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6992 Expr *Operand, SourceLocation RParen) {
6993 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
6994}
6995
6996static bool IsSpecialDiscardedValue(Expr *E) {
6997 // In C++11, discarded-value expressions of a certain form are special,
6998 // according to [expr]p10:
6999 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7000 // expression is an lvalue of volatile-qualified type and it has
7001 // one of the following forms:
7002 E = E->IgnoreParens();
7003
7004 // - id-expression (5.1.1),
7005 if (isa<DeclRefExpr>(E))
7006 return true;
7007
7008 // - subscripting (5.2.1),
7009 if (isa<ArraySubscriptExpr>(E))
7010 return true;
7011
7012 // - class member access (5.2.5),
7013 if (isa<MemberExpr>(E))
7014 return true;
7015
7016 // - indirection (5.3.1),
7017 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7018 if (UO->getOpcode() == UO_Deref)
7019 return true;
7020
7021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7022 // - pointer-to-member operation (5.5),
7023 if (BO->isPtrMemOp())
7024 return true;
7025
7026 // - comma expression (5.18) where the right operand is one of the above.
7027 if (BO->getOpcode() == BO_Comma)
7028 return IsSpecialDiscardedValue(BO->getRHS());
7029 }
7030
7031 // - conditional expression (5.16) where both the second and the third
7032 // operands are one of the above, or
7033 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7034 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7035 IsSpecialDiscardedValue(CO->getFalseExpr());
7036 // The related edge case of "*x ?: *x".
7037 if (BinaryConditionalOperator *BCO =
7038 dyn_cast<BinaryConditionalOperator>(E)) {
7039 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7040 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7041 IsSpecialDiscardedValue(BCO->getFalseExpr());
7042 }
7043
7044 // Objective-C++ extensions to the rule.
7045 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7046 return true;
7047
7048 return false;
7049}
7050
7051/// Perform the conversions required for an expression used in a
7052/// context that ignores the result.
7053ExprResult Sema::IgnoredValueConversions(Expr *E) {
7054 if (E->hasPlaceholderType()) {
7055 ExprResult result = CheckPlaceholderExpr(E);
7056 if (result.isInvalid()) return E;
7057 E = result.get();
7058 }
7059
7060 // C99 6.3.2.1:
7061 // [Except in specific positions,] an lvalue that does not have
7062 // array type is converted to the value stored in the
7063 // designated object (and is no longer an lvalue).
7064 if (E->isRValue()) {
7065 // In C, function designators (i.e. expressions of function type)
7066 // are r-values, but we still want to do function-to-pointer decay
7067 // on them. This is both technically correct and convenient for
7068 // some clients.
7069 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7070 return DefaultFunctionArrayConversion(E);
7071
7072 return E;
7073 }
7074
7075 if (getLangOpts().CPlusPlus) {
7076 // The C++11 standard defines the notion of a discarded-value expression;
7077 // normally, we don't need to do anything to handle it, but if it is a
7078 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7079 // conversion.
7080 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
7081 E->getType().isVolatileQualified() &&
7082 IsSpecialDiscardedValue(E)) {
7083 ExprResult Res = DefaultLvalueConversion(E);
7084 if (Res.isInvalid())
7085 return E;
7086 E = Res.get();
7087 }
7088
7089 // C++1z:
7090 // If the expression is a prvalue after this optional conversion, the
7091 // temporary materialization conversion is applied.
7092 //
7093 // We skip this step: IR generation is able to synthesize the storage for
7094 // itself in the aggregate case, and adding the extra node to the AST is
7095 // just clutter.
7096 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7097 // FIXME: Do any other AST consumers care about this?
7098 return E;
7099 }
7100
7101 // GCC seems to also exclude expressions of incomplete enum type.
7102 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7103 if (!T->getDecl()->isComplete()) {
7104 // FIXME: stupid workaround for a codegen bug!
7105 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7106 return E;
7107 }
7108 }
7109
7110 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7111 if (Res.isInvalid())
7112 return E;
7113 E = Res.get();
7114
7115 if (!E->getType()->isVoidType())
7116 RequireCompleteType(E->getExprLoc(), E->getType(),
7117 diag::err_incomplete_type);
7118 return E;
7119}
7120
7121// If we can unambiguously determine whether Var can never be used
7122// in a constant expression, return true.
7123// - if the variable and its initializer are non-dependent, then
7124// we can unambiguously check if the variable is a constant expression.
7125// - if the initializer is not value dependent - we can determine whether
7126// it can be used to initialize a constant expression. If Init can not
7127// be used to initialize a constant expression we conclude that Var can
7128// never be a constant expression.
7129// - FXIME: if the initializer is dependent, we can still do some analysis and
7130// identify certain cases unambiguously as non-const by using a Visitor:
7131// - such as those that involve odr-use of a ParmVarDecl, involve a new
7132// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7133static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7134 ASTContext &Context) {
7135 if (isa<ParmVarDecl>(Var)) return true;
7136 const VarDecl *DefVD = nullptr;
7137
7138 // If there is no initializer - this can not be a constant expression.
7139 if (!Var->getAnyInitializer(DefVD)) return true;
7140 assert(DefVD)(static_cast <bool> (DefVD) ? void (0) : __assert_fail (
"DefVD", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7140, __extension__ __PRETTY_FUNCTION__))
;
7141 if (DefVD->isWeak()) return false;
7142 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7143
7144 Expr *Init = cast<Expr>(Eval->Value);
7145
7146 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7147 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7148 // of value-dependent expressions, and use it here to determine whether the
7149 // initializer is a potential constant expression.
7150 return false;
7151 }
7152
7153 return !IsVariableAConstantExpression(Var, Context);
7154}
7155
7156/// \brief Check if the current lambda has any potential captures
7157/// that must be captured by any of its enclosing lambdas that are ready to
7158/// capture. If there is a lambda that can capture a nested
7159/// potential-capture, go ahead and do so. Also, check to see if any
7160/// variables are uncaptureable or do not involve an odr-use so do not
7161/// need to be captured.
7162
7163static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7164 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7165
7166 assert(!S.isUnevaluatedContext())(static_cast <bool> (!S.isUnevaluatedContext()) ? void (
0) : __assert_fail ("!S.isUnevaluatedContext()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7166, __extension__ __PRETTY_FUNCTION__))
;
7167 assert(S.CurContext->isDependentContext())(static_cast <bool> (S.CurContext->isDependentContext
()) ? void (0) : __assert_fail ("S.CurContext->isDependentContext()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7167, __extension__ __PRETTY_FUNCTION__))
;
7168#ifndef NDEBUG
7169 DeclContext *DC = S.CurContext;
7170 while (DC && isa<CapturedDecl>(DC))
7171 DC = DC->getParent();
7172 assert((static_cast <bool> (CurrentLSI->CallOperator == DC &&
"The current call operator must be synchronized with Sema's CurContext"
) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7174, __extension__ __PRETTY_FUNCTION__))
7173 CurrentLSI->CallOperator == DC &&(static_cast <bool> (CurrentLSI->CallOperator == DC &&
"The current call operator must be synchronized with Sema's CurContext"
) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7174, __extension__ __PRETTY_FUNCTION__))
7174 "The current call operator must be synchronized with Sema's CurContext")(static_cast <bool> (CurrentLSI->CallOperator == DC &&
"The current call operator must be synchronized with Sema's CurContext"
) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7174, __extension__ __PRETTY_FUNCTION__))
;
7175#endif // NDEBUG
7176
7177 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7178
7179 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7180 S.FunctionScopes.data(), S.FunctionScopes.size());
7181
7182 // All the potentially captureable variables in the current nested
7183 // lambda (within a generic outer lambda), must be captured by an
7184 // outer lambda that is enclosed within a non-dependent context.
7185 const unsigned NumPotentialCaptures =
7186 CurrentLSI->getNumPotentialVariableCaptures();
7187 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
7188 Expr *VarExpr = nullptr;
7189 VarDecl *Var = nullptr;
7190 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
7191 // If the variable is clearly identified as non-odr-used and the full
7192 // expression is not instantiation dependent, only then do we not
7193 // need to check enclosing lambda's for speculative captures.
7194 // For e.g.:
7195 // Even though 'x' is not odr-used, it should be captured.
7196 // int test() {
7197 // const int x = 10;
7198 // auto L = [=](auto a) {
7199 // (void) +x + a;
7200 // };
7201 // }
7202 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7203 !IsFullExprInstantiationDependent)
7204 continue;
7205
7206 // If we have a capture-capable lambda for the variable, go ahead and
7207 // capture the variable in that lambda (and all its enclosing lambdas).
7208 if (const Optional<unsigned> Index =
7209 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7210 FunctionScopesArrayRef, Var, S)) {
7211 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7212 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7213 &FunctionScopeIndexOfCapturableLambda);
7214 }
7215 const bool IsVarNeverAConstantExpression =
7216 VariableCanNeverBeAConstantExpression(Var, S.Context);
7217 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7218 // This full expression is not instantiation dependent or the variable
7219 // can not be used in a constant expression - which means
7220 // this variable must be odr-used here, so diagnose a
7221 // capture violation early, if the variable is un-captureable.
7222 // This is purely for diagnosing errors early. Otherwise, this
7223 // error would get diagnosed when the lambda becomes capture ready.
7224 QualType CaptureType, DeclRefType;
7225 SourceLocation ExprLoc = VarExpr->getExprLoc();
7226 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7227 /*EllipsisLoc*/ SourceLocation(),
7228 /*BuildAndDiagnose*/false, CaptureType,
7229 DeclRefType, nullptr)) {
7230 // We will never be able to capture this variable, and we need
7231 // to be able to in any and all instantiations, so diagnose it.
7232 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7233 /*EllipsisLoc*/ SourceLocation(),
7234 /*BuildAndDiagnose*/true, CaptureType,
7235 DeclRefType, nullptr);
7236 }
7237 }
7238 }
7239
7240 // Check if 'this' needs to be captured.
7241 if (CurrentLSI->hasPotentialThisCapture()) {
7242 // If we have a capture-capable lambda for 'this', go ahead and capture
7243 // 'this' in that lambda (and all its enclosing lambdas).
7244 if (const Optional<unsigned> Index =
7245 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7246 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
7247 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7248 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7249 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7250 &FunctionScopeIndexOfCapturableLambda);
7251 }
7252 }
7253
7254 // Reset all the potential captures at the end of each full-expression.
7255 CurrentLSI->clearPotentialCaptures();
7256}
7257
7258static ExprResult attemptRecovery(Sema &SemaRef,
7259 const TypoCorrectionConsumer &Consumer,
7260 const TypoCorrection &TC) {
7261 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7262 Consumer.getLookupResult().getLookupKind());
7263 const CXXScopeSpec *SS = Consumer.getSS();
7264 CXXScopeSpec NewSS;
7265
7266 // Use an approprate CXXScopeSpec for building the expr.
7267 if (auto *NNS = TC.getCorrectionSpecifier())
7268 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7269 else if (SS && !TC.WillReplaceSpecifier())
7270 NewSS = *SS;
7271
7272 if (auto *ND = TC.getFoundDecl()) {
7273 R.setLookupName(ND->getDeclName());
7274 R.addDecl(ND);
7275 if (ND->isCXXClassMember()) {
7276 // Figure out the correct naming class to add to the LookupResult.
7277 CXXRecordDecl *Record = nullptr;
7278 if (auto *NNS = TC.getCorrectionSpecifier())
7279 Record = NNS->getAsType()->getAsCXXRecordDecl();
7280 if (!Record)
7281 Record =
7282 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7283 if (Record)
7284 R.setNamingClass(Record);
7285
7286 // Detect and handle the case where the decl might be an implicit
7287 // member.
7288 bool MightBeImplicitMember;
7289 if (!Consumer.isAddressOfOperand())
7290 MightBeImplicitMember = true;
7291 else if (!NewSS.isEmpty())
7292 MightBeImplicitMember = false;
7293 else if (R.isOverloadedResult())
7294 MightBeImplicitMember = false;
7295 else if (R.isUnresolvableResult())
7296 MightBeImplicitMember = true;
7297 else
7298 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7299 isa<IndirectFieldDecl>(ND) ||
7300 isa<MSPropertyDecl>(ND);
7301
7302 if (MightBeImplicitMember)
7303 return SemaRef.BuildPossibleImplicitMemberExpr(
7304 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7305 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7306 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7307 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7308 Ivar->getIdentifier());
7309 }
7310 }
7311
7312 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7313 /*AcceptInvalidDecl*/ true);
7314}
7315
7316namespace {
7317class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7318 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7319
7320public:
7321 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7322 : TypoExprs(TypoExprs) {}
7323 bool VisitTypoExpr(TypoExpr *TE) {
7324 TypoExprs.insert(TE);
7325 return true;
7326 }
7327};
7328
7329class TransformTypos : public TreeTransform<TransformTypos> {
7330 typedef TreeTransform<TransformTypos> BaseTransform;
7331
7332 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7333 // process of being initialized.
7334 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7335 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7336 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7337 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7338
7339 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7340 /// If the TypoExprs were successfully corrected, then the diagnostics should
7341 /// suggest the corrections. Otherwise the diagnostics will not suggest
7342 /// anything (having been passed an empty TypoCorrection).
7343 void EmitAllDiagnostics() {
7344 for (TypoExpr *TE : TypoExprs) {
7345 auto &State = SemaRef.getTypoExprState(TE);
7346 if (State.DiagHandler) {
7347 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7348 ExprResult Replacement = TransformCache[TE];
7349
7350 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7351 // TypoCorrection, replacing the existing decls. This ensures the right
7352 // NamedDecl is used in diagnostics e.g. in the case where overload
7353 // resolution was used to select one from several possible decls that
7354 // had been stored in the TypoCorrection.
7355 if (auto *ND = getDeclFromExpr(
7356 Replacement.isInvalid() ? nullptr : Replacement.get()))
7357 TC.setCorrectionDecl(ND);
7358
7359 State.DiagHandler(TC);
7360 }
7361 SemaRef.clearDelayedTypo(TE);
7362 }
7363 }
7364
7365 /// \brief If corrections for the first TypoExpr have been exhausted for a
7366 /// given combination of the other TypoExprs, retry those corrections against
7367 /// the next combination of substitutions for the other TypoExprs by advancing
7368 /// to the next potential correction of the second TypoExpr. For the second
7369 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7370 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7371 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7372 /// TransformCache). Returns true if there is still any untried combinations
7373 /// of corrections.
7374 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7375 for (auto TE : TypoExprs) {
7376 auto &State = SemaRef.getTypoExprState(TE);
7377 TransformCache.erase(TE);
7378 if (!State.Consumer->finished())
7379 return true;
7380 State.Consumer->resetCorrectionStream();
7381 }
7382 return false;
7383 }
7384
7385 NamedDecl *getDeclFromExpr(Expr *E) {
7386 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7387 E = OverloadResolution[OE];
7388
7389 if (!E)
7390 return nullptr;
7391 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7392 return DRE->getFoundDecl();
7393 if (auto *ME = dyn_cast<MemberExpr>(E))
7394 return ME->getFoundDecl();
7395 // FIXME: Add any other expr types that could be be seen by the delayed typo
7396 // correction TreeTransform for which the corresponding TypoCorrection could
7397 // contain multiple decls.
7398 return nullptr;
7399 }
7400
7401 ExprResult TryTransform(Expr *E) {
7402 Sema::SFINAETrap Trap(SemaRef);
7403 ExprResult Res = TransformExpr(E);
7404 if (Trap.hasErrorOccurred() || Res.isInvalid())
7405 return ExprError();
7406
7407 return ExprFilter(Res.get());
7408 }
7409
7410public:
7411 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7412 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
7413
7414 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7415 MultiExprArg Args,
7416 SourceLocation RParenLoc,
7417 Expr *ExecConfig = nullptr) {
7418 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7419 RParenLoc, ExecConfig);
7420 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
7421 if (Result.isUsable()) {
7422 Expr *ResultCall = Result.get();
7423 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7424 ResultCall = BE->getSubExpr();
7425 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7426 OverloadResolution[OE] = CE->getCallee();
7427 }
7428 }
7429 return Result;
7430 }
7431
7432 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7433
7434 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7435
7436 ExprResult Transform(Expr *E) {
7437 ExprResult Res;
7438 while (true) {
7439 Res = TryTransform(E);
7440
7441 // Exit if either the transform was valid or if there were no TypoExprs
7442 // to transform that still have any untried correction candidates..
7443 if (!Res.isInvalid() ||
7444 !CheckAndAdvanceTypoExprCorrectionStreams())
7445 break;
7446 }
7447
7448 // Ensure none of the TypoExprs have multiple typo correction candidates
7449 // with the same edit length that pass all the checks and filters.
7450 // TODO: Properly handle various permutations of possible corrections when
7451 // there is more than one potentially ambiguous typo correction.
7452 // Also, disable typo correction while attempting the transform when
7453 // handling potentially ambiguous typo corrections as any new TypoExprs will
7454 // have been introduced by the application of one of the correction
7455 // candidates and add little to no value if corrected.
7456 SemaRef.DisableTypoCorrection = true;
7457 while (!AmbiguousTypoExprs.empty()) {
7458 auto TE = AmbiguousTypoExprs.back();
7459 auto Cached = TransformCache[TE];
7460 auto &State = SemaRef.getTypoExprState(TE);
7461 State.Consumer->saveCurrentPosition();
7462 TransformCache.erase(TE);
7463 if (!TryTransform(E).isInvalid()) {
7464 State.Consumer->resetCorrectionStream();
7465 TransformCache.erase(TE);
7466 Res = ExprError();
7467 break;
7468 }
7469 AmbiguousTypoExprs.remove(TE);
7470 State.Consumer->restoreSavedPosition();
7471 TransformCache[TE] = Cached;
7472 }
7473 SemaRef.DisableTypoCorrection = false;
7474
7475 // Ensure that all of the TypoExprs within the current Expr have been found.
7476 if (!Res.isUsable())
7477 FindTypoExprs(TypoExprs).TraverseStmt(E);
7478
7479 EmitAllDiagnostics();
7480
7481 return Res;
7482 }
7483
7484 ExprResult TransformTypoExpr(TypoExpr *E) {
7485 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7486 // cached transformation result if there is one and the TypoExpr isn't the
7487 // first one that was encountered.
7488 auto &CacheEntry = TransformCache[E];
7489 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7490 return CacheEntry;
7491 }
7492
7493 auto &State = SemaRef.getTypoExprState(E);
7494 assert(State.Consumer && "Cannot transform a cleared TypoExpr")(static_cast <bool> (State.Consumer && "Cannot transform a cleared TypoExpr"
) ? void (0) : __assert_fail ("State.Consumer && \"Cannot transform a cleared TypoExpr\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7494, __extension__ __PRETTY_FUNCTION__))
;
7495
7496 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7497 // typo correction and return it.
7498 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
7499 if (InitDecl && TC.getFoundDecl() == InitDecl)
7500 continue;
7501 // FIXME: If we would typo-correct to an invalid declaration, it's
7502 // probably best to just suppress all errors from this typo correction.
7503 ExprResult NE = State.RecoveryHandler ?
7504 State.RecoveryHandler(SemaRef, E, TC) :
7505 attemptRecovery(SemaRef, *State.Consumer, TC);
7506 if (!NE.isInvalid()) {
7507 // Check whether there may be a second viable correction with the same
7508 // edit distance; if so, remember this TypoExpr may have an ambiguous
7509 // correction so it can be more thoroughly vetted later.
7510 TypoCorrection Next;
7511 if ((Next = State.Consumer->peekNextCorrection()) &&
7512 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7513 AmbiguousTypoExprs.insert(E);
7514 } else {
7515 AmbiguousTypoExprs.remove(E);
7516 }
7517 assert(!NE.isUnset() &&(static_cast <bool> (!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult"
) ? void (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7518, __extension__ __PRETTY_FUNCTION__))
7518 "Typo was transformed into a valid-but-null ExprResult")(static_cast <bool> (!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult"
) ? void (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7518, __extension__ __PRETTY_FUNCTION__))
;
7519 return CacheEntry = NE;
7520 }
7521 }
7522 return CacheEntry = ExprError();
7523 }
7524};
7525}
7526
7527ExprResult
7528Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7529 llvm::function_ref<ExprResult(Expr *)> Filter) {
7530 // If the current evaluation context indicates there are uncorrected typos
7531 // and the current expression isn't guaranteed to not have typos, try to
7532 // resolve any TypoExpr nodes that might be in the expression.
7533 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
7534 (E->isTypeDependent() || E->isValueDependent() ||
7535 E->isInstantiationDependent())) {
7536 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7537 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr")(static_cast <bool> (TyposInContext < ~0U &&
"Recursive call of CorrectDelayedTyposInExpr") ? void (0) : __assert_fail
("TyposInContext < ~0U && \"Recursive call of CorrectDelayedTyposInExpr\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7537, __extension__ __PRETTY_FUNCTION__))
;
7538 ExprEvalContexts.back().NumTypos = ~0U;
7539 auto TyposResolved = DelayedTypos.size();
7540 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
7541 ExprEvalContexts.back().NumTypos = TyposInContext;
7542 TyposResolved -= DelayedTypos.size();
7543 if (Result.isInvalid() || Result.get() != E) {
7544 ExprEvalContexts.back().NumTypos -= TyposResolved;
7545 return Result;
7546 }
7547 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?")(static_cast <bool> (TyposResolved == 0 && "Corrected typo but got same Expr back?"
) ? void (0) : __assert_fail ("TyposResolved == 0 && \"Corrected typo but got same Expr back?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7547, __extension__ __PRETTY_FUNCTION__))
;
7548 }
7549 return E;
7550}
7551
7552ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
7553 bool DiscardedValue,
7554 bool IsConstexpr,
7555 bool IsLambdaInitCaptureInitializer) {
7556 ExprResult FullExpr = FE;
7557
7558 if (!FullExpr.get())
7559 return ExprError();
7560
7561 // If we are an init-expression in a lambdas init-capture, we should not
7562 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
7563 // containing full-expression is done).
7564 // template<class ... Ts> void test(Ts ... t) {
7565 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7566 // return a;
7567 // }() ...);
7568 // }
7569 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7570 // when we parse the lambda introducer, and teach capturing (but not
7571 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7572 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7573 // lambda where we've entered the introducer but not the body, or represent a
7574 // lambda where we've entered the body, depending on where the
7575 // parser/instantiation has got to).
7576 if (!IsLambdaInitCaptureInitializer &&
7577 DiagnoseUnexpandedParameterPack(FullExpr.get()))
7578 return ExprError();
7579
7580 // Top-level expressions default to 'id' when we're in a debugger.
7581 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
7582 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7583 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7584 if (FullExpr.isInvalid())
7585 return ExprError();
7586 }
7587
7588 if (DiscardedValue) {
7589 FullExpr = CheckPlaceholderExpr(FullExpr.get());
7590 if (FullExpr.isInvalid())
7591 return ExprError();
7592
7593 FullExpr = IgnoredValueConversions(FullExpr.get());
7594 if (FullExpr.isInvalid())
7595 return ExprError();
7596 }
7597
7598 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7599 if (FullExpr.isInvalid())
7600 return ExprError();
7601
7602 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7603
7604 // At the end of this full expression (which could be a deeply nested
7605 // lambda), if there is a potential capture within the nested lambda,
7606 // have the outer capture-able lambda try and capture it.
7607 // Consider the following code:
7608 // void f(int, int);
7609 // void f(const int&, double);
7610 // void foo() {
7611 // const int x = 10, y = 20;
7612 // auto L = [=](auto a) {
7613 // auto M = [=](auto b) {
7614 // f(x, b); <-- requires x to be captured by L and M
7615 // f(y, a); <-- requires y to be captured by L, but not all Ms
7616 // };
7617 // };
7618 // }
7619
7620 // FIXME: Also consider what happens for something like this that involves
7621 // the gnu-extension statement-expressions or even lambda-init-captures:
7622 // void f() {
7623 // const int n = 0;
7624 // auto L = [&](auto a) {
7625 // +n + ({ 0; a; });
7626 // };
7627 // }
7628 //
7629 // Here, we see +n, and then the full-expression 0; ends, so we don't
7630 // capture n (and instead remove it from our list of potential captures),
7631 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7632 // for us to see that we need to capture n after all.
7633
7634 LambdaScopeInfo *const CurrentLSI =
7635 getCurLambda(/*IgnoreCapturedRegions=*/true);
7636 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7637 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7638 // for an example of the code that might cause this asynchrony.
7639 // By ensuring we are in the context of a lambda's call operator
7640 // we can fix the bug (we only need to check whether we need to capture
7641 // if we are within a lambda's body); but per the comments in that
7642 // PR, a proper fix would entail :
7643 // "Alternative suggestion:
7644 // - Add to Sema an integer holding the smallest (outermost) scope
7645 // index that we are *lexically* within, and save/restore/set to
7646 // FunctionScopes.size() in InstantiatingTemplate's
7647 // constructor/destructor.
7648 // - Teach the handful of places that iterate over FunctionScopes to
7649 // stop at the outermost enclosing lexical scope."
7650 DeclContext *DC = CurContext;
7651 while (DC && isa<CapturedDecl>(DC))
7652 DC = DC->getParent();
7653 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7654 if (IsInLambdaDeclContext && CurrentLSI &&
7655 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7656 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7657 *this);
7658 return MaybeCreateExprWithCleanups(FullExpr);
7659}
7660
7661StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7662 if (!FullStmt) return StmtError();
7663
7664 return MaybeCreateStmtWithCleanups(FullStmt);
7665}
7666
7667Sema::IfExistsResult
7668Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7669 CXXScopeSpec &SS,
7670 const DeclarationNameInfo &TargetNameInfo) {
7671 DeclarationName TargetName = TargetNameInfo.getName();
7672 if (!TargetName)
7673 return IER_DoesNotExist;
7674
7675 // If the name itself is dependent, then the result is dependent.
7676 if (TargetName.isDependentName())
7677 return IER_Dependent;
7678
7679 // Do the redeclaration lookup in the current scope.
7680 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7681 Sema::NotForRedeclaration);
7682 LookupParsedName(R, S, &SS);
7683 R.suppressDiagnostics();
7684
7685 switch (R.getResultKind()) {
7686 case LookupResult::Found:
7687 case LookupResult::FoundOverloaded:
7688 case LookupResult::FoundUnresolvedValue:
7689 case LookupResult::Ambiguous:
7690 return IER_Exists;
7691
7692 case LookupResult::NotFound:
7693 return IER_DoesNotExist;
7694
7695 case LookupResult::NotFoundInCurrentInstantiation:
7696 return IER_Dependent;
7697 }
7698
7699 llvm_unreachable("Invalid LookupResult Kind!")::llvm::llvm_unreachable_internal("Invalid LookupResult Kind!"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7699)
;
7700}
7701
7702Sema::IfExistsResult
7703Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7704 bool IsIfExists, CXXScopeSpec &SS,
7705 UnqualifiedId &Name) {
7706 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7707
7708 // Check for an unexpanded parameter pack.
7709 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7710 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7711 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7712 return IER_Error;
7713
7714 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7715}

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h

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
62namespace 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
70namespace 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
201namespace 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
216namespace 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.
223typedef 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.
228struct 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.
246class 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
256public:
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.
275class 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
307public:
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
1184public:
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
1533private:
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
1552public:
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
1893private:
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
1898public:
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
3108private:
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
3150public:
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
3539private:
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
3550public:
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
3572private:
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
3588public:
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.
3635public:
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
4396private:
4397 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4398
4399public:
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 //
8520private:
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;
8526public:
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 //
8572private:
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
8610public:
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 &paramType);
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
9874private:
9875 unsigned ForceCUDAHostDeviceDepth = 0;
9876
9877public:
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())
8
Assuming the condition is false
9
Taking false branch
9979 *Diag.ImmediateDiag << Value;
9980 else if (Diag.PartialDiag.hasValue())
10
Assuming the condition is true
11
Taking true branch
9981 *Diag.PartialDiag << Value;
12
Calling 'operator<<'
23
Returned allocated memory
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
10082public:
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
10303public:
10304 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10305 unsigned ByteNo) const;
10306
10307private:
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
10365public:
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
10372private:
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);
10392public:
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
10411private:
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
10446public:
10447 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
10448
10449private:
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);
10479public:
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
10505private:
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
10541protected:
10542 friend class Parser;
10543 friend class InitializationSequence;
10544 friend class ASTReader;
10545 friend class ASTDeclReader;
10546 friend class ASTWriter;
10547
10548public:
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
10603private:
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
10659public:
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.
10682class EnterExpressionEvaluationContext {
10683 Sema &Actions;
10684 bool Entered = true;
10685
10686public:
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
10730DeductionFailureInfo
10731MakeDeductionFailureInfo(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.
10736struct LateParsedTemplate {
10737 CachedTokens Toks;
10738 /// \brief The template function declaration to be late parsed.
10739 Decl *D;
10740};
10741
10742} // end namespace clang
10743
10744namespace llvm {
10745// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10746// SourceLocation.
10747template <> 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

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h

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
30namespace clang {
31
32class DeclContext;
33class IdentifierInfo;
34
35class PartialDiagnostic {
36public:
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
118private:
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)
17
Taking false branch
135 return DiagStorage;
136
137 if (Allocator)
18
Assuming the condition is false
19
Taking false branch
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;
20
Memory is allocated
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
184public:
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)
14
Assuming the condition is true
15
Taking true branch
273 DiagStorage = getStorage();
16
Calling 'PartialDiagnostic::getStorage'
21
Returned allocated memory
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),
13
Calling 'PartialDiagnostic::AddTaggedVal'
22
Returned allocated memory
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
411inline 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.
419using PartialDiagnosticAt = std::pair<SourceLocation, PartialDiagnostic>;
420
421} // namespace clang
422
423#endif // LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H