Bug Summary

File:tools/clang/lib/Sema/SemaTemplateDeduction.cpp
Warning:line 3831, column 9
Called C++ object pointer is null

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 SemaTemplateDeduction.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp

1//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/TemplateDeduction.h"
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclAccessPair.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/TemplateBase.h"
28#include "clang/AST/TemplateName.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/UnresolvedSet.h"
32#include "clang/Basic/AddressSpaces.h"
33#include "clang/Basic/ExceptionSpecificationType.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/PartialDiagnostic.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "clang/Sema/Ownership.h"
40#include "clang/Sema/Sema.h"
41#include "clang/Sema/Template.h"
42#include "llvm/ADT/APInt.h"
43#include "llvm/ADT/APSInt.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/FoldingSet.h"
47#include "llvm/ADT/Optional.h"
48#include "llvm/ADT/SmallBitVector.h"
49#include "llvm/ADT/SmallPtrSet.h"
50#include "llvm/ADT/SmallVector.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/Compiler.h"
53#include "llvm/Support/ErrorHandling.h"
54#include <algorithm>
55#include <cassert>
56#include <tuple>
57#include <utility>
58
59namespace clang {
60
61 /// Various flags that control template argument deduction.
62 ///
63 /// These flags can be bitwise-OR'd together.
64 enum TemplateDeductionFlags {
65 /// No template argument deduction flags, which indicates the
66 /// strictest results for template argument deduction (as used for, e.g.,
67 /// matching class template partial specializations).
68 TDF_None = 0,
69
70 /// Within template argument deduction from a function call, we are
71 /// matching with a parameter type for which the original parameter was
72 /// a reference.
73 TDF_ParamWithReferenceType = 0x1,
74
75 /// Within template argument deduction from a function call, we
76 /// are matching in a case where we ignore cv-qualifiers.
77 TDF_IgnoreQualifiers = 0x02,
78
79 /// Within template argument deduction from a function call,
80 /// we are matching in a case where we can perform template argument
81 /// deduction from a template-id of a derived class of the argument type.
82 TDF_DerivedClass = 0x04,
83
84 /// Allow non-dependent types to differ, e.g., when performing
85 /// template argument deduction from a function call where conversions
86 /// may apply.
87 TDF_SkipNonDependent = 0x08,
88
89 /// Whether we are performing template argument deduction for
90 /// parameters and arguments in a top-level template argument
91 TDF_TopLevelParameterTypeList = 0x10,
92
93 /// Within template argument deduction from overload resolution per
94 /// C++ [over.over] allow matching function types that are compatible in
95 /// terms of noreturn and default calling convention adjustments, or
96 /// similarly matching a declared template specialization against a
97 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
98 /// deduction where the parameter is a function type that can be converted
99 /// to the argument type.
100 TDF_AllowCompatibleFunctionType = 0x20,
101
102 /// Within template argument deduction for a conversion function, we are
103 /// matching with an argument type for which the original argument was
104 /// a reference.
105 TDF_ArgWithReferenceType = 0x40,
106 };
107}
108
109using namespace clang;
110using namespace sema;
111
112/// Compare two APSInts, extending and switching the sign as
113/// necessary to compare their values regardless of underlying type.
114static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
115 if (Y.getBitWidth() > X.getBitWidth())
116 X = X.extend(Y.getBitWidth());
117 else if (Y.getBitWidth() < X.getBitWidth())
118 Y = Y.extend(X.getBitWidth());
119
120 // If there is a signedness mismatch, correct it.
121 if (X.isSigned() != Y.isSigned()) {
122 // If the signed value is negative, then the values cannot be the same.
123 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
124 return false;
125
126 Y.setIsSigned(true);
127 X.setIsSigned(true);
128 }
129
130 return X == Y;
131}
132
133static Sema::TemplateDeductionResult
134DeduceTemplateArguments(Sema &S,
135 TemplateParameterList *TemplateParams,
136 const TemplateArgument &Param,
137 TemplateArgument Arg,
138 TemplateDeductionInfo &Info,
139 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
140
141static Sema::TemplateDeductionResult
142DeduceTemplateArgumentsByTypeMatch(Sema &S,
143 TemplateParameterList *TemplateParams,
144 QualType Param,
145 QualType Arg,
146 TemplateDeductionInfo &Info,
147 SmallVectorImpl<DeducedTemplateArgument> &
148 Deduced,
149 unsigned TDF,
150 bool PartialOrdering = false,
151 bool DeducedFromArrayBound = false);
152
153static Sema::TemplateDeductionResult
154DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
155 ArrayRef<TemplateArgument> Params,
156 ArrayRef<TemplateArgument> Args,
157 TemplateDeductionInfo &Info,
158 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
159 bool NumberOfArgumentsMustMatch);
160
161static void MarkUsedTemplateParameters(ASTContext &Ctx,
162 const TemplateArgument &TemplateArg,
163 bool OnlyDeduced, unsigned Depth,
164 llvm::SmallBitVector &Used);
165
166static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
167 bool OnlyDeduced, unsigned Level,
168 llvm::SmallBitVector &Deduced);
169
170/// If the given expression is of a form that permits the deduction
171/// of a non-type template parameter, return the declaration of that
172/// non-type template parameter.
173static NonTypeTemplateParmDecl *
174getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
175 // If we are within an alias template, the expression may have undergone
176 // any number of parameter substitutions already.
177 while (true) {
178 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
179 E = IC->getSubExpr();
180 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
181 E = CE->getSubExpr();
182 else if (SubstNonTypeTemplateParmExpr *Subst =
183 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
184 E = Subst->getReplacement();
185 else
186 break;
187 }
188
189 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
190 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
191 if (NTTP->getDepth() == Info.getDeducedDepth())
192 return NTTP;
193
194 return nullptr;
195}
196
197/// Determine whether two declaration pointers refer to the same
198/// declaration.
199static bool isSameDeclaration(Decl *X, Decl *Y) {
200 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
201 X = NX->getUnderlyingDecl();
202 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
203 Y = NY->getUnderlyingDecl();
204
205 return X->getCanonicalDecl() == Y->getCanonicalDecl();
206}
207
208/// Verify that the given, deduced template arguments are compatible.
209///
210/// \returns The deduced template argument, or a NULL template argument if
211/// the deduced template arguments were incompatible.
212static DeducedTemplateArgument
213checkDeducedTemplateArguments(ASTContext &Context,
214 const DeducedTemplateArgument &X,
215 const DeducedTemplateArgument &Y) {
216 // We have no deduction for one or both of the arguments; they're compatible.
217 if (X.isNull())
218 return Y;
219 if (Y.isNull())
220 return X;
221
222 // If we have two non-type template argument values deduced for the same
223 // parameter, they must both match the type of the parameter, and thus must
224 // match each other's type. As we're only keeping one of them, we must check
225 // for that now. The exception is that if either was deduced from an array
226 // bound, the type is permitted to differ.
227 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
228 QualType XType = X.getNonTypeTemplateArgumentType();
229 if (!XType.isNull()) {
230 QualType YType = Y.getNonTypeTemplateArgumentType();
231 if (YType.isNull() || !Context.hasSameType(XType, YType))
232 return DeducedTemplateArgument();
233 }
234 }
235
236 switch (X.getKind()) {
237 case TemplateArgument::Null:
238 llvm_unreachable("Non-deduced template arguments handled above")::llvm::llvm_unreachable_internal("Non-deduced template arguments handled above"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 238)
;
239
240 case TemplateArgument::Type:
241 // If two template type arguments have the same type, they're compatible.
242 if (Y.getKind() == TemplateArgument::Type &&
243 Context.hasSameType(X.getAsType(), Y.getAsType()))
244 return X;
245
246 // If one of the two arguments was deduced from an array bound, the other
247 // supersedes it.
248 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
249 return X.wasDeducedFromArrayBound() ? Y : X;
250
251 // The arguments are not compatible.
252 return DeducedTemplateArgument();
253
254 case TemplateArgument::Integral:
255 // If we deduced a constant in one case and either a dependent expression or
256 // declaration in another case, keep the integral constant.
257 // If both are integral constants with the same value, keep that value.
258 if (Y.getKind() == TemplateArgument::Expression ||
259 Y.getKind() == TemplateArgument::Declaration ||
260 (Y.getKind() == TemplateArgument::Integral &&
261 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
262 return X.wasDeducedFromArrayBound() ? Y : X;
263
264 // All other combinations are incompatible.
265 return DeducedTemplateArgument();
266
267 case TemplateArgument::Template:
268 if (Y.getKind() == TemplateArgument::Template &&
269 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
270 return X;
271
272 // All other combinations are incompatible.
273 return DeducedTemplateArgument();
274
275 case TemplateArgument::TemplateExpansion:
276 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
277 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
278 Y.getAsTemplateOrTemplatePattern()))
279 return X;
280
281 // All other combinations are incompatible.
282 return DeducedTemplateArgument();
283
284 case TemplateArgument::Expression: {
285 if (Y.getKind() != TemplateArgument::Expression)
286 return checkDeducedTemplateArguments(Context, Y, X);
287
288 // Compare the expressions for equality
289 llvm::FoldingSetNodeID ID1, ID2;
290 X.getAsExpr()->Profile(ID1, Context, true);
291 Y.getAsExpr()->Profile(ID2, Context, true);
292 if (ID1 == ID2)
293 return X.wasDeducedFromArrayBound() ? Y : X;
294
295 // Differing dependent expressions are incompatible.
296 return DeducedTemplateArgument();
297 }
298
299 case TemplateArgument::Declaration:
300 assert(!X.wasDeducedFromArrayBound())((!X.wasDeducedFromArrayBound()) ? static_cast<void> (0
) : __assert_fail ("!X.wasDeducedFromArrayBound()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 300, __PRETTY_FUNCTION__))
;
301
302 // If we deduced a declaration and a dependent expression, keep the
303 // declaration.
304 if (Y.getKind() == TemplateArgument::Expression)
305 return X;
306
307 // If we deduced a declaration and an integral constant, keep the
308 // integral constant and whichever type did not come from an array
309 // bound.
310 if (Y.getKind() == TemplateArgument::Integral) {
311 if (Y.wasDeducedFromArrayBound())
312 return TemplateArgument(Context, Y.getAsIntegral(),
313 X.getParamTypeForDecl());
314 return Y;
315 }
316
317 // If we deduced two declarations, make sure that they refer to the
318 // same declaration.
319 if (Y.getKind() == TemplateArgument::Declaration &&
320 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
321 return X;
322
323 // All other combinations are incompatible.
324 return DeducedTemplateArgument();
325
326 case TemplateArgument::NullPtr:
327 // If we deduced a null pointer and a dependent expression, keep the
328 // null pointer.
329 if (Y.getKind() == TemplateArgument::Expression)
330 return X;
331
332 // If we deduced a null pointer and an integral constant, keep the
333 // integral constant.
334 if (Y.getKind() == TemplateArgument::Integral)
335 return Y;
336
337 // If we deduced two null pointers, they are the same.
338 if (Y.getKind() == TemplateArgument::NullPtr)
339 return X;
340
341 // All other combinations are incompatible.
342 return DeducedTemplateArgument();
343
344 case TemplateArgument::Pack: {
345 if (Y.getKind() != TemplateArgument::Pack ||
346 X.pack_size() != Y.pack_size())
347 return DeducedTemplateArgument();
348
349 llvm::SmallVector<TemplateArgument, 8> NewPack;
350 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
351 XAEnd = X.pack_end(),
352 YA = Y.pack_begin();
353 XA != XAEnd; ++XA, ++YA) {
354 TemplateArgument Merged = checkDeducedTemplateArguments(
355 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
356 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
357 if (Merged.isNull())
358 return DeducedTemplateArgument();
359 NewPack.push_back(Merged);
360 }
361
362 return DeducedTemplateArgument(
363 TemplateArgument::CreatePackCopy(Context, NewPack),
364 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
365 }
366 }
367
368 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 368)
;
369}
370
371/// Deduce the value of the given non-type template parameter
372/// as the given deduced template argument. All non-type template parameter
373/// deduction is funneled through here.
374static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
375 Sema &S, TemplateParameterList *TemplateParams,
376 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
377 QualType ValueType, TemplateDeductionInfo &Info,
378 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
379 assert(NTTP->getDepth() == Info.getDeducedDepth() &&((NTTP->getDepth() == Info.getDeducedDepth() && "deducing non-type template argument with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"deducing non-type template argument with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 380, __PRETTY_FUNCTION__))
380 "deducing non-type template argument with wrong depth")((NTTP->getDepth() == Info.getDeducedDepth() && "deducing non-type template argument with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"deducing non-type template argument with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 380, __PRETTY_FUNCTION__))
;
381
382 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
383 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
384 if (Result.isNull()) {
385 Info.Param = NTTP;
386 Info.FirstArg = Deduced[NTTP->getIndex()];
387 Info.SecondArg = NewDeduced;
388 return Sema::TDK_Inconsistent;
389 }
390
391 Deduced[NTTP->getIndex()] = Result;
392 if (!S.getLangOpts().CPlusPlus17)
393 return Sema::TDK_Success;
394
395 if (NTTP->isExpandedParameterPack())
396 // FIXME: We may still need to deduce parts of the type here! But we
397 // don't have any way to find which slice of the type to use, and the
398 // type stored on the NTTP itself is nonsense. Perhaps the type of an
399 // expanded NTTP should be a pack expansion type?
400 return Sema::TDK_Success;
401
402 // Get the type of the parameter for deduction. If it's a (dependent) array
403 // or function type, we will not have decayed it yet, so do that now.
404 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
405 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
406 ParamType = Expansion->getPattern();
407
408 // FIXME: It's not clear how deduction of a parameter of reference
409 // type from an argument (of non-reference type) should be performed.
410 // For now, we just remove reference types from both sides and let
411 // the final check for matching types sort out the mess.
412 return DeduceTemplateArgumentsByTypeMatch(
413 S, TemplateParams, ParamType.getNonReferenceType(),
414 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
415 /*PartialOrdering=*/false,
416 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
417}
418
419/// Deduce the value of the given non-type template parameter
420/// from the given integral constant.
421static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
422 Sema &S, TemplateParameterList *TemplateParams,
423 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
424 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
425 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
426 return DeduceNonTypeTemplateArgument(
427 S, TemplateParams, NTTP,
428 DeducedTemplateArgument(S.Context, Value, ValueType,
429 DeducedFromArrayBound),
430 ValueType, Info, Deduced);
431}
432
433/// Deduce the value of the given non-type template parameter
434/// from the given null pointer template argument type.
435static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
436 Sema &S, TemplateParameterList *TemplateParams,
437 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
438 TemplateDeductionInfo &Info,
439 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
440 Expr *Value =
441 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
442 S.Context.NullPtrTy, NTTP->getLocation()),
443 NullPtrType, CK_NullToPointer)
444 .get();
445 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
446 DeducedTemplateArgument(Value),
447 Value->getType(), Info, Deduced);
448}
449
450/// Deduce the value of the given non-type template parameter
451/// from the given type- or value-dependent expression.
452///
453/// \returns true if deduction succeeded, false otherwise.
454static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
455 Sema &S, TemplateParameterList *TemplateParams,
456 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
457 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
458 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
459 DeducedTemplateArgument(Value),
460 Value->getType(), Info, Deduced);
461}
462
463/// Deduce the value of the given non-type template parameter
464/// from the given declaration.
465///
466/// \returns true if deduction succeeded, false otherwise.
467static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
468 Sema &S, TemplateParameterList *TemplateParams,
469 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
470 TemplateDeductionInfo &Info,
471 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
472 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
473 TemplateArgument New(D, T);
474 return DeduceNonTypeTemplateArgument(
475 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
476}
477
478static Sema::TemplateDeductionResult
479DeduceTemplateArguments(Sema &S,
480 TemplateParameterList *TemplateParams,
481 TemplateName Param,
482 TemplateName Arg,
483 TemplateDeductionInfo &Info,
484 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
485 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
486 if (!ParamDecl) {
487 // The parameter type is dependent and is not a template template parameter,
488 // so there is nothing that we can deduce.
489 return Sema::TDK_Success;
490 }
491
492 if (TemplateTemplateParmDecl *TempParam
493 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
494 // If we're not deducing at this depth, there's nothing to deduce.
495 if (TempParam->getDepth() != Info.getDeducedDepth())
496 return Sema::TDK_Success;
497
498 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
499 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
500 Deduced[TempParam->getIndex()],
501 NewDeduced);
502 if (Result.isNull()) {
503 Info.Param = TempParam;
504 Info.FirstArg = Deduced[TempParam->getIndex()];
505 Info.SecondArg = NewDeduced;
506 return Sema::TDK_Inconsistent;
507 }
508
509 Deduced[TempParam->getIndex()] = Result;
510 return Sema::TDK_Success;
511 }
512
513 // Verify that the two template names are equivalent.
514 if (S.Context.hasSameTemplateName(Param, Arg))
515 return Sema::TDK_Success;
516
517 // Mismatch of non-dependent template parameter to argument.
518 Info.FirstArg = TemplateArgument(Param);
519 Info.SecondArg = TemplateArgument(Arg);
520 return Sema::TDK_NonDeducedMismatch;
521}
522
523/// Deduce the template arguments by comparing the template parameter
524/// type (which is a template-id) with the template argument type.
525///
526/// \param S the Sema
527///
528/// \param TemplateParams the template parameters that we are deducing
529///
530/// \param Param the parameter type
531///
532/// \param Arg the argument type
533///
534/// \param Info information about the template argument deduction itself
535///
536/// \param Deduced the deduced template arguments
537///
538/// \returns the result of template argument deduction so far. Note that a
539/// "success" result means that template argument deduction has not yet failed,
540/// but it may still fail, later, for other reasons.
541static Sema::TemplateDeductionResult
542DeduceTemplateArguments(Sema &S,
543 TemplateParameterList *TemplateParams,
544 const TemplateSpecializationType *Param,
545 QualType Arg,
546 TemplateDeductionInfo &Info,
547 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
548 assert(Arg.isCanonical() && "Argument type must be canonical")((Arg.isCanonical() && "Argument type must be canonical"
) ? static_cast<void> (0) : __assert_fail ("Arg.isCanonical() && \"Argument type must be canonical\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 548, __PRETTY_FUNCTION__))
;
549
550 // Treat an injected-class-name as its underlying template-id.
551 if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg))
552 Arg = Injected->getInjectedSpecializationType();
553
554 // Check whether the template argument is a dependent template-id.
555 if (const TemplateSpecializationType *SpecArg
556 = dyn_cast<TemplateSpecializationType>(Arg)) {
557 // Perform template argument deduction for the template name.
558 if (Sema::TemplateDeductionResult Result
559 = DeduceTemplateArguments(S, TemplateParams,
560 Param->getTemplateName(),
561 SpecArg->getTemplateName(),
562 Info, Deduced))
563 return Result;
564
565
566 // Perform template argument deduction on each template
567 // argument. Ignore any missing/extra arguments, since they could be
568 // filled in by default arguments.
569 return DeduceTemplateArguments(S, TemplateParams,
570 Param->template_arguments(),
571 SpecArg->template_arguments(), Info, Deduced,
572 /*NumberOfArgumentsMustMatch=*/false);
573 }
574
575 // If the argument type is a class template specialization, we
576 // perform template argument deduction using its template
577 // arguments.
578 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
579 if (!RecordArg) {
580 Info.FirstArg = TemplateArgument(QualType(Param, 0));
581 Info.SecondArg = TemplateArgument(Arg);
582 return Sema::TDK_NonDeducedMismatch;
583 }
584
585 ClassTemplateSpecializationDecl *SpecArg
586 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
587 if (!SpecArg) {
588 Info.FirstArg = TemplateArgument(QualType(Param, 0));
589 Info.SecondArg = TemplateArgument(Arg);
590 return Sema::TDK_NonDeducedMismatch;
591 }
592
593 // Perform template argument deduction for the template name.
594 if (Sema::TemplateDeductionResult Result
595 = DeduceTemplateArguments(S,
596 TemplateParams,
597 Param->getTemplateName(),
598 TemplateName(SpecArg->getSpecializedTemplate()),
599 Info, Deduced))
600 return Result;
601
602 // Perform template argument deduction for the template arguments.
603 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
604 SpecArg->getTemplateArgs().asArray(), Info,
605 Deduced, /*NumberOfArgumentsMustMatch=*/true);
606}
607
608/// Determines whether the given type is an opaque type that
609/// might be more qualified when instantiated.
610static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
611 switch (T->getTypeClass()) {
612 case Type::TypeOfExpr:
613 case Type::TypeOf:
614 case Type::DependentName:
615 case Type::Decltype:
616 case Type::UnresolvedUsing:
617 case Type::TemplateTypeParm:
618 return true;
619
620 case Type::ConstantArray:
621 case Type::IncompleteArray:
622 case Type::VariableArray:
623 case Type::DependentSizedArray:
624 return IsPossiblyOpaquelyQualifiedType(
625 cast<ArrayType>(T)->getElementType());
626
627 default:
628 return false;
629 }
630}
631
632/// Helper function to build a TemplateParameter when we don't
633/// know its type statically.
634static TemplateParameter makeTemplateParameter(Decl *D) {
635 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
636 return TemplateParameter(TTP);
637 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
638 return TemplateParameter(NTTP);
639
640 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
641}
642
643/// If \p Param is an expanded parameter pack, get the number of expansions.
644static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
645 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
646 if (NTTP->isExpandedParameterPack())
647 return NTTP->getNumExpansionTypes();
648
649 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param))
650 if (TTP->isExpandedParameterPack())
651 return TTP->getNumExpansionTemplateParameters();
652
653 return None;
654}
655
656/// A pack that we're currently deducing.
657struct clang::DeducedPack {
658 // The index of the pack.
659 unsigned Index;
660
661 // The old value of the pack before we started deducing it.
662 DeducedTemplateArgument Saved;
663
664 // A deferred value of this pack from an inner deduction, that couldn't be
665 // deduced because this deduction hadn't happened yet.
666 DeducedTemplateArgument DeferredDeduction;
667
668 // The new value of the pack.
669 SmallVector<DeducedTemplateArgument, 4> New;
670
671 // The outer deduction for this pack, if any.
672 DeducedPack *Outer = nullptr;
673
674 DeducedPack(unsigned Index) : Index(Index) {}
675};
676
677namespace {
678
679/// A scope in which we're performing pack deduction.
680class PackDeductionScope {
681public:
682 /// Prepare to deduce the packs named within Pattern.
683 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
684 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
685 TemplateDeductionInfo &Info, TemplateArgument Pattern)
686 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
687 unsigned NumNamedPacks = addPacks(Pattern);
688 finishConstruction(NumNamedPacks);
689 }
690
691 /// Prepare to directly deduce arguments of the parameter with index \p Index.
692 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
693 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
694 TemplateDeductionInfo &Info, unsigned Index)
695 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
696 addPack(Index);
697 finishConstruction(1);
698 }
699
700private:
701 void addPack(unsigned Index) {
702 // Save the deduced template argument for the parameter pack expanded
703 // by this pack expansion, then clear out the deduction.
704 DeducedPack Pack(Index);
705 Pack.Saved = Deduced[Index];
706 Deduced[Index] = TemplateArgument();
707
708 // FIXME: What if we encounter multiple packs with different numbers of
709 // pre-expanded expansions? (This should already have been diagnosed
710 // during substitution.)
711 if (Optional<unsigned> ExpandedPackExpansions =
712 getExpandedPackSize(TemplateParams->getParam(Index)))
713 FixedNumExpansions = ExpandedPackExpansions;
714
715 Packs.push_back(Pack);
716 }
717
718 unsigned addPacks(TemplateArgument Pattern) {
719 // Compute the set of template parameter indices that correspond to
720 // parameter packs expanded by the pack expansion.
721 llvm::SmallBitVector SawIndices(TemplateParams->size());
722
723 auto AddPack = [&](unsigned Index) {
724 if (SawIndices[Index])
725 return;
726 SawIndices[Index] = true;
727 addPack(Index);
728 };
729
730 // First look for unexpanded packs in the pattern.
731 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
732 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
733 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
734 unsigned Depth, Index;
735 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
736 if (Depth == Info.getDeducedDepth())
737 AddPack(Index);
738 }
739 assert(!Packs.empty() && "Pack expansion without unexpanded packs?")((!Packs.empty() && "Pack expansion without unexpanded packs?"
) ? static_cast<void> (0) : __assert_fail ("!Packs.empty() && \"Pack expansion without unexpanded packs?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 739, __PRETTY_FUNCTION__))
;
740
741 unsigned NumNamedPacks = Packs.size();
742
743 // We can also have deduced template parameters that do not actually
744 // appear in the pattern, but can be deduced by it (the type of a non-type
745 // template parameter pack, in particular). These won't have prevented us
746 // from partially expanding the pack.
747 llvm::SmallBitVector Used(TemplateParams->size());
748 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
749 Info.getDeducedDepth(), Used);
750 for (int Index = Used.find_first(); Index != -1;
751 Index = Used.find_next(Index))
752 if (TemplateParams->getParam(Index)->isParameterPack())
753 AddPack(Index);
754
755 return NumNamedPacks;
756 }
757
758 void finishConstruction(unsigned NumNamedPacks) {
759 // Dig out the partially-substituted pack, if there is one.
760 const TemplateArgument *PartialPackArgs = nullptr;
761 unsigned NumPartialPackArgs = 0;
762 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
763 if (auto *Scope = S.CurrentInstantiationScope)
764 if (auto *Partial = Scope->getPartiallySubstitutedPack(
765 &PartialPackArgs, &NumPartialPackArgs))
766 PartialPackDepthIndex = getDepthAndIndex(Partial);
767
768 // This pack expansion will have been partially or fully expanded if
769 // it only names explicitly-specified parameter packs (including the
770 // partially-substituted one, if any).
771 bool IsExpanded = true;
772 for (unsigned I = 0; I != NumNamedPacks; ++I) {
773 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
774 IsExpanded = false;
775 IsPartiallyExpanded = false;
776 break;
777 }
778 if (PartialPackDepthIndex ==
779 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
780 IsPartiallyExpanded = true;
781 }
782 }
783
784 // Skip over the pack elements that were expanded into separate arguments.
785 // If we partially expanded, this is the number of partial arguments.
786 if (IsPartiallyExpanded)
787 PackElements += NumPartialPackArgs;
788 else if (IsExpanded)
789 PackElements += *FixedNumExpansions;
790
791 for (auto &Pack : Packs) {
792 if (Info.PendingDeducedPacks.size() > Pack.Index)
793 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
794 else
795 Info.PendingDeducedPacks.resize(Pack.Index + 1);
796 Info.PendingDeducedPacks[Pack.Index] = &Pack;
797
798 if (PartialPackDepthIndex ==
799 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
800 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
801 // We pre-populate the deduced value of the partially-substituted
802 // pack with the specified value. This is not entirely correct: the
803 // value is supposed to have been substituted, not deduced, but the
804 // cases where this is observable require an exact type match anyway.
805 //
806 // FIXME: If we could represent a "depth i, index j, pack elem k"
807 // parameter, we could substitute the partially-substituted pack
808 // everywhere and avoid this.
809 if (!IsPartiallyExpanded)
810 Deduced[Pack.Index] = Pack.New[PackElements];
811 }
812 }
813 }
814
815public:
816 ~PackDeductionScope() {
817 for (auto &Pack : Packs)
818 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
819 }
820
821 /// Determine whether this pack has already been partially expanded into a
822 /// sequence of (prior) function parameters / template arguments.
823 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
824
825 /// Determine whether this pack expansion scope has a known, fixed arity.
826 /// This happens if it involves a pack from an outer template that has
827 /// (notionally) already been expanded.
828 bool hasFixedArity() { return FixedNumExpansions.hasValue(); }
829
830 /// Determine whether the next element of the argument is still part of this
831 /// pack. This is the case unless the pack is already expanded to a fixed
832 /// length.
833 bool hasNextElement() {
834 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
835 }
836
837 /// Move to deducing the next element in each pack that is being deduced.
838 void nextPackElement() {
839 // Capture the deduced template arguments for each parameter pack expanded
840 // by this pack expansion, add them to the list of arguments we've deduced
841 // for that pack, then clear out the deduced argument.
842 for (auto &Pack : Packs) {
843 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
844 if (!Pack.New.empty() || !DeducedArg.isNull()) {
845 while (Pack.New.size() < PackElements)
846 Pack.New.push_back(DeducedTemplateArgument());
847 if (Pack.New.size() == PackElements)
848 Pack.New.push_back(DeducedArg);
849 else
850 Pack.New[PackElements] = DeducedArg;
851 DeducedArg = Pack.New.size() > PackElements + 1
852 ? Pack.New[PackElements + 1]
853 : DeducedTemplateArgument();
854 }
855 }
856 ++PackElements;
857 }
858
859 /// Finish template argument deduction for a set of argument packs,
860 /// producing the argument packs and checking for consistency with prior
861 /// deductions.
862 Sema::TemplateDeductionResult
863 finish(bool TreatNoDeductionsAsNonDeduced = true) {
864 // Build argument packs for each of the parameter packs expanded by this
865 // pack expansion.
866 for (auto &Pack : Packs) {
867 // Put back the old value for this pack.
868 Deduced[Pack.Index] = Pack.Saved;
869
870 // If we are deducing the size of this pack even if we didn't deduce any
871 // values for it, then make sure we build a pack of the right size.
872 // FIXME: Should we always deduce the size, even if the pack appears in
873 // a non-deduced context?
874 if (!TreatNoDeductionsAsNonDeduced)
875 Pack.New.resize(PackElements);
876
877 // Build or find a new value for this pack.
878 DeducedTemplateArgument NewPack;
879 if (PackElements && Pack.New.empty()) {
880 if (Pack.DeferredDeduction.isNull()) {
881 // We were not able to deduce anything for this parameter pack
882 // (because it only appeared in non-deduced contexts), so just
883 // restore the saved argument pack.
884 continue;
885 }
886
887 NewPack = Pack.DeferredDeduction;
888 Pack.DeferredDeduction = TemplateArgument();
889 } else if (Pack.New.empty()) {
890 // If we deduced an empty argument pack, create it now.
891 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
892 } else {
893 TemplateArgument *ArgumentPack =
894 new (S.Context) TemplateArgument[Pack.New.size()];
895 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
896 NewPack = DeducedTemplateArgument(
897 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
898 // FIXME: This is wrong, it's possible that some pack elements are
899 // deduced from an array bound and others are not:
900 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
901 // g({1, 2, 3}, {{}, {}});
902 // ... should deduce T = {int, size_t (from array bound)}.
903 Pack.New[0].wasDeducedFromArrayBound());
904 }
905
906 // Pick where we're going to put the merged pack.
907 DeducedTemplateArgument *Loc;
908 if (Pack.Outer) {
909 if (Pack.Outer->DeferredDeduction.isNull()) {
910 // Defer checking this pack until we have a complete pack to compare
911 // it against.
912 Pack.Outer->DeferredDeduction = NewPack;
913 continue;
914 }
915 Loc = &Pack.Outer->DeferredDeduction;
916 } else {
917 Loc = &Deduced[Pack.Index];
918 }
919
920 // Check the new pack matches any previous value.
921 DeducedTemplateArgument OldPack = *Loc;
922 DeducedTemplateArgument Result =
923 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
924
925 // If we deferred a deduction of this pack, check that one now too.
926 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
927 OldPack = Result;
928 NewPack = Pack.DeferredDeduction;
929 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
930 }
931
932 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
933 if (Result.isNull()) {
934 Info.Param = makeTemplateParameter(Param);
935 Info.FirstArg = OldPack;
936 Info.SecondArg = NewPack;
937 return Sema::TDK_Inconsistent;
938 }
939
940 // If we have a pre-expanded pack and we didn't deduce enough elements
941 // for it, fail deduction.
942 if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) {
943 if (*Expansions != PackElements) {
944 Info.Param = makeTemplateParameter(Param);
945 Info.FirstArg = Result;
946 return Sema::TDK_IncompletePack;
947 }
948 }
949
950 *Loc = Result;
951 }
952
953 return Sema::TDK_Success;
954 }
955
956private:
957 Sema &S;
958 TemplateParameterList *TemplateParams;
959 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
960 TemplateDeductionInfo &Info;
961 unsigned PackElements = 0;
962 bool IsPartiallyExpanded = false;
963 /// The number of expansions, if we have a fully-expanded pack in this scope.
964 Optional<unsigned> FixedNumExpansions;
965
966 SmallVector<DeducedPack, 2> Packs;
967};
968
969} // namespace
970
971/// Deduce the template arguments by comparing the list of parameter
972/// types to the list of argument types, as in the parameter-type-lists of
973/// function types (C++ [temp.deduct.type]p10).
974///
975/// \param S The semantic analysis object within which we are deducing
976///
977/// \param TemplateParams The template parameters that we are deducing
978///
979/// \param Params The list of parameter types
980///
981/// \param NumParams The number of types in \c Params
982///
983/// \param Args The list of argument types
984///
985/// \param NumArgs The number of types in \c Args
986///
987/// \param Info information about the template argument deduction itself
988///
989/// \param Deduced the deduced template arguments
990///
991/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
992/// how template argument deduction is performed.
993///
994/// \param PartialOrdering If true, we are performing template argument
995/// deduction for during partial ordering for a call
996/// (C++0x [temp.deduct.partial]).
997///
998/// \returns the result of template argument deduction so far. Note that a
999/// "success" result means that template argument deduction has not yet failed,
1000/// but it may still fail, later, for other reasons.
1001static Sema::TemplateDeductionResult
1002DeduceTemplateArguments(Sema &S,
1003 TemplateParameterList *TemplateParams,
1004 const QualType *Params, unsigned NumParams,
1005 const QualType *Args, unsigned NumArgs,
1006 TemplateDeductionInfo &Info,
1007 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1008 unsigned TDF,
1009 bool PartialOrdering = false) {
1010 // C++0x [temp.deduct.type]p10:
1011 // Similarly, if P has a form that contains (T), then each parameter type
1012 // Pi of the respective parameter-type- list of P is compared with the
1013 // corresponding parameter type Ai of the corresponding parameter-type-list
1014 // of A. [...]
1015 unsigned ArgIdx = 0, ParamIdx = 0;
1016 for (; ParamIdx != NumParams; ++ParamIdx) {
1017 // Check argument types.
1018 const PackExpansionType *Expansion
1019 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1020 if (!Expansion) {
1021 // Simple case: compare the parameter and argument types at this point.
1022
1023 // Make sure we have an argument.
1024 if (ArgIdx >= NumArgs)
1025 return Sema::TDK_MiscellaneousDeductionFailure;
1026
1027 if (isa<PackExpansionType>(Args[ArgIdx])) {
1028 // C++0x [temp.deduct.type]p22:
1029 // If the original function parameter associated with A is a function
1030 // parameter pack and the function parameter associated with P is not
1031 // a function parameter pack, then template argument deduction fails.
1032 return Sema::TDK_MiscellaneousDeductionFailure;
1033 }
1034
1035 if (Sema::TemplateDeductionResult Result
1036 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1037 Params[ParamIdx], Args[ArgIdx],
1038 Info, Deduced, TDF,
1039 PartialOrdering))
1040 return Result;
1041
1042 ++ArgIdx;
1043 continue;
1044 }
1045
1046 // C++0x [temp.deduct.type]p10:
1047 // If the parameter-declaration corresponding to Pi is a function
1048 // parameter pack, then the type of its declarator- id is compared with
1049 // each remaining parameter type in the parameter-type-list of A. Each
1050 // comparison deduces template arguments for subsequent positions in the
1051 // template parameter packs expanded by the function parameter pack.
1052
1053 QualType Pattern = Expansion->getPattern();
1054 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1055
1056 // A pack scope with fixed arity is not really a pack any more, so is not
1057 // a non-deduced context.
1058 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1059 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
1060 // Deduce template arguments from the pattern.
1061 if (Sema::TemplateDeductionResult Result
1062 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
1063 Args[ArgIdx], Info, Deduced,
1064 TDF, PartialOrdering))
1065 return Result;
1066
1067 PackScope.nextPackElement();
1068 }
1069 } else {
1070 // C++0x [temp.deduct.type]p5:
1071 // The non-deduced contexts are:
1072 // - A function parameter pack that does not occur at the end of the
1073 // parameter-declaration-clause.
1074 //
1075 // FIXME: There is no wording to say what we should do in this case. We
1076 // choose to resolve this by applying the same rule that is applied for a
1077 // function call: that is, deduce all contained packs to their
1078 // explicitly-specified values (or to <> if there is no such value).
1079 //
1080 // This is seemingly-arbitrarily different from the case of a template-id
1081 // with a non-trailing pack-expansion in its arguments, which renders the
1082 // entire template-argument-list a non-deduced context.
1083
1084 // If the parameter type contains an explicitly-specified pack that we
1085 // could not expand, skip the number of parameters notionally created
1086 // by the expansion.
1087 Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1088 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1089 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1090 ++I, ++ArgIdx)
1091 PackScope.nextPackElement();
1092 }
1093 }
1094
1095 // Build argument packs for each of the parameter packs expanded by this
1096 // pack expansion.
1097 if (auto Result = PackScope.finish())
1098 return Result;
1099 }
1100
1101 // Make sure we don't have any extra arguments.
1102 if (ArgIdx < NumArgs)
1103 return Sema::TDK_MiscellaneousDeductionFailure;
1104
1105 return Sema::TDK_Success;
1106}
1107
1108/// Determine whether the parameter has qualifiers that the argument
1109/// lacks. Put another way, determine whether there is no way to add
1110/// a deduced set of qualifiers to the ParamType that would result in
1111/// its qualifiers matching those of the ArgType.
1112static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1113 QualType ArgType) {
1114 Qualifiers ParamQs = ParamType.getQualifiers();
1115 Qualifiers ArgQs = ArgType.getQualifiers();
1116
1117 if (ParamQs == ArgQs)
1118 return false;
1119
1120 // Mismatched (but not missing) Objective-C GC attributes.
1121 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1122 ParamQs.hasObjCGCAttr())
1123 return true;
1124
1125 // Mismatched (but not missing) address spaces.
1126 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1127 ParamQs.hasAddressSpace())
1128 return true;
1129
1130 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1131 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1132 ParamQs.hasObjCLifetime())
1133 return true;
1134
1135 // CVR qualifiers inconsistent or a superset.
1136 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1137}
1138
1139/// Compare types for equality with respect to possibly compatible
1140/// function types (noreturn adjustment, implicit calling conventions). If any
1141/// of parameter and argument is not a function, just perform type comparison.
1142///
1143/// \param Param the template parameter type.
1144///
1145/// \param Arg the argument type.
1146bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1147 CanQualType Arg) {
1148 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1149 *ArgFunction = Arg->getAs<FunctionType>();
1150
1151 // Just compare if not functions.
1152 if (!ParamFunction || !ArgFunction)
1153 return Param == Arg;
1154
1155 // Noreturn and noexcept adjustment.
1156 QualType AdjustedParam;
1157 if (IsFunctionConversion(Param, Arg, AdjustedParam))
1158 return Arg == Context.getCanonicalType(AdjustedParam);
1159
1160 // FIXME: Compatible calling conventions.
1161
1162 return Param == Arg;
1163}
1164
1165/// Get the index of the first template parameter that was originally from the
1166/// innermost template-parameter-list. This is 0 except when we concatenate
1167/// the template parameter lists of a class template and a constructor template
1168/// when forming an implicit deduction guide.
1169static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
1170 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1171 if (!Guide || !Guide->isImplicit())
1172 return 0;
1173 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1174}
1175
1176/// Determine whether a type denotes a forwarding reference.
1177static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1178 // C++1z [temp.deduct.call]p3:
1179 // A forwarding reference is an rvalue reference to a cv-unqualified
1180 // template parameter that does not represent a template parameter of a
1181 // class template.
1182 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1183 if (ParamRef->getPointeeType().getQualifiers())
1184 return false;
1185 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1186 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1187 }
1188 return false;
1189}
1190
1191/// Deduce the template arguments by comparing the parameter type and
1192/// the argument type (C++ [temp.deduct.type]).
1193///
1194/// \param S the semantic analysis object within which we are deducing
1195///
1196/// \param TemplateParams the template parameters that we are deducing
1197///
1198/// \param ParamIn the parameter type
1199///
1200/// \param ArgIn the argument type
1201///
1202/// \param Info information about the template argument deduction itself
1203///
1204/// \param Deduced the deduced template arguments
1205///
1206/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1207/// how template argument deduction is performed.
1208///
1209/// \param PartialOrdering Whether we're performing template argument deduction
1210/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1211///
1212/// \returns the result of template argument deduction so far. Note that a
1213/// "success" result means that template argument deduction has not yet failed,
1214/// but it may still fail, later, for other reasons.
1215static Sema::TemplateDeductionResult
1216DeduceTemplateArgumentsByTypeMatch(Sema &S,
1217 TemplateParameterList *TemplateParams,
1218 QualType ParamIn, QualType ArgIn,
1219 TemplateDeductionInfo &Info,
1220 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1221 unsigned TDF,
1222 bool PartialOrdering,
1223 bool DeducedFromArrayBound) {
1224 // We only want to look at the canonical types, since typedefs and
1225 // sugar are not part of template argument deduction.
1226 QualType Param = S.Context.getCanonicalType(ParamIn);
1227 QualType Arg = S.Context.getCanonicalType(ArgIn);
1228
1229 // If the argument type is a pack expansion, look at its pattern.
1230 // This isn't explicitly called out
1231 if (const PackExpansionType *ArgExpansion
1232 = dyn_cast<PackExpansionType>(Arg))
1233 Arg = ArgExpansion->getPattern();
1234
1235 if (PartialOrdering) {
1236 // C++11 [temp.deduct.partial]p5:
1237 // Before the partial ordering is done, certain transformations are
1238 // performed on the types used for partial ordering:
1239 // - If P is a reference type, P is replaced by the type referred to.
1240 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1241 if (ParamRef)
1242 Param = ParamRef->getPointeeType();
1243
1244 // - If A is a reference type, A is replaced by the type referred to.
1245 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1246 if (ArgRef)
1247 Arg = ArgRef->getPointeeType();
1248
1249 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1250 // C++11 [temp.deduct.partial]p9:
1251 // If, for a given type, deduction succeeds in both directions (i.e.,
1252 // the types are identical after the transformations above) and both
1253 // P and A were reference types [...]:
1254 // - if [one type] was an lvalue reference and [the other type] was
1255 // not, [the other type] is not considered to be at least as
1256 // specialized as [the first type]
1257 // - if [one type] is more cv-qualified than [the other type],
1258 // [the other type] is not considered to be at least as specialized
1259 // as [the first type]
1260 // Objective-C ARC adds:
1261 // - [one type] has non-trivial lifetime, [the other type] has
1262 // __unsafe_unretained lifetime, and the types are otherwise
1263 // identical
1264 //
1265 // A is "considered to be at least as specialized" as P iff deduction
1266 // succeeds, so we model this as a deduction failure. Note that
1267 // [the first type] is P and [the other type] is A here; the standard
1268 // gets this backwards.
1269 Qualifiers ParamQuals = Param.getQualifiers();
1270 Qualifiers ArgQuals = Arg.getQualifiers();
1271 if ((ParamRef->isLValueReferenceType() &&
1272 !ArgRef->isLValueReferenceType()) ||
1273 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1274 (ParamQuals.hasNonTrivialObjCLifetime() &&
1275 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1276 ParamQuals.withoutObjCLifetime() ==
1277 ArgQuals.withoutObjCLifetime())) {
1278 Info.FirstArg = TemplateArgument(ParamIn);
1279 Info.SecondArg = TemplateArgument(ArgIn);
1280 return Sema::TDK_NonDeducedMismatch;
1281 }
1282 }
1283
1284 // C++11 [temp.deduct.partial]p7:
1285 // Remove any top-level cv-qualifiers:
1286 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1287 // version of P.
1288 Param = Param.getUnqualifiedType();
1289 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1290 // version of A.
1291 Arg = Arg.getUnqualifiedType();
1292 } else {
1293 // C++0x [temp.deduct.call]p4 bullet 1:
1294 // - If the original P is a reference type, the deduced A (i.e., the type
1295 // referred to by the reference) can be more cv-qualified than the
1296 // transformed A.
1297 if (TDF & TDF_ParamWithReferenceType) {
1298 Qualifiers Quals;
1299 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1300 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
1301 Arg.getCVRQualifiers());
1302 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1303 }
1304
1305 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1306 // C++0x [temp.deduct.type]p10:
1307 // If P and A are function types that originated from deduction when
1308 // taking the address of a function template (14.8.2.2) or when deducing
1309 // template arguments from a function declaration (14.8.2.6) and Pi and
1310 // Ai are parameters of the top-level parameter-type-list of P and A,
1311 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1312 // is an lvalue reference, in
1313 // which case the type of Pi is changed to be the template parameter
1314 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1315 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1316 // deduced as X&. - end note ]
1317 TDF &= ~TDF_TopLevelParameterTypeList;
1318 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1319 Param = Param->getPointeeType();
1320 }
1321 }
1322
1323 // C++ [temp.deduct.type]p9:
1324 // A template type argument T, a template template argument TT or a
1325 // template non-type argument i can be deduced if P and A have one of
1326 // the following forms:
1327 //
1328 // T
1329 // cv-list T
1330 if (const TemplateTypeParmType *TemplateTypeParm
1331 = Param->getAs<TemplateTypeParmType>()) {
1332 // Just skip any attempts to deduce from a placeholder type or a parameter
1333 // at a different depth.
1334 if (Arg->isPlaceholderType() ||
1335 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
1336 return Sema::TDK_Success;
1337
1338 unsigned Index = TemplateTypeParm->getIndex();
1339 bool RecanonicalizeArg = false;
1340
1341 // If the argument type is an array type, move the qualifiers up to the
1342 // top level, so they can be matched with the qualifiers on the parameter.
1343 if (isa<ArrayType>(Arg)) {
1344 Qualifiers Quals;
1345 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1346 if (Quals) {
1347 Arg = S.Context.getQualifiedType(Arg, Quals);
1348 RecanonicalizeArg = true;
1349 }
1350 }
1351
1352 // The argument type can not be less qualified than the parameter
1353 // type.
1354 if (!(TDF & TDF_IgnoreQualifiers) &&
1355 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
1356 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1357 Info.FirstArg = TemplateArgument(Param);
1358 Info.SecondArg = TemplateArgument(Arg);
1359 return Sema::TDK_Underqualified;
1360 }
1361
1362 // Do not match a function type with a cv-qualified type.
1363 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1364 if (Arg->isFunctionType() && Param.hasQualifiers()) {
1365 return Sema::TDK_NonDeducedMismatch;
1366 }
1367
1368 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&((TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
"saw template type parameter with wrong depth") ? static_cast
<void> (0) : __assert_fail ("TemplateTypeParm->getDepth() == Info.getDeducedDepth() && \"saw template type parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1369, __PRETTY_FUNCTION__))
1369 "saw template type parameter with wrong depth")((TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
"saw template type parameter with wrong depth") ? static_cast
<void> (0) : __assert_fail ("TemplateTypeParm->getDepth() == Info.getDeducedDepth() && \"saw template type parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1369, __PRETTY_FUNCTION__))
;
1370 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function")((Arg != S.Context.OverloadTy && "Unresolved overloaded function"
) ? static_cast<void> (0) : __assert_fail ("Arg != S.Context.OverloadTy && \"Unresolved overloaded function\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1370, __PRETTY_FUNCTION__))
;
1371 QualType DeducedType = Arg;
1372
1373 // Remove any qualifiers on the parameter from the deduced type.
1374 // We checked the qualifiers for consistency above.
1375 Qualifiers DeducedQs = DeducedType.getQualifiers();
1376 Qualifiers ParamQs = Param.getQualifiers();
1377 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1378 if (ParamQs.hasObjCGCAttr())
1379 DeducedQs.removeObjCGCAttr();
1380 if (ParamQs.hasAddressSpace())
1381 DeducedQs.removeAddressSpace();
1382 if (ParamQs.hasObjCLifetime())
1383 DeducedQs.removeObjCLifetime();
1384
1385 // Objective-C ARC:
1386 // If template deduction would produce a lifetime qualifier on a type
1387 // that is not a lifetime type, template argument deduction fails.
1388 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1389 !DeducedType->isDependentType()) {
1390 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1391 Info.FirstArg = TemplateArgument(Param);
1392 Info.SecondArg = TemplateArgument(Arg);
1393 return Sema::TDK_Underqualified;
1394 }
1395
1396 // Objective-C ARC:
1397 // If template deduction would produce an argument type with lifetime type
1398 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1399 if (S.getLangOpts().ObjCAutoRefCount &&
1400 DeducedType->isObjCLifetimeType() &&
1401 !DeducedQs.hasObjCLifetime())
1402 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1403
1404 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1405 DeducedQs);
1406
1407 if (RecanonicalizeArg)
1408 DeducedType = S.Context.getCanonicalType(DeducedType);
1409
1410 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1411 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
1412 Deduced[Index],
1413 NewDeduced);
1414 if (Result.isNull()) {
1415 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1416 Info.FirstArg = Deduced[Index];
1417 Info.SecondArg = NewDeduced;
1418 return Sema::TDK_Inconsistent;
1419 }
1420
1421 Deduced[Index] = Result;
1422 return Sema::TDK_Success;
1423 }
1424
1425 // Set up the template argument deduction information for a failure.
1426 Info.FirstArg = TemplateArgument(ParamIn);
1427 Info.SecondArg = TemplateArgument(ArgIn);
1428
1429 // If the parameter is an already-substituted template parameter
1430 // pack, do nothing: we don't know which of its arguments to look
1431 // at, so we have to wait until all of the parameter packs in this
1432 // expansion have arguments.
1433 if (isa<SubstTemplateTypeParmPackType>(Param))
1434 return Sema::TDK_Success;
1435
1436 // Check the cv-qualifiers on the parameter and argument types.
1437 CanQualType CanParam = S.Context.getCanonicalType(Param);
1438 CanQualType CanArg = S.Context.getCanonicalType(Arg);
1439 if (!(TDF & TDF_IgnoreQualifiers)) {
1440 if (TDF & TDF_ParamWithReferenceType) {
1441 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1442 return Sema::TDK_NonDeducedMismatch;
1443 } else if (TDF & TDF_ArgWithReferenceType) {
1444 // C++ [temp.deduct.conv]p4:
1445 // If the original A is a reference type, A can be more cv-qualified
1446 // than the deduced A
1447 if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers()))
1448 return Sema::TDK_NonDeducedMismatch;
1449
1450 // Strip out all extra qualifiers from the argument to figure out the
1451 // type we're converting to, prior to the qualification conversion.
1452 Qualifiers Quals;
1453 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1454 Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers());
1455 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1456 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1457 return Sema::TDK_NonDeducedMismatch;
1458 }
1459
1460 // If the parameter type is not dependent, there is nothing to deduce.
1461 if (!Param->isDependentType()) {
1462 if (!(TDF & TDF_SkipNonDependent)) {
1463 bool NonDeduced =
1464 (TDF & TDF_AllowCompatibleFunctionType)
1465 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1466 : Param != Arg;
1467 if (NonDeduced) {
1468 return Sema::TDK_NonDeducedMismatch;
1469 }
1470 }
1471 return Sema::TDK_Success;
1472 }
1473 } else if (!Param->isDependentType()) {
1474 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1475 ArgUnqualType = CanArg.getUnqualifiedType();
1476 bool Success =
1477 (TDF & TDF_AllowCompatibleFunctionType)
1478 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1479 : ParamUnqualType == ArgUnqualType;
1480 if (Success)
1481 return Sema::TDK_Success;
1482 }
1483
1484 switch (Param->getTypeClass()) {
1485 // Non-canonical types cannot appear here.
1486#define NON_CANONICAL_TYPE(Class, Base) \
1487 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class)::llvm::llvm_unreachable_internal("deducing non-canonical type: "
#Class, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1487)
;
1488#define TYPE(Class, Base)
1489#include "clang/AST/TypeNodes.inc"
1490
1491 case Type::TemplateTypeParm:
1492 case Type::SubstTemplateTypeParmPack:
1493 llvm_unreachable("Type nodes handled above")::llvm::llvm_unreachable_internal("Type nodes handled above",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1493)
;
1494
1495 // These types cannot be dependent, so simply check whether the types are
1496 // the same.
1497 case Type::Builtin:
1498 case Type::VariableArray:
1499 case Type::Vector:
1500 case Type::FunctionNoProto:
1501 case Type::Record:
1502 case Type::Enum:
1503 case Type::ObjCObject:
1504 case Type::ObjCInterface:
1505 case Type::ObjCObjectPointer:
1506 if (TDF & TDF_SkipNonDependent)
1507 return Sema::TDK_Success;
1508
1509 if (TDF & TDF_IgnoreQualifiers) {
1510 Param = Param.getUnqualifiedType();
1511 Arg = Arg.getUnqualifiedType();
1512 }
1513
1514 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1515
1516 // _Complex T [placeholder extension]
1517 case Type::Complex:
1518 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1519 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1520 cast<ComplexType>(Param)->getElementType(),
1521 ComplexArg->getElementType(),
1522 Info, Deduced, TDF);
1523
1524 return Sema::TDK_NonDeducedMismatch;
1525
1526 // _Atomic T [extension]
1527 case Type::Atomic:
1528 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1529 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1530 cast<AtomicType>(Param)->getValueType(),
1531 AtomicArg->getValueType(),
1532 Info, Deduced, TDF);
1533
1534 return Sema::TDK_NonDeducedMismatch;
1535
1536 // T *
1537 case Type::Pointer: {
1538 QualType PointeeType;
1539 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1540 PointeeType = PointerArg->getPointeeType();
1541 } else if (const ObjCObjectPointerType *PointerArg
1542 = Arg->getAs<ObjCObjectPointerType>()) {
1543 PointeeType = PointerArg->getPointeeType();
1544 } else {
1545 return Sema::TDK_NonDeducedMismatch;
1546 }
1547
1548 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1549 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1550 cast<PointerType>(Param)->getPointeeType(),
1551 PointeeType,
1552 Info, Deduced, SubTDF);
1553 }
1554
1555 // T &
1556 case Type::LValueReference: {
1557 const LValueReferenceType *ReferenceArg =
1558 Arg->getAs<LValueReferenceType>();
1559 if (!ReferenceArg)
1560 return Sema::TDK_NonDeducedMismatch;
1561
1562 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1563 cast<LValueReferenceType>(Param)->getPointeeType(),
1564 ReferenceArg->getPointeeType(), Info, Deduced, 0);
1565 }
1566
1567 // T && [C++0x]
1568 case Type::RValueReference: {
1569 const RValueReferenceType *ReferenceArg =
1570 Arg->getAs<RValueReferenceType>();
1571 if (!ReferenceArg)
1572 return Sema::TDK_NonDeducedMismatch;
1573
1574 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1575 cast<RValueReferenceType>(Param)->getPointeeType(),
1576 ReferenceArg->getPointeeType(),
1577 Info, Deduced, 0);
1578 }
1579
1580 // T [] (implied, but not stated explicitly)
1581 case Type::IncompleteArray: {
1582 const IncompleteArrayType *IncompleteArrayArg =
1583 S.Context.getAsIncompleteArrayType(Arg);
1584 if (!IncompleteArrayArg)
1585 return Sema::TDK_NonDeducedMismatch;
1586
1587 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1588 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1589 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1590 IncompleteArrayArg->getElementType(),
1591 Info, Deduced, SubTDF);
1592 }
1593
1594 // T [integer-constant]
1595 case Type::ConstantArray: {
1596 const ConstantArrayType *ConstantArrayArg =
1597 S.Context.getAsConstantArrayType(Arg);
1598 if (!ConstantArrayArg)
1599 return Sema::TDK_NonDeducedMismatch;
1600
1601 const ConstantArrayType *ConstantArrayParm =
1602 S.Context.getAsConstantArrayType(Param);
1603 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1604 return Sema::TDK_NonDeducedMismatch;
1605
1606 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1607 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1608 ConstantArrayParm->getElementType(),
1609 ConstantArrayArg->getElementType(),
1610 Info, Deduced, SubTDF);
1611 }
1612
1613 // type [i]
1614 case Type::DependentSizedArray: {
1615 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1616 if (!ArrayArg)
1617 return Sema::TDK_NonDeducedMismatch;
1618
1619 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1620
1621 // Check the element type of the arrays
1622 const DependentSizedArrayType *DependentArrayParm
1623 = S.Context.getAsDependentSizedArrayType(Param);
1624 if (Sema::TemplateDeductionResult Result
1625 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1626 DependentArrayParm->getElementType(),
1627 ArrayArg->getElementType(),
1628 Info, Deduced, SubTDF))
1629 return Result;
1630
1631 // Determine the array bound is something we can deduce.
1632 NonTypeTemplateParmDecl *NTTP
1633 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
1634 if (!NTTP)
1635 return Sema::TDK_Success;
1636
1637 // We can perform template argument deduction for the given non-type
1638 // template parameter.
1639 assert(NTTP->getDepth() == Info.getDeducedDepth() &&((NTTP->getDepth() == Info.getDeducedDepth() && "saw non-type template parameter with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1640, __PRETTY_FUNCTION__))
1640 "saw non-type template parameter with wrong depth")((NTTP->getDepth() == Info.getDeducedDepth() && "saw non-type template parameter with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1640, __PRETTY_FUNCTION__))
;
1641 if (const ConstantArrayType *ConstantArrayArg
1642 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1643 llvm::APSInt Size(ConstantArrayArg->getSize());
1644 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
1645 S.Context.getSizeType(),
1646 /*ArrayBound=*/true,
1647 Info, Deduced);
1648 }
1649 if (const DependentSizedArrayType *DependentArrayArg
1650 = dyn_cast<DependentSizedArrayType>(ArrayArg))
1651 if (DependentArrayArg->getSizeExpr())
1652 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1653 DependentArrayArg->getSizeExpr(),
1654 Info, Deduced);
1655
1656 // Incomplete type does not match a dependently-sized array type
1657 return Sema::TDK_NonDeducedMismatch;
1658 }
1659
1660 // type(*)(T)
1661 // T(*)()
1662 // T(*)(T)
1663 case Type::FunctionProto: {
1664 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1665 const FunctionProtoType *FunctionProtoArg =
1666 dyn_cast<FunctionProtoType>(Arg);
1667 if (!FunctionProtoArg)
1668 return Sema::TDK_NonDeducedMismatch;
1669
1670 const FunctionProtoType *FunctionProtoParam =
1671 cast<FunctionProtoType>(Param);
1672
1673 if (FunctionProtoParam->getMethodQuals()
1674 != FunctionProtoArg->getMethodQuals() ||
1675 FunctionProtoParam->getRefQualifier()
1676 != FunctionProtoArg->getRefQualifier() ||
1677 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1678 return Sema::TDK_NonDeducedMismatch;
1679
1680 // Check return types.
1681 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1682 S, TemplateParams, FunctionProtoParam->getReturnType(),
1683 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
1684 return Result;
1685
1686 // Check parameter types.
1687 if (auto Result = DeduceTemplateArguments(
1688 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1689 FunctionProtoParam->getNumParams(),
1690 FunctionProtoArg->param_type_begin(),
1691 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1692 return Result;
1693
1694 if (TDF & TDF_AllowCompatibleFunctionType)
1695 return Sema::TDK_Success;
1696
1697 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1698 // deducing through the noexcept-specifier if it's part of the canonical
1699 // type. libstdc++ relies on this.
1700 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1701 if (NonTypeTemplateParmDecl *NTTP =
1702 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1703 : nullptr) {
1704 assert(NTTP->getDepth() == Info.getDeducedDepth() &&((NTTP->getDepth() == Info.getDeducedDepth() && "saw non-type template parameter with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1705, __PRETTY_FUNCTION__))
1705 "saw non-type template parameter with wrong depth")((NTTP->getDepth() == Info.getDeducedDepth() && "saw non-type template parameter with wrong depth"
) ? static_cast<void> (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1705, __PRETTY_FUNCTION__))
;
1706
1707 llvm::APSInt Noexcept(1);
1708 switch (FunctionProtoArg->canThrow()) {
1709 case CT_Cannot:
1710 Noexcept = 1;
1711 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1712
1713 case CT_Can:
1714 // We give E in noexcept(E) the "deduced from array bound" treatment.
1715 // FIXME: Should we?
1716 return DeduceNonTypeTemplateArgument(
1717 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1718 /*ArrayBound*/true, Info, Deduced);
1719
1720 case CT_Dependent:
1721 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1722 return DeduceNonTypeTemplateArgument(
1723 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1724 // Can't deduce anything from throw(T...).
1725 break;
1726 }
1727 }
1728 // FIXME: Detect non-deduced exception specification mismatches?
1729 //
1730 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1731 // top-level differences in noexcept-specifications.
1732
1733 return Sema::TDK_Success;
1734 }
1735
1736 case Type::InjectedClassName:
1737 // Treat a template's injected-class-name as if the template
1738 // specialization type had been used.
1739 Param = cast<InjectedClassNameType>(Param)
1740 ->getInjectedSpecializationType();
1741 assert(isa<TemplateSpecializationType>(Param) &&((isa<TemplateSpecializationType>(Param) && "injected class name is not a template specialization type"
) ? static_cast<void> (0) : __assert_fail ("isa<TemplateSpecializationType>(Param) && \"injected class name is not a template specialization type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1742, __PRETTY_FUNCTION__))
1742 "injected class name is not a template specialization type")((isa<TemplateSpecializationType>(Param) && "injected class name is not a template specialization type"
) ? static_cast<void> (0) : __assert_fail ("isa<TemplateSpecializationType>(Param) && \"injected class name is not a template specialization type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1742, __PRETTY_FUNCTION__))
;
1743 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1744
1745 // template-name<T> (where template-name refers to a class template)
1746 // template-name<i>
1747 // TT<T>
1748 // TT<i>
1749 // TT<>
1750 case Type::TemplateSpecialization: {
1751 const TemplateSpecializationType *SpecParam =
1752 cast<TemplateSpecializationType>(Param);
1753
1754 // When Arg cannot be a derived class, we can just try to deduce template
1755 // arguments from the template-id.
1756 const RecordType *RecordT = Arg->getAs<RecordType>();
1757 if (!(TDF & TDF_DerivedClass) || !RecordT)
1758 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1759 Deduced);
1760
1761 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1762 Deduced.end());
1763
1764 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1765 S, TemplateParams, SpecParam, Arg, Info, Deduced);
1766
1767 if (Result == Sema::TDK_Success)
1768 return Result;
1769
1770 // We cannot inspect base classes as part of deduction when the type
1771 // is incomplete, so either instantiate any templates necessary to
1772 // complete the type, or skip over it if it cannot be completed.
1773 if (!S.isCompleteType(Info.getLocation(), Arg))
1774 return Result;
1775
1776 // C++14 [temp.deduct.call] p4b3:
1777 // If P is a class and P has the form simple-template-id, then the
1778 // transformed A can be a derived class of the deduced A. Likewise if
1779 // P is a pointer to a class of the form simple-template-id, the
1780 // transformed A can be a pointer to a derived class pointed to by the
1781 // deduced A.
1782 //
1783 // These alternatives are considered only if type deduction would
1784 // otherwise fail. If they yield more than one possible deduced A, the
1785 // type deduction fails.
1786
1787 // Reset the incorrectly deduced argument from above.
1788 Deduced = DeducedOrig;
1789
1790 // Use data recursion to crawl through the list of base classes.
1791 // Visited contains the set of nodes we have already visited, while
1792 // ToVisit is our stack of records that we still need to visit.
1793 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1794 SmallVector<const RecordType *, 8> ToVisit;
1795 ToVisit.push_back(RecordT);
1796 bool Successful = false;
1797 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
1798 while (!ToVisit.empty()) {
1799 // Retrieve the next class in the inheritance hierarchy.
1800 const RecordType *NextT = ToVisit.pop_back_val();
1801
1802 // If we have already seen this type, skip it.
1803 if (!Visited.insert(NextT).second)
1804 continue;
1805
1806 // If this is a base class, try to perform template argument
1807 // deduction from it.
1808 if (NextT != RecordT) {
1809 TemplateDeductionInfo BaseInfo(Info.getLocation());
1810 Sema::TemplateDeductionResult BaseResult =
1811 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1812 QualType(NextT, 0), BaseInfo, Deduced);
1813
1814 // If template argument deduction for this base was successful,
1815 // note that we had some success. Otherwise, ignore any deductions
1816 // from this base class.
1817 if (BaseResult == Sema::TDK_Success) {
1818 // If we've already seen some success, then deduction fails due to
1819 // an ambiguity (temp.deduct.call p5).
1820 if (Successful)
1821 return Sema::TDK_MiscellaneousDeductionFailure;
1822
1823 Successful = true;
1824 std::swap(SuccessfulDeduced, Deduced);
1825
1826 Info.Param = BaseInfo.Param;
1827 Info.FirstArg = BaseInfo.FirstArg;
1828 Info.SecondArg = BaseInfo.SecondArg;
1829 }
1830
1831 Deduced = DeducedOrig;
1832 }
1833
1834 // Visit base classes
1835 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1836 for (const auto &Base : Next->bases()) {
1837 assert(Base.getType()->isRecordType() &&((Base.getType()->isRecordType() && "Base class that isn't a record?"
) ? static_cast<void> (0) : __assert_fail ("Base.getType()->isRecordType() && \"Base class that isn't a record?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1838, __PRETTY_FUNCTION__))
1838 "Base class that isn't a record?")((Base.getType()->isRecordType() && "Base class that isn't a record?"
) ? static_cast<void> (0) : __assert_fail ("Base.getType()->isRecordType() && \"Base class that isn't a record?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 1838, __PRETTY_FUNCTION__))
;
1839 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1840 }
1841 }
1842
1843 if (Successful) {
1844 std::swap(SuccessfulDeduced, Deduced);
1845 return Sema::TDK_Success;
1846 }
1847
1848 return Result;
1849 }
1850
1851 // T type::*
1852 // T T::*
1853 // T (type::*)()
1854 // type (T::*)()
1855 // type (type::*)(T)
1856 // type (T::*)(T)
1857 // T (type::*)(T)
1858 // T (T::*)()
1859 // T (T::*)(T)
1860 case Type::MemberPointer: {
1861 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1862 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1863 if (!MemPtrArg)
1864 return Sema::TDK_NonDeducedMismatch;
1865
1866 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1867 if (ParamPointeeType->isFunctionType())
1868 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1869 /*IsCtorOrDtor=*/false, Info.getLocation());
1870 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1871 if (ArgPointeeType->isFunctionType())
1872 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1873 /*IsCtorOrDtor=*/false, Info.getLocation());
1874
1875 if (Sema::TemplateDeductionResult Result
1876 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1877 ParamPointeeType,
1878 ArgPointeeType,
1879 Info, Deduced,
1880 TDF & TDF_IgnoreQualifiers))
1881 return Result;
1882
1883 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1884 QualType(MemPtrParam->getClass(), 0),
1885 QualType(MemPtrArg->getClass(), 0),
1886 Info, Deduced,
1887 TDF & TDF_IgnoreQualifiers);
1888 }
1889
1890 // (clang extension)
1891 //
1892 // type(^)(T)
1893 // T(^)()
1894 // T(^)(T)
1895 case Type::BlockPointer: {
1896 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1897 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1898
1899 if (!BlockPtrArg)
1900 return Sema::TDK_NonDeducedMismatch;
1901
1902 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1903 BlockPtrParam->getPointeeType(),
1904 BlockPtrArg->getPointeeType(),
1905 Info, Deduced, 0);
1906 }
1907
1908 // (clang extension)
1909 //
1910 // T __attribute__(((ext_vector_type(<integral constant>))))
1911 case Type::ExtVector: {
1912 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1913 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1914 // Make sure that the vectors have the same number of elements.
1915 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1916 return Sema::TDK_NonDeducedMismatch;
1917
1918 // Perform deduction on the element types.
1919 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1920 VectorParam->getElementType(),
1921 VectorArg->getElementType(),
1922 Info, Deduced, TDF);
1923 }
1924
1925 if (const DependentSizedExtVectorType *VectorArg
1926 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1927 // We can't check the number of elements, since the argument has a
1928 // dependent number of elements. This can only occur during partial
1929 // ordering.
1930
1931 // Perform deduction on the element types.
1932 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1933 VectorParam->getElementType(),
1934 VectorArg->getElementType(),
1935 Info, Deduced, TDF);
1936 }
1937
1938 return Sema::TDK_NonDeducedMismatch;
1939 }
1940
1941 case Type::DependentVector: {
1942 const auto *VectorParam = cast<DependentVectorType>(Param);
1943
1944 if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) {
1945 // Perform deduction on the element types.
1946 if (Sema::TemplateDeductionResult Result =
1947 DeduceTemplateArgumentsByTypeMatch(
1948 S, TemplateParams, VectorParam->getElementType(),
1949 VectorArg->getElementType(), Info, Deduced, TDF))
1950 return Result;
1951
1952 // Perform deduction on the vector size, if we can.
1953 NonTypeTemplateParmDecl *NTTP =
1954 getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1955 if (!NTTP)
1956 return Sema::TDK_Success;
1957
1958 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1959 ArgSize = VectorArg->getNumElements();
1960 // Note that we use the "array bound" rules here; just like in that
1961 // case, we don't have any particular type for the vector size, but
1962 // we can provide one if necessary.
1963 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1964 S.Context.UnsignedIntTy, true,
1965 Info, Deduced);
1966 }
1967
1968 if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) {
1969 // Perform deduction on the element types.
1970 if (Sema::TemplateDeductionResult Result =
1971 DeduceTemplateArgumentsByTypeMatch(
1972 S, TemplateParams, VectorParam->getElementType(),
1973 VectorArg->getElementType(), Info, Deduced, TDF))
1974 return Result;
1975
1976 // Perform deduction on the vector size, if we can.
1977 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1978 Info, VectorParam->getSizeExpr());
1979 if (!NTTP)
1980 return Sema::TDK_Success;
1981
1982 return DeduceNonTypeTemplateArgument(
1983 S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced);
1984 }
1985
1986 return Sema::TDK_NonDeducedMismatch;
1987 }
1988
1989 // (clang extension)
1990 //
1991 // T __attribute__(((ext_vector_type(N))))
1992 case Type::DependentSizedExtVector: {
1993 const DependentSizedExtVectorType *VectorParam
1994 = cast<DependentSizedExtVectorType>(Param);
1995
1996 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1997 // Perform deduction on the element types.
1998 if (Sema::TemplateDeductionResult Result
1999 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2000 VectorParam->getElementType(),
2001 VectorArg->getElementType(),
2002 Info, Deduced, TDF))
2003 return Result;
2004
2005 // Perform deduction on the vector size, if we can.
2006 NonTypeTemplateParmDecl *NTTP
2007 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2008 if (!NTTP)
2009 return Sema::TDK_Success;
2010
2011 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2012 ArgSize = VectorArg->getNumElements();
2013 // Note that we use the "array bound" rules here; just like in that
2014 // case, we don't have any particular type for the vector size, but
2015 // we can provide one if necessary.
2016 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2017 S.Context.IntTy, true, Info,
2018 Deduced);
2019 }
2020
2021 if (const DependentSizedExtVectorType *VectorArg
2022 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
2023 // Perform deduction on the element types.
2024 if (Sema::TemplateDeductionResult Result
2025 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2026 VectorParam->getElementType(),
2027 VectorArg->getElementType(),
2028 Info, Deduced, TDF))
2029 return Result;
2030
2031 // Perform deduction on the vector size, if we can.
2032 NonTypeTemplateParmDecl *NTTP
2033 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
2034 if (!NTTP)
2035 return Sema::TDK_Success;
2036
2037 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2038 VectorArg->getSizeExpr(),
2039 Info, Deduced);
2040 }
2041
2042 return Sema::TDK_NonDeducedMismatch;
2043 }
2044
2045 // (clang extension)
2046 //
2047 // T __attribute__(((address_space(N))))
2048 case Type::DependentAddressSpace: {
2049 const DependentAddressSpaceType *AddressSpaceParam =
2050 cast<DependentAddressSpaceType>(Param);
2051
2052 if (const DependentAddressSpaceType *AddressSpaceArg =
2053 dyn_cast<DependentAddressSpaceType>(Arg)) {
2054 // Perform deduction on the pointer type.
2055 if (Sema::TemplateDeductionResult Result =
2056 DeduceTemplateArgumentsByTypeMatch(
2057 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2058 AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
2059 return Result;
2060
2061 // Perform deduction on the address space, if we can.
2062 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2063 Info, AddressSpaceParam->getAddrSpaceExpr());
2064 if (!NTTP)
2065 return Sema::TDK_Success;
2066
2067 return DeduceNonTypeTemplateArgument(
2068 S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
2069 Deduced);
2070 }
2071
2072 if (isTargetAddressSpace(Arg.getAddressSpace())) {
2073 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2074 false);
2075 ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
2076
2077 // Perform deduction on the pointer types.
2078 if (Sema::TemplateDeductionResult Result =
2079 DeduceTemplateArgumentsByTypeMatch(
2080 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2081 S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
2082 return Result;
2083
2084 // Perform deduction on the address space, if we can.
2085 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2086 Info, AddressSpaceParam->getAddrSpaceExpr());
2087 if (!NTTP)
2088 return Sema::TDK_Success;
2089
2090 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2091 ArgAddressSpace, S.Context.IntTy,
2092 true, Info, Deduced);
2093 }
2094
2095 return Sema::TDK_NonDeducedMismatch;
2096 }
2097
2098 case Type::TypeOfExpr:
2099 case Type::TypeOf:
2100 case Type::DependentName:
2101 case Type::UnresolvedUsing:
2102 case Type::Decltype:
2103 case Type::UnaryTransform:
2104 case Type::Auto:
2105 case Type::DeducedTemplateSpecialization:
2106 case Type::DependentTemplateSpecialization:
2107 case Type::PackExpansion:
2108 case Type::Pipe:
2109 // No template argument deduction for these types
2110 return Sema::TDK_Success;
2111 }
2112
2113 llvm_unreachable("Invalid Type Class!")::llvm::llvm_unreachable_internal("Invalid Type Class!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2113)
;
2114}
2115
2116static Sema::TemplateDeductionResult
2117DeduceTemplateArguments(Sema &S,
2118 TemplateParameterList *TemplateParams,
2119 const TemplateArgument &Param,
2120 TemplateArgument Arg,
2121 TemplateDeductionInfo &Info,
2122 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2123 // If the template argument is a pack expansion, perform template argument
2124 // deduction against the pattern of that expansion. This only occurs during
2125 // partial ordering.
2126 if (Arg.isPackExpansion())
2127 Arg = Arg.getPackExpansionPattern();
2128
2129 switch (Param.getKind()) {
2130 case TemplateArgument::Null:
2131 llvm_unreachable("Null template argument in parameter list")::llvm::llvm_unreachable_internal("Null template argument in parameter list"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2131)
;
2132
2133 case TemplateArgument::Type:
2134 if (Arg.getKind() == TemplateArgument::Type)
2135 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2136 Param.getAsType(),
2137 Arg.getAsType(),
2138 Info, Deduced, 0);
2139 Info.FirstArg = Param;
2140 Info.SecondArg = Arg;
2141 return Sema::TDK_NonDeducedMismatch;
2142
2143 case TemplateArgument::Template:
2144 if (Arg.getKind() == TemplateArgument::Template)
2145 return DeduceTemplateArguments(S, TemplateParams,
2146 Param.getAsTemplate(),
2147 Arg.getAsTemplate(), Info, Deduced);
2148 Info.FirstArg = Param;
2149 Info.SecondArg = Arg;
2150 return Sema::TDK_NonDeducedMismatch;
2151
2152 case TemplateArgument::TemplateExpansion:
2153 llvm_unreachable("caller should handle pack expansions")::llvm::llvm_unreachable_internal("caller should handle pack expansions"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2153)
;
2154
2155 case TemplateArgument::Declaration:
2156 if (Arg.getKind() == TemplateArgument::Declaration &&
2157 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
2158 return Sema::TDK_Success;
2159
2160 Info.FirstArg = Param;
2161 Info.SecondArg = Arg;
2162 return Sema::TDK_NonDeducedMismatch;
2163
2164 case TemplateArgument::NullPtr:
2165 if (Arg.getKind() == TemplateArgument::NullPtr &&
2166 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
2167 return Sema::TDK_Success;
2168
2169 Info.FirstArg = Param;
2170 Info.SecondArg = Arg;
2171 return Sema::TDK_NonDeducedMismatch;
2172
2173 case TemplateArgument::Integral:
2174 if (Arg.getKind() == TemplateArgument::Integral) {
2175 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
2176 return Sema::TDK_Success;
2177
2178 Info.FirstArg = Param;
2179 Info.SecondArg = Arg;
2180 return Sema::TDK_NonDeducedMismatch;
2181 }
2182
2183 if (Arg.getKind() == TemplateArgument::Expression) {
2184 Info.FirstArg = Param;
2185 Info.SecondArg = Arg;
2186 return Sema::TDK_NonDeducedMismatch;
2187 }
2188
2189 Info.FirstArg = Param;
2190 Info.SecondArg = Arg;
2191 return Sema::TDK_NonDeducedMismatch;
2192
2193 case TemplateArgument::Expression:
2194 if (NonTypeTemplateParmDecl *NTTP
2195 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
2196 if (Arg.getKind() == TemplateArgument::Integral)
2197 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2198 Arg.getAsIntegral(),
2199 Arg.getIntegralType(),
2200 /*ArrayBound=*/false,
2201 Info, Deduced);
2202 if (Arg.getKind() == TemplateArgument::NullPtr)
2203 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2204 Arg.getNullPtrType(),
2205 Info, Deduced);
2206 if (Arg.getKind() == TemplateArgument::Expression)
2207 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2208 Arg.getAsExpr(), Info, Deduced);
2209 if (Arg.getKind() == TemplateArgument::Declaration)
2210 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2211 Arg.getAsDecl(),
2212 Arg.getParamTypeForDecl(),
2213 Info, Deduced);
2214
2215 Info.FirstArg = Param;
2216 Info.SecondArg = Arg;
2217 return Sema::TDK_NonDeducedMismatch;
2218 }
2219
2220 // Can't deduce anything, but that's okay.
2221 return Sema::TDK_Success;
2222
2223 case TemplateArgument::Pack:
2224 llvm_unreachable("Argument packs should be expanded by the caller!")::llvm::llvm_unreachable_internal("Argument packs should be expanded by the caller!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2224)
;
2225 }
2226
2227 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2227)
;
2228}
2229
2230/// Determine whether there is a template argument to be used for
2231/// deduction.
2232///
2233/// This routine "expands" argument packs in-place, overriding its input
2234/// parameters so that \c Args[ArgIdx] will be the available template argument.
2235///
2236/// \returns true if there is another template argument (which will be at
2237/// \c Args[ArgIdx]), false otherwise.
2238static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2239 unsigned &ArgIdx) {
2240 if (ArgIdx == Args.size())
2241 return false;
2242
2243 const TemplateArgument &Arg = Args[ArgIdx];
2244 if (Arg.getKind() != TemplateArgument::Pack)
2245 return true;
2246
2247 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?")((ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?"
) ? static_cast<void> (0) : __assert_fail ("ArgIdx == Args.size() - 1 && \"Pack not at the end of argument list?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2247, __PRETTY_FUNCTION__))
;
2248 Args = Arg.pack_elements();
2249 ArgIdx = 0;
2250 return ArgIdx < Args.size();
2251}
2252
2253/// Determine whether the given set of template arguments has a pack
2254/// expansion that is not the last template argument.
2255static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2256 bool FoundPackExpansion = false;
2257 for (const auto &A : Args) {
2258 if (FoundPackExpansion)
2259 return true;
2260
2261 if (A.getKind() == TemplateArgument::Pack)
2262 return hasPackExpansionBeforeEnd(A.pack_elements());
2263
2264 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2265 // templates, it should not be treated as a pack expansion.
2266 if (A.isPackExpansion())
2267 FoundPackExpansion = true;
2268 }
2269
2270 return false;
2271}
2272
2273static Sema::TemplateDeductionResult
2274DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2275 ArrayRef<TemplateArgument> Params,
2276 ArrayRef<TemplateArgument> Args,
2277 TemplateDeductionInfo &Info,
2278 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2279 bool NumberOfArgumentsMustMatch) {
2280 // C++0x [temp.deduct.type]p9:
2281 // If the template argument list of P contains a pack expansion that is not
2282 // the last template argument, the entire template argument list is a
2283 // non-deduced context.
2284 if (hasPackExpansionBeforeEnd(Params))
2285 return Sema::TDK_Success;
2286
2287 // C++0x [temp.deduct.type]p9:
2288 // If P has a form that contains <T> or <i>, then each argument Pi of the
2289 // respective template argument list P is compared with the corresponding
2290 // argument Ai of the corresponding template argument list of A.
2291 unsigned ArgIdx = 0, ParamIdx = 0;
2292 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
2293 if (!Params[ParamIdx].isPackExpansion()) {
2294 // The simple case: deduce template arguments by matching Pi and Ai.
2295
2296 // Check whether we have enough arguments.
2297 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
2298 return NumberOfArgumentsMustMatch
2299 ? Sema::TDK_MiscellaneousDeductionFailure
2300 : Sema::TDK_Success;
2301
2302 // C++1z [temp.deduct.type]p9:
2303 // During partial ordering, if Ai was originally a pack expansion [and]
2304 // Pi is not a pack expansion, template argument deduction fails.
2305 if (Args[ArgIdx].isPackExpansion())
2306 return Sema::TDK_MiscellaneousDeductionFailure;
2307
2308 // Perform deduction for this Pi/Ai pair.
2309 if (Sema::TemplateDeductionResult Result
2310 = DeduceTemplateArguments(S, TemplateParams,
2311 Params[ParamIdx], Args[ArgIdx],
2312 Info, Deduced))
2313 return Result;
2314
2315 // Move to the next argument.
2316 ++ArgIdx;
2317 continue;
2318 }
2319
2320 // The parameter is a pack expansion.
2321
2322 // C++0x [temp.deduct.type]p9:
2323 // If Pi is a pack expansion, then the pattern of Pi is compared with
2324 // each remaining argument in the template argument list of A. Each
2325 // comparison deduces template arguments for subsequent positions in the
2326 // template parameter packs expanded by Pi.
2327 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
2328
2329 // Prepare to deduce the packs within the pattern.
2330 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2331
2332 // Keep track of the deduced template arguments for each parameter pack
2333 // expanded by this pack expansion (the outer index) and for each
2334 // template argument (the inner SmallVectors).
2335 for (; hasTemplateArgumentForDeduction(Args, ArgIdx) &&
2336 PackScope.hasNextElement();
2337 ++ArgIdx) {
2338 // Deduce template arguments from the pattern.
2339 if (Sema::TemplateDeductionResult Result
2340 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2341 Info, Deduced))
2342 return Result;
2343
2344 PackScope.nextPackElement();
2345 }
2346
2347 // Build argument packs for each of the parameter packs expanded by this
2348 // pack expansion.
2349 if (auto Result = PackScope.finish())
2350 return Result;
2351 }
2352
2353 return Sema::TDK_Success;
2354}
2355
2356static Sema::TemplateDeductionResult
2357DeduceTemplateArguments(Sema &S,
2358 TemplateParameterList *TemplateParams,
2359 const TemplateArgumentList &ParamList,
2360 const TemplateArgumentList &ArgList,
2361 TemplateDeductionInfo &Info,
2362 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2363 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
2364 ArgList.asArray(), Info, Deduced,
2365 /*NumberOfArgumentsMustMatch*/false);
2366}
2367
2368/// Determine whether two template arguments are the same.
2369static bool isSameTemplateArg(ASTContext &Context,
2370 TemplateArgument X,
2371 const TemplateArgument &Y,
2372 bool PackExpansionMatchesPack = false) {
2373 // If we're checking deduced arguments (X) against original arguments (Y),
2374 // we will have flattened packs to non-expansions in X.
2375 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2376 X = X.getPackExpansionPattern();
2377
2378 if (X.getKind() != Y.getKind())
2379 return false;
2380
2381 switch (X.getKind()) {
2382 case TemplateArgument::Null:
2383 llvm_unreachable("Comparing NULL template argument")::llvm::llvm_unreachable_internal("Comparing NULL template argument"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2383)
;
2384
2385 case TemplateArgument::Type:
2386 return Context.getCanonicalType(X.getAsType()) ==
2387 Context.getCanonicalType(Y.getAsType());
2388
2389 case TemplateArgument::Declaration:
2390 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2391
2392 case TemplateArgument::NullPtr:
2393 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2394
2395 case TemplateArgument::Template:
2396 case TemplateArgument::TemplateExpansion:
2397 return Context.getCanonicalTemplateName(
2398 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2399 Context.getCanonicalTemplateName(
2400 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
2401
2402 case TemplateArgument::Integral:
2403 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2404
2405 case TemplateArgument::Expression: {
2406 llvm::FoldingSetNodeID XID, YID;
2407 X.getAsExpr()->Profile(XID, Context, true);
2408 Y.getAsExpr()->Profile(YID, Context, true);
2409 return XID == YID;
2410 }
2411
2412 case TemplateArgument::Pack:
2413 if (X.pack_size() != Y.pack_size())
2414 return false;
2415
2416 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2417 XPEnd = X.pack_end(),
2418 YP = Y.pack_begin();
2419 XP != XPEnd; ++XP, ++YP)
2420 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
2421 return false;
2422
2423 return true;
2424 }
2425
2426 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2426)
;
2427}
2428
2429/// Allocate a TemplateArgumentLoc where all locations have
2430/// been initialized to the given location.
2431///
2432/// \param Arg The template argument we are producing template argument
2433/// location information for.
2434///
2435/// \param NTTPType For a declaration template argument, the type of
2436/// the non-type template parameter that corresponds to this template
2437/// argument. Can be null if no type sugar is available to add to the
2438/// type from the template argument.
2439///
2440/// \param Loc The source location to use for the resulting template
2441/// argument.
2442TemplateArgumentLoc
2443Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2444 QualType NTTPType, SourceLocation Loc) {
2445 switch (Arg.getKind()) {
2446 case TemplateArgument::Null:
2447 llvm_unreachable("Can't get a NULL template argument here")::llvm::llvm_unreachable_internal("Can't get a NULL template argument here"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2447)
;
2448
2449 case TemplateArgument::Type:
2450 return TemplateArgumentLoc(
2451 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2452
2453 case TemplateArgument::Declaration: {
2454 if (NTTPType.isNull())
2455 NTTPType = Arg.getParamTypeForDecl();
2456 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2457 .getAs<Expr>();
2458 return TemplateArgumentLoc(TemplateArgument(E), E);
2459 }
2460
2461 case TemplateArgument::NullPtr: {
2462 if (NTTPType.isNull())
2463 NTTPType = Arg.getNullPtrType();
2464 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2465 .getAs<Expr>();
2466 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2467 E);
2468 }
2469
2470 case TemplateArgument::Integral: {
2471 Expr *E =
2472 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2473 return TemplateArgumentLoc(TemplateArgument(E), E);
2474 }
2475
2476 case TemplateArgument::Template:
2477 case TemplateArgument::TemplateExpansion: {
2478 NestedNameSpecifierLocBuilder Builder;
2479 TemplateName Template = Arg.getAsTemplate();
2480 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2481 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2482 else if (QualifiedTemplateName *QTN =
2483 Template.getAsQualifiedTemplateName())
2484 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2485
2486 if (Arg.getKind() == TemplateArgument::Template)
2487 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2488 Loc);
2489
2490 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2491 Loc, Loc);
2492 }
2493
2494 case TemplateArgument::Expression:
2495 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2496
2497 case TemplateArgument::Pack:
2498 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2499 }
2500
2501 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2501)
;
2502}
2503
2504/// Convert the given deduced template argument and add it to the set of
2505/// fully-converted template arguments.
2506static bool
2507ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2508 DeducedTemplateArgument Arg,
2509 NamedDecl *Template,
2510 TemplateDeductionInfo &Info,
2511 bool IsDeduced,
2512 SmallVectorImpl<TemplateArgument> &Output) {
2513 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2514 unsigned ArgumentPackIndex) {
2515 // Convert the deduced template argument into a template
2516 // argument that we can check, almost as if the user had written
2517 // the template argument explicitly.
2518 TemplateArgumentLoc ArgLoc =
2519 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
2520
2521 // Check the template argument, converting it as necessary.
2522 return S.CheckTemplateArgument(
2523 Param, ArgLoc, Template, Template->getLocation(),
2524 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2525 IsDeduced
2526 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2527 : Sema::CTAK_Deduced)
2528 : Sema::CTAK_Specified);
2529 };
2530
2531 if (Arg.getKind() == TemplateArgument::Pack) {
2532 // This is a template argument pack, so check each of its arguments against
2533 // the template parameter.
2534 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2535 for (const auto &P : Arg.pack_elements()) {
2536 // When converting the deduced template argument, append it to the
2537 // general output list. We need to do this so that the template argument
2538 // checking logic has all of the prior template arguments available.
2539 DeducedTemplateArgument InnerArg(P);
2540 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2541 assert(InnerArg.getKind() != TemplateArgument::Pack &&((InnerArg.getKind() != TemplateArgument::Pack && "deduced nested pack"
) ? static_cast<void> (0) : __assert_fail ("InnerArg.getKind() != TemplateArgument::Pack && \"deduced nested pack\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2542, __PRETTY_FUNCTION__))
2542 "deduced nested pack")((InnerArg.getKind() != TemplateArgument::Pack && "deduced nested pack"
) ? static_cast<void> (0) : __assert_fail ("InnerArg.getKind() != TemplateArgument::Pack && \"deduced nested pack\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2542, __PRETTY_FUNCTION__))
;
2543 if (P.isNull()) {
2544 // We deduced arguments for some elements of this pack, but not for
2545 // all of them. This happens if we get a conditionally-non-deduced
2546 // context in a pack expansion (such as an overload set in one of the
2547 // arguments).
2548 S.Diag(Param->getLocation(),
2549 diag::err_template_arg_deduced_incomplete_pack)
2550 << Arg << Param;
2551 return true;
2552 }
2553 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
2554 return true;
2555
2556 // Move the converted template argument into our argument pack.
2557 PackedArgsBuilder.push_back(Output.pop_back_val());
2558 }
2559
2560 // If the pack is empty, we still need to substitute into the parameter
2561 // itself, in case that substitution fails.
2562 if (PackedArgsBuilder.empty()) {
2563 LocalInstantiationScope Scope(S);
2564 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
2565 MultiLevelTemplateArgumentList Args(TemplateArgs);
2566
2567 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2568 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2569 NTTP, Output,
2570 Template->getSourceRange());
2571 if (Inst.isInvalid() ||
2572 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2573 NTTP->getDeclName()).isNull())
2574 return true;
2575 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2576 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2577 TTP, Output,
2578 Template->getSourceRange());
2579 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2580 return true;
2581 }
2582 // For type parameters, no substitution is ever required.
2583 }
2584
2585 // Create the resulting argument pack.
2586 Output.push_back(
2587 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2588 return false;
2589 }
2590
2591 return ConvertArg(Arg, 0);
2592}
2593
2594// FIXME: This should not be a template, but
2595// ClassTemplatePartialSpecializationDecl sadly does not derive from
2596// TemplateDecl.
2597template<typename TemplateDeclT>
2598static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2599 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2600 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2601 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2602 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2603 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2604 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2605
2606 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2607 NamedDecl *Param = TemplateParams->getParam(I);
2608
2609 // C++0x [temp.arg.explicit]p3:
2610 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2611 // be deduced to an empty sequence of template arguments.
2612 // FIXME: Where did the word "trailing" come from?
2613 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2614 if (auto Result = PackDeductionScope(S, TemplateParams, Deduced, Info, I)
2615 .finish(/*TreatNoDeductionsAsNonDeduced*/false))
2616 return Result;
2617 }
2618
2619 if (!Deduced[I].isNull()) {
2620 if (I < NumAlreadyConverted) {
2621 // We may have had explicitly-specified template arguments for a
2622 // template parameter pack (that may or may not have been extended
2623 // via additional deduced arguments).
2624 if (Param->isParameterPack() && CurrentInstantiationScope &&
2625 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2626 // Forget the partially-substituted pack; its substitution is now
2627 // complete.
2628 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2629 // We still need to check the argument in case it was extended by
2630 // deduction.
2631 } else {
2632 // We have already fully type-checked and converted this
2633 // argument, because it was explicitly-specified. Just record the
2634 // presence of this argument.
2635 Builder.push_back(Deduced[I]);
2636 continue;
2637 }
2638 }
2639
2640 // We may have deduced this argument, so it still needs to be
2641 // checked and converted.
2642 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2643 IsDeduced, Builder)) {
2644 Info.Param = makeTemplateParameter(Param);
2645 // FIXME: These template arguments are temporary. Free them!
2646 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2647 return Sema::TDK_SubstitutionFailure;
2648 }
2649
2650 continue;
2651 }
2652
2653 // Substitute into the default template argument, if available.
2654 bool HasDefaultArg = false;
2655 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2656 if (!TD) {
2657 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||((isa<ClassTemplatePartialSpecializationDecl>(Template)
|| isa<VarTemplatePartialSpecializationDecl>(Template)
) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplatePartialSpecializationDecl>(Template) || isa<VarTemplatePartialSpecializationDecl>(Template)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2658, __PRETTY_FUNCTION__))
2658 isa<VarTemplatePartialSpecializationDecl>(Template))((isa<ClassTemplatePartialSpecializationDecl>(Template)
|| isa<VarTemplatePartialSpecializationDecl>(Template)
) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplatePartialSpecializationDecl>(Template) || isa<VarTemplatePartialSpecializationDecl>(Template)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2658, __PRETTY_FUNCTION__))
;
2659 return Sema::TDK_Incomplete;
2660 }
2661
2662 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2663 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2664 HasDefaultArg);
2665
2666 // If there was no default argument, deduction is incomplete.
2667 if (DefArg.getArgument().isNull()) {
2668 Info.Param = makeTemplateParameter(
2669 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2670 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2671 if (PartialOverloading) break;
2672
2673 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2674 : Sema::TDK_Incomplete;
2675 }
2676
2677 // Check whether we can actually use the default argument.
2678 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2679 TD->getSourceRange().getEnd(), 0, Builder,
2680 Sema::CTAK_Specified)) {
2681 Info.Param = makeTemplateParameter(
2682 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2683 // FIXME: These template arguments are temporary. Free them!
2684 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2685 return Sema::TDK_SubstitutionFailure;
2686 }
2687
2688 // If we get here, we successfully used the default template argument.
2689 }
2690
2691 return Sema::TDK_Success;
2692}
2693
2694static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2695 if (auto *DC = dyn_cast<DeclContext>(D))
2696 return DC;
2697 return D->getDeclContext();
2698}
2699
2700template<typename T> struct IsPartialSpecialization {
2701 static constexpr bool value = false;
2702};
2703template<>
2704struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2705 static constexpr bool value = true;
2706};
2707template<>
2708struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2709 static constexpr bool value = true;
2710};
2711
2712/// Complete template argument deduction for a partial specialization.
2713template <typename T>
2714static typename std::enable_if<IsPartialSpecialization<T>::value,
2715 Sema::TemplateDeductionResult>::type
2716FinishTemplateArgumentDeduction(
2717 Sema &S, T *Partial, bool IsPartialOrdering,
2718 const TemplateArgumentList &TemplateArgs,
2719 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2720 TemplateDeductionInfo &Info) {
2721 // Unevaluated SFINAE context.
2722 EnterExpressionEvaluationContext Unevaluated(
2723 S, Sema::ExpressionEvaluationContext::Unevaluated);
2724 Sema::SFINAETrap Trap(S);
2725
2726 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2727
2728 // C++ [temp.deduct.type]p2:
2729 // [...] or if any template argument remains neither deduced nor
2730 // explicitly specified, template argument deduction fails.
2731 SmallVector<TemplateArgument, 4> Builder;
2732 if (auto Result = ConvertDeducedTemplateArguments(
2733 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
2734 return Result;
2735
2736 // Form the template argument list from the deduced template arguments.
2737 TemplateArgumentList *DeducedArgumentList
2738 = TemplateArgumentList::CreateCopy(S.Context, Builder);
2739
2740 Info.reset(DeducedArgumentList);
2741
2742 // Substitute the deduced template arguments into the template
2743 // arguments of the class template partial specialization, and
2744 // verify that the instantiated template arguments are both valid
2745 // and are equivalent to the template arguments originally provided
2746 // to the class template.
2747 LocalInstantiationScope InstScope(S);
2748 auto *Template = Partial->getSpecializedTemplate();
2749 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2750 Partial->getTemplateArgsAsWritten();
2751 const TemplateArgumentLoc *PartialTemplateArgs =
2752 PartialTemplArgInfo->getTemplateArgs();
2753
2754 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2755 PartialTemplArgInfo->RAngleLoc);
2756
2757 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2758 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2759 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2760 if (ParamIdx >= Partial->getTemplateParameters()->size())
2761 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2762
2763 Decl *Param = const_cast<NamedDecl *>(
2764 Partial->getTemplateParameters()->getParam(ParamIdx));
2765 Info.Param = makeTemplateParameter(Param);
2766 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2767 return Sema::TDK_SubstitutionFailure;
2768 }
2769
2770 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2771 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2772 false, ConvertedInstArgs))
2773 return Sema::TDK_SubstitutionFailure;
2774
2775 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2776 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2777 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2778 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2779 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2780 Info.FirstArg = TemplateArgs[I];
2781 Info.SecondArg = InstArg;
2782 return Sema::TDK_NonDeducedMismatch;
2783 }
2784 }
2785
2786 if (Trap.hasErrorOccurred())
2787 return Sema::TDK_SubstitutionFailure;
2788
2789 return Sema::TDK_Success;
2790}
2791
2792/// Complete template argument deduction for a class or variable template,
2793/// when partial ordering against a partial specialization.
2794// FIXME: Factor out duplication with partial specialization version above.
2795static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2796 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2797 const TemplateArgumentList &TemplateArgs,
2798 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2799 TemplateDeductionInfo &Info) {
2800 // Unevaluated SFINAE context.
2801 EnterExpressionEvaluationContext Unevaluated(
2802 S, Sema::ExpressionEvaluationContext::Unevaluated);
2803 Sema::SFINAETrap Trap(S);
2804
2805 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2806
2807 // C++ [temp.deduct.type]p2:
2808 // [...] or if any template argument remains neither deduced nor
2809 // explicitly specified, template argument deduction fails.
2810 SmallVector<TemplateArgument, 4> Builder;
2811 if (auto Result = ConvertDeducedTemplateArguments(
2812 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2813 return Result;
2814
2815 // Check that we produced the correct argument list.
2816 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2817 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2818 TemplateArgument InstArg = Builder[I];
2819 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2820 /*PackExpansionMatchesPack*/true)) {
2821 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2822 Info.FirstArg = TemplateArgs[I];
2823 Info.SecondArg = InstArg;
2824 return Sema::TDK_NonDeducedMismatch;
2825 }
2826 }
2827
2828 if (Trap.hasErrorOccurred())
2829 return Sema::TDK_SubstitutionFailure;
2830
2831 return Sema::TDK_Success;
2832}
2833
2834
2835/// Perform template argument deduction to determine whether
2836/// the given template arguments match the given class template
2837/// partial specialization per C++ [temp.class.spec.match].
2838Sema::TemplateDeductionResult
2839Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2840 const TemplateArgumentList &TemplateArgs,
2841 TemplateDeductionInfo &Info) {
2842 if (Partial->isInvalidDecl())
2843 return TDK_Invalid;
2844
2845 // C++ [temp.class.spec.match]p2:
2846 // A partial specialization matches a given actual template
2847 // argument list if the template arguments of the partial
2848 // specialization can be deduced from the actual template argument
2849 // list (14.8.2).
2850
2851 // Unevaluated SFINAE context.
2852 EnterExpressionEvaluationContext Unevaluated(
2853 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2854 SFINAETrap Trap(*this);
2855
2856 SmallVector<DeducedTemplateArgument, 4> Deduced;
2857 Deduced.resize(Partial->getTemplateParameters()->size());
2858 if (TemplateDeductionResult Result
2859 = ::DeduceTemplateArguments(*this,
2860 Partial->getTemplateParameters(),
2861 Partial->getTemplateArgs(),
2862 TemplateArgs, Info, Deduced))
2863 return Result;
2864
2865 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2866 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2867 Info);
2868 if (Inst.isInvalid())
2869 return TDK_InstantiationDepth;
2870
2871 if (Trap.hasErrorOccurred())
2872 return Sema::TDK_SubstitutionFailure;
2873
2874 return ::FinishTemplateArgumentDeduction(
2875 *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2876}
2877
2878/// Perform template argument deduction to determine whether
2879/// the given template arguments match the given variable template
2880/// partial specialization per C++ [temp.class.spec.match].
2881Sema::TemplateDeductionResult
2882Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2883 const TemplateArgumentList &TemplateArgs,
2884 TemplateDeductionInfo &Info) {
2885 if (Partial->isInvalidDecl())
2886 return TDK_Invalid;
2887
2888 // C++ [temp.class.spec.match]p2:
2889 // A partial specialization matches a given actual template
2890 // argument list if the template arguments of the partial
2891 // specialization can be deduced from the actual template argument
2892 // list (14.8.2).
2893
2894 // Unevaluated SFINAE context.
2895 EnterExpressionEvaluationContext Unevaluated(
2896 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2897 SFINAETrap Trap(*this);
2898
2899 SmallVector<DeducedTemplateArgument, 4> Deduced;
2900 Deduced.resize(Partial->getTemplateParameters()->size());
2901 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2902 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2903 TemplateArgs, Info, Deduced))
2904 return Result;
2905
2906 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2907 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2908 Info);
2909 if (Inst.isInvalid())
2910 return TDK_InstantiationDepth;
2911
2912 if (Trap.hasErrorOccurred())
2913 return Sema::TDK_SubstitutionFailure;
2914
2915 return ::FinishTemplateArgumentDeduction(
2916 *this, Partial, /*IsPartialOrdering=*/false, TemplateArgs, Deduced, Info);
2917}
2918
2919/// Determine whether the given type T is a simple-template-id type.
2920static bool isSimpleTemplateIdType(QualType T) {
2921 if (const TemplateSpecializationType *Spec
2922 = T->getAs<TemplateSpecializationType>())
2923 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
2924
2925 // C++17 [temp.local]p2:
2926 // the injected-class-name [...] is equivalent to the template-name followed
2927 // by the template-arguments of the class template specialization or partial
2928 // specialization enclosed in <>
2929 // ... which means it's equivalent to a simple-template-id.
2930 //
2931 // This only arises during class template argument deduction for a copy
2932 // deduction candidate, where it permits slicing.
2933 if (T->getAs<InjectedClassNameType>())
2934 return true;
2935
2936 return false;
2937}
2938
2939/// Substitute the explicitly-provided template arguments into the
2940/// given function template according to C++ [temp.arg.explicit].
2941///
2942/// \param FunctionTemplate the function template into which the explicit
2943/// template arguments will be substituted.
2944///
2945/// \param ExplicitTemplateArgs the explicitly-specified template
2946/// arguments.
2947///
2948/// \param Deduced the deduced template arguments, which will be populated
2949/// with the converted and checked explicit template arguments.
2950///
2951/// \param ParamTypes will be populated with the instantiated function
2952/// parameters.
2953///
2954/// \param FunctionType if non-NULL, the result type of the function template
2955/// will also be instantiated and the pointed-to value will be updated with
2956/// the instantiated function type.
2957///
2958/// \param Info if substitution fails for any reason, this object will be
2959/// populated with more information about the failure.
2960///
2961/// \returns TDK_Success if substitution was successful, or some failure
2962/// condition.
2963Sema::TemplateDeductionResult
2964Sema::SubstituteExplicitTemplateArguments(
2965 FunctionTemplateDecl *FunctionTemplate,
2966 TemplateArgumentListInfo &ExplicitTemplateArgs,
2967 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2968 SmallVectorImpl<QualType> &ParamTypes,
2969 QualType *FunctionType,
2970 TemplateDeductionInfo &Info) {
2971 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2972 TemplateParameterList *TemplateParams
2973 = FunctionTemplate->getTemplateParameters();
2974
2975 if (ExplicitTemplateArgs.size() == 0) {
2976 // No arguments to substitute; just copy over the parameter types and
2977 // fill in the function type.
2978 for (auto P : Function->parameters())
2979 ParamTypes.push_back(P->getType());
2980
2981 if (FunctionType)
2982 *FunctionType = Function->getType();
2983 return TDK_Success;
2984 }
2985
2986 // Unevaluated SFINAE context.
2987 EnterExpressionEvaluationContext Unevaluated(
2988 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2989 SFINAETrap Trap(*this);
2990
2991 // C++ [temp.arg.explicit]p3:
2992 // Template arguments that are present shall be specified in the
2993 // declaration order of their corresponding template-parameters. The
2994 // template argument list shall not specify more template-arguments than
2995 // there are corresponding template-parameters.
2996 SmallVector<TemplateArgument, 4> Builder;
2997
2998 // Enter a new template instantiation context where we check the
2999 // explicitly-specified template arguments against this function template,
3000 // and then substitute them into the function parameter types.
3001 SmallVector<TemplateArgument, 4> DeducedArgs;
3002 InstantiatingTemplate Inst(
3003 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3004 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
3005 if (Inst.isInvalid())
3006 return TDK_InstantiationDepth;
3007
3008 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
3009 ExplicitTemplateArgs, true, Builder, false) ||
3010 Trap.hasErrorOccurred()) {
3011 unsigned Index = Builder.size();
3012 if (Index >= TemplateParams->size())
3013 return TDK_SubstitutionFailure;
3014 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3015 return TDK_InvalidExplicitArguments;
3016 }
3017
3018 // Form the template argument list from the explicitly-specified
3019 // template arguments.
3020 TemplateArgumentList *ExplicitArgumentList
3021 = TemplateArgumentList::CreateCopy(Context, Builder);
3022 Info.setExplicitArgs(ExplicitArgumentList);
3023
3024 // Template argument deduction and the final substitution should be
3025 // done in the context of the templated declaration. Explicit
3026 // argument substitution, on the other hand, needs to happen in the
3027 // calling context.
3028 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3029
3030 // If we deduced template arguments for a template parameter pack,
3031 // note that the template argument pack is partially substituted and record
3032 // the explicit template arguments. They'll be used as part of deduction
3033 // for this template parameter pack.
3034 unsigned PartiallySubstitutedPackIndex = -1u;
3035 if (!Builder.empty()) {
3036 const TemplateArgument &Arg = Builder.back();
3037 if (Arg.getKind() == TemplateArgument::Pack) {
3038 auto *Param = TemplateParams->getParam(Builder.size() - 1);
3039 // If this is a fully-saturated fixed-size pack, it should be
3040 // fully-substituted, not partially-substituted.
3041 Optional<unsigned> Expansions = getExpandedPackSize(Param);
3042 if (!Expansions || Arg.pack_size() < *Expansions) {
3043 PartiallySubstitutedPackIndex = Builder.size() - 1;
3044 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3045 Param, Arg.pack_begin(), Arg.pack_size());
3046 }
3047 }
3048 }
3049
3050 const FunctionProtoType *Proto
3051 = Function->getType()->getAs<FunctionProtoType>();
3052 assert(Proto && "Function template does not have a prototype?")((Proto && "Function template does not have a prototype?"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Function template does not have a prototype?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3052, __PRETTY_FUNCTION__))
;
3053
3054 // Isolate our substituted parameters from our caller.
3055 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3056
3057 ExtParameterInfoBuilder ExtParamInfos;
3058
3059 // Instantiate the types of each of the function parameters given the
3060 // explicitly-specified template arguments. If the function has a trailing
3061 // return type, substitute it after the arguments to ensure we substitute
3062 // in lexical order.
3063 if (Proto->hasTrailingReturn()) {
3064 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3065 Proto->getExtParameterInfosOrNull(),
3066 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3067 ParamTypes, /*params*/ nullptr, ExtParamInfos))
3068 return TDK_SubstitutionFailure;
3069 }
3070
3071 // Instantiate the return type.
3072 QualType ResultType;
3073 {
3074 // C++11 [expr.prim.general]p3:
3075 // If a declaration declares a member function or member function
3076 // template of a class X, the expression this is a prvalue of type
3077 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3078 // and the end of the function-definition, member-declarator, or
3079 // declarator.
3080 Qualifiers ThisTypeQuals;
3081 CXXRecordDecl *ThisContext = nullptr;
3082 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3083 ThisContext = Method->getParent();
3084 ThisTypeQuals = Method->getMethodQualifiers();
3085 }
3086
3087 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3088 getLangOpts().CPlusPlus11);
3089
3090 ResultType =
3091 SubstType(Proto->getReturnType(),
3092 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3093 Function->getTypeSpecStartLoc(), Function->getDeclName());
3094 if (ResultType.isNull() || Trap.hasErrorOccurred())
3095 return TDK_SubstitutionFailure;
3096 // CUDA: Kernel function must have 'void' return type.
3097 if (getLangOpts().CUDA)
3098 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3099 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3100 << Function->getType() << Function->getSourceRange();
3101 return TDK_SubstitutionFailure;
3102 }
3103 }
3104
3105 // Instantiate the types of each of the function parameters given the
3106 // explicitly-specified template arguments if we didn't do so earlier.
3107 if (!Proto->hasTrailingReturn() &&
3108 SubstParmTypes(Function->getLocation(), Function->parameters(),
3109 Proto->getExtParameterInfosOrNull(),
3110 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3111 ParamTypes, /*params*/ nullptr, ExtParamInfos))
3112 return TDK_SubstitutionFailure;
3113
3114 if (FunctionType) {
3115 auto EPI = Proto->getExtProtoInfo();
3116 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3117
3118 // In C++1z onwards, exception specifications are part of the function type,
3119 // so substitution into the type must also substitute into the exception
3120 // specification.
3121 SmallVector<QualType, 4> ExceptionStorage;
3122 if (getLangOpts().CPlusPlus17 &&
3123 SubstExceptionSpec(
3124 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
3125 MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
3126 return TDK_SubstitutionFailure;
3127
3128 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3129 Function->getLocation(),
3130 Function->getDeclName(),
3131 EPI);
3132 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3133 return TDK_SubstitutionFailure;
3134 }
3135
3136 // C++ [temp.arg.explicit]p2:
3137 // Trailing template arguments that can be deduced (14.8.2) may be
3138 // omitted from the list of explicit template-arguments. If all of the
3139 // template arguments can be deduced, they may all be omitted; in this
3140 // case, the empty template argument list <> itself may also be omitted.
3141 //
3142 // Take all of the explicitly-specified arguments and put them into
3143 // the set of deduced template arguments. The partially-substituted
3144 // parameter pack, however, will be set to NULL since the deduction
3145 // mechanism handles the partially-substituted argument pack directly.
3146 Deduced.reserve(TemplateParams->size());
3147 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
3148 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
3149 if (I == PartiallySubstitutedPackIndex)
3150 Deduced.push_back(DeducedTemplateArgument());
3151 else
3152 Deduced.push_back(Arg);
3153 }
3154
3155 return TDK_Success;
3156}
3157
3158/// Check whether the deduced argument type for a call to a function
3159/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3160static Sema::TemplateDeductionResult
3161CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3162 Sema::OriginalCallArg OriginalArg,
3163 QualType DeducedA) {
3164 ASTContext &Context = S.Context;
3165
3166 auto Failed = [&]() -> Sema::TemplateDeductionResult {
3167 Info.FirstArg = TemplateArgument(DeducedA);
3168 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3169 Info.CallArgIndex = OriginalArg.ArgIdx;
3170 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
3171 : Sema::TDK_DeducedMismatch;
3172 };
3173
3174 QualType A = OriginalArg.OriginalArgType;
3175 QualType OriginalParamType = OriginalArg.OriginalParamType;
3176
3177 // Check for type equality (top-level cv-qualifiers are ignored).
3178 if (Context.hasSameUnqualifiedType(A, DeducedA))
3179 return Sema::TDK_Success;
3180
3181 // Strip off references on the argument types; they aren't needed for
3182 // the following checks.
3183 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3184 DeducedA = DeducedARef->getPointeeType();
3185 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3186 A = ARef->getPointeeType();
3187
3188 // C++ [temp.deduct.call]p4:
3189 // [...] However, there are three cases that allow a difference:
3190 // - If the original P is a reference type, the deduced A (i.e., the
3191 // type referred to by the reference) can be more cv-qualified than
3192 // the transformed A.
3193 if (const ReferenceType *OriginalParamRef
3194 = OriginalParamType->getAs<ReferenceType>()) {
3195 // We don't want to keep the reference around any more.
3196 OriginalParamType = OriginalParamRef->getPointeeType();
3197
3198 // FIXME: Resolve core issue (no number yet): if the original P is a
3199 // reference type and the transformed A is function type "noexcept F",
3200 // the deduced A can be F.
3201 QualType Tmp;
3202 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3203 return Sema::TDK_Success;
3204
3205 Qualifiers AQuals = A.getQualifiers();
3206 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3207
3208 // Under Objective-C++ ARC, the deduced type may have implicitly
3209 // been given strong or (when dealing with a const reference)
3210 // unsafe_unretained lifetime. If so, update the original
3211 // qualifiers to include this lifetime.
3212 if (S.getLangOpts().ObjCAutoRefCount &&
3213 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3214 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3215 (DeducedAQuals.hasConst() &&
3216 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3217 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3218 }
3219
3220 if (AQuals == DeducedAQuals) {
3221 // Qualifiers match; there's nothing to do.
3222 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
3223 return Failed();
3224 } else {
3225 // Qualifiers are compatible, so have the argument type adopt the
3226 // deduced argument type's qualifiers as if we had performed the
3227 // qualification conversion.
3228 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3229 }
3230 }
3231
3232 // - The transformed A can be another pointer or pointer to member
3233 // type that can be converted to the deduced A via a function pointer
3234 // conversion and/or a qualification conversion.
3235 //
3236 // Also allow conversions which merely strip __attribute__((noreturn)) from
3237 // function types (recursively).
3238 bool ObjCLifetimeConversion = false;
3239 QualType ResultTy;
3240 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3241 (S.IsQualificationConversion(A, DeducedA, false,
3242 ObjCLifetimeConversion) ||
3243 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3244 return Sema::TDK_Success;
3245
3246 // - If P is a class and P has the form simple-template-id, then the
3247 // transformed A can be a derived class of the deduced A. [...]
3248 // [...] Likewise, if P is a pointer to a class of the form
3249 // simple-template-id, the transformed A can be a pointer to a
3250 // derived class pointed to by the deduced A.
3251 if (const PointerType *OriginalParamPtr
3252 = OriginalParamType->getAs<PointerType>()) {
3253 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3254 if (const PointerType *APtr = A->getAs<PointerType>()) {
3255 if (A->getPointeeType()->isRecordType()) {
3256 OriginalParamType = OriginalParamPtr->getPointeeType();
3257 DeducedA = DeducedAPtr->getPointeeType();
3258 A = APtr->getPointeeType();
3259 }
3260 }
3261 }
3262 }
3263
3264 if (Context.hasSameUnqualifiedType(A, DeducedA))
3265 return Sema::TDK_Success;
3266
3267 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3268 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3269 return Sema::TDK_Success;
3270
3271 return Failed();
3272}
3273
3274/// Find the pack index for a particular parameter index in an instantiation of
3275/// a function template with specific arguments.
3276///
3277/// \return The pack index for whichever pack produced this parameter, or -1
3278/// if this was not produced by a parameter. Intended to be used as the
3279/// ArgumentPackSubstitutionIndex for further substitutions.
3280// FIXME: We should track this in OriginalCallArgs so we don't need to
3281// reconstruct it here.
3282static unsigned getPackIndexForParam(Sema &S,
3283 FunctionTemplateDecl *FunctionTemplate,
3284 const MultiLevelTemplateArgumentList &Args,
3285 unsigned ParamIdx) {
3286 unsigned Idx = 0;
3287 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3288 if (PD->isParameterPack()) {
3289 unsigned NumExpansions =
3290 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3291 if (Idx + NumExpansions > ParamIdx)
3292 return ParamIdx - Idx;
3293 Idx += NumExpansions;
3294 } else {
3295 if (Idx == ParamIdx)
3296 return -1; // Not a pack expansion
3297 ++Idx;
3298 }
3299 }
3300
3301 llvm_unreachable("parameter index would not be produced from template")::llvm::llvm_unreachable_internal("parameter index would not be produced from template"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3301)
;
3302}
3303
3304/// Finish template argument deduction for a function template,
3305/// checking the deduced template arguments for completeness and forming
3306/// the function template specialization.
3307///
3308/// \param OriginalCallArgs If non-NULL, the original call arguments against
3309/// which the deduced argument types should be compared.
3310Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3311 FunctionTemplateDecl *FunctionTemplate,
3312 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3313 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3314 TemplateDeductionInfo &Info,
3315 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3316 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3317 // Unevaluated SFINAE context.
3318 EnterExpressionEvaluationContext Unevaluated(
3319 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3320 SFINAETrap Trap(*this);
3321
3322 // Enter a new template instantiation context while we instantiate the
3323 // actual function declaration.
3324 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3325 InstantiatingTemplate Inst(
3326 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3327 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
3328 if (Inst.isInvalid())
3329 return TDK_InstantiationDepth;
3330
3331 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3332
3333 // C++ [temp.deduct.type]p2:
3334 // [...] or if any template argument remains neither deduced nor
3335 // explicitly specified, template argument deduction fails.
3336 SmallVector<TemplateArgument, 4> Builder;
3337 if (auto Result = ConvertDeducedTemplateArguments(
3338 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
3339 CurrentInstantiationScope, NumExplicitlySpecified,
3340 PartialOverloading))
3341 return Result;
3342
3343 // C++ [temp.deduct.call]p10: [DR1391]
3344 // If deduction succeeds for all parameters that contain
3345 // template-parameters that participate in template argument deduction,
3346 // and all template arguments are explicitly specified, deduced, or
3347 // obtained from default template arguments, remaining parameters are then
3348 // compared with the corresponding arguments. For each remaining parameter
3349 // P with a type that was non-dependent before substitution of any
3350 // explicitly-specified template arguments, if the corresponding argument
3351 // A cannot be implicitly converted to P, deduction fails.
3352 if (CheckNonDependent())
3353 return TDK_NonDependentConversionFailure;
3354
3355 // Form the template argument list from the deduced template arguments.
3356 TemplateArgumentList *DeducedArgumentList
3357 = TemplateArgumentList::CreateCopy(Context, Builder);
3358 Info.reset(DeducedArgumentList);
3359
3360 // Substitute the deduced template arguments into the function template
3361 // declaration to produce the function template specialization.
3362 DeclContext *Owner = FunctionTemplate->getDeclContext();
3363 if (FunctionTemplate->getFriendObjectKind())
3364 Owner = FunctionTemplate->getLexicalDeclContext();
3365 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
3366 Specialization = cast_or_null<FunctionDecl>(
3367 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
3368 if (!Specialization || Specialization->isInvalidDecl())
3369 return TDK_SubstitutionFailure;
3370
3371 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==((Specialization->getPrimaryTemplate()->getCanonicalDecl
() == FunctionTemplate->getCanonicalDecl()) ? static_cast<
void> (0) : __assert_fail ("Specialization->getPrimaryTemplate()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3372, __PRETTY_FUNCTION__))
3372 FunctionTemplate->getCanonicalDecl())((Specialization->getPrimaryTemplate()->getCanonicalDecl
() == FunctionTemplate->getCanonicalDecl()) ? static_cast<
void> (0) : __assert_fail ("Specialization->getPrimaryTemplate()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 3372, __PRETTY_FUNCTION__))
;
3373
3374 // If the template argument list is owned by the function template
3375 // specialization, release it.
3376 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3377 !Trap.hasErrorOccurred())
3378 Info.take();
3379
3380 // There may have been an error that did not prevent us from constructing a
3381 // declaration. Mark the declaration invalid and return with a substitution
3382 // failure.
3383 if (Trap.hasErrorOccurred()) {
3384 Specialization->setInvalidDecl(true);
3385 return TDK_SubstitutionFailure;
3386 }
3387
3388 if (OriginalCallArgs) {
3389 // C++ [temp.deduct.call]p4:
3390 // In general, the deduction process attempts to find template argument
3391 // values that will make the deduced A identical to A (after the type A
3392 // is transformed as described above). [...]
3393 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3394 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3395 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3396
3397 auto ParamIdx = OriginalArg.ArgIdx;
3398 if (ParamIdx >= Specialization->getNumParams())
3399 // FIXME: This presumably means a pack ended up smaller than we
3400 // expected while deducing. Should this not result in deduction
3401 // failure? Can it even happen?
3402 continue;
3403
3404 QualType DeducedA;
3405 if (!OriginalArg.DecomposedParam) {
3406 // P is one of the function parameters, just look up its substituted
3407 // type.
3408 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3409 } else {
3410 // P is a decomposed element of a parameter corresponding to a
3411 // braced-init-list argument. Substitute back into P to find the
3412 // deduced A.
3413 QualType &CacheEntry =
3414 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3415 if (CacheEntry.isNull()) {
3416 ArgumentPackSubstitutionIndexRAII PackIndex(
3417 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3418 ParamIdx));
3419 CacheEntry =
3420 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3421 Specialization->getTypeSpecStartLoc(),
3422 Specialization->getDeclName());
3423 }
3424 DeducedA = CacheEntry;
3425 }
3426
3427 if (auto TDK =
3428 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3429 return TDK;
3430 }
3431 }
3432
3433 // If we suppressed any diagnostics while performing template argument
3434 // deduction, and if we haven't already instantiated this declaration,
3435 // keep track of these diagnostics. They'll be emitted if this specialization
3436 // is actually used.
3437 if (Info.diag_begin() != Info.diag_end()) {
3438 SuppressedDiagnosticsMap::iterator
3439 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3440 if (Pos == SuppressedDiagnostics.end())
3441 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3442 .append(Info.diag_begin(), Info.diag_end());
3443 }
3444
3445 return TDK_Success;
3446}
3447
3448/// Gets the type of a function for template-argument-deducton
3449/// purposes when it's considered as part of an overload set.
3450static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
3451 FunctionDecl *Fn) {
3452 // We may need to deduce the return type of the function now.
3453 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
3454 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
3455 return {};
3456
3457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
3458 if (Method->isInstance()) {
3459 // An instance method that's referenced in a form that doesn't
3460 // look like a member pointer is just invalid.
3461 if (!R.HasFormOfMemberPointer)
3462 return {};
3463
3464 return S.Context.getMemberPointerType(Fn->getType(),
3465 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
3466 }
3467
3468 if (!R.IsAddressOfOperand) return Fn->getType();
3469 return S.Context.getPointerType(Fn->getType());
3470}
3471
3472/// Apply the deduction rules for overload sets.
3473///
3474/// \return the null type if this argument should be treated as an
3475/// undeduced context
3476static QualType
3477ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
3478 Expr *Arg, QualType ParamType,
3479 bool ParamWasReference) {
3480
3481 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
3482
3483 OverloadExpr *Ovl = R.Expression;
3484
3485 // C++0x [temp.deduct.call]p4
3486 unsigned TDF = 0;
3487 if (ParamWasReference)
3488 TDF |= TDF_ParamWithReferenceType;
3489 if (R.IsAddressOfOperand)
3490 TDF |= TDF_IgnoreQualifiers;
3491
3492 // C++0x [temp.deduct.call]p6:
3493 // When P is a function type, pointer to function type, or pointer
3494 // to member function type:
3495
3496 if (!ParamType->isFunctionType() &&
3497 !ParamType->isFunctionPointerType() &&
3498 !ParamType->isMemberFunctionPointerType()) {
3499 if (Ovl->hasExplicitTemplateArgs()) {
3500 // But we can still look for an explicit specialization.
3501 if (FunctionDecl *ExplicitSpec
3502 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
3503 return GetTypeOfFunction(S, R, ExplicitSpec);
3504 }
3505
3506 DeclAccessPair DAP;
3507 if (FunctionDecl *Viable =
3508 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3509 return GetTypeOfFunction(S, R, Viable);
3510
3511 return {};
3512 }
3513
3514 // Gather the explicit template arguments, if any.
3515 TemplateArgumentListInfo ExplicitTemplateArgs;
3516 if (Ovl->hasExplicitTemplateArgs())
3517 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3518 QualType Match;
3519 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3520 E = Ovl->decls_end(); I != E; ++I) {
3521 NamedDecl *D = (*I)->getUnderlyingDecl();
3522
3523 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3524 // - If the argument is an overload set containing one or more
3525 // function templates, the parameter is treated as a
3526 // non-deduced context.
3527 if (!Ovl->hasExplicitTemplateArgs())
3528 return {};
3529
3530 // Otherwise, see if we can resolve a function type
3531 FunctionDecl *Specialization = nullptr;
3532 TemplateDeductionInfo Info(Ovl->getNameLoc());
3533 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3534 Specialization, Info))
3535 continue;
3536
3537 D = Specialization;
3538 }
3539
3540 FunctionDecl *Fn = cast<FunctionDecl>(D);
3541 QualType ArgType = GetTypeOfFunction(S, R, Fn);
3542 if (ArgType.isNull()) continue;
3543
3544 // Function-to-pointer conversion.
3545 if (!ParamWasReference && ParamType->isPointerType() &&
3546 ArgType->isFunctionType())
3547 ArgType = S.Context.getPointerType(ArgType);
3548
3549 // - If the argument is an overload set (not containing function
3550 // templates), trial argument deduction is attempted using each
3551 // of the members of the set. If deduction succeeds for only one
3552 // of the overload set members, that member is used as the
3553 // argument value for the deduction. If deduction succeeds for
3554 // more than one member of the overload set the parameter is
3555 // treated as a non-deduced context.
3556
3557 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3558 // Type deduction is done independently for each P/A pair, and
3559 // the deduced template argument values are then combined.
3560 // So we do not reject deductions which were made elsewhere.
3561 SmallVector<DeducedTemplateArgument, 8>
3562 Deduced(TemplateParams->size());
3563 TemplateDeductionInfo Info(Ovl->getNameLoc());
3564 Sema::TemplateDeductionResult Result
3565 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3566 ArgType, Info, Deduced, TDF);
3567 if (Result) continue;
3568 if (!Match.isNull())
3569 return {};
3570 Match = ArgType;
3571 }
3572
3573 return Match;
3574}
3575
3576/// Perform the adjustments to the parameter and argument types
3577/// described in C++ [temp.deduct.call].
3578///
3579/// \returns true if the caller should not attempt to perform any template
3580/// argument deduction based on this P/A pair because the argument is an
3581/// overloaded function set that could not be resolved.
3582static bool AdjustFunctionParmAndArgTypesForDeduction(
3583 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3584 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
3585 // C++0x [temp.deduct.call]p3:
3586 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
3587 // are ignored for type deduction.
3588 if (ParamType.hasQualifiers())
3589 ParamType = ParamType.getUnqualifiedType();
3590
3591 // [...] If P is a reference type, the type referred to by P is
3592 // used for type deduction.
3593 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3594 if (ParamRefType)
3595 ParamType = ParamRefType->getPointeeType();
3596
3597 // Overload sets usually make this parameter an undeduced context,
3598 // but there are sometimes special circumstances. Typically
3599 // involving a template-id-expr.
3600 if (ArgType == S.Context.OverloadTy) {
3601 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3602 Arg, ParamType,
3603 ParamRefType != nullptr);
3604 if (ArgType.isNull())
3605 return true;
3606 }
3607
3608 if (ParamRefType) {
3609 // If the argument has incomplete array type, try to complete its type.
3610 if (ArgType->isIncompleteArrayType()) {
3611 S.completeExprArrayBound(Arg);
3612 ArgType = Arg->getType();
3613 }
3614
3615 // C++1z [temp.deduct.call]p3:
3616 // If P is a forwarding reference and the argument is an lvalue, the type
3617 // "lvalue reference to A" is used in place of A for type deduction.
3618 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
3619 Arg->isLValue())
3620 ArgType = S.Context.getLValueReferenceType(ArgType);
3621 } else {
3622 // C++ [temp.deduct.call]p2:
3623 // If P is not a reference type:
3624 // - If A is an array type, the pointer type produced by the
3625 // array-to-pointer standard conversion (4.2) is used in place of
3626 // A for type deduction; otherwise,
3627 if (ArgType->isArrayType())
3628 ArgType = S.Context.getArrayDecayedType(ArgType);
3629 // - If A is a function type, the pointer type produced by the
3630 // function-to-pointer standard conversion (4.3) is used in place
3631 // of A for type deduction; otherwise,
3632 else if (ArgType->isFunctionType())
3633 ArgType = S.Context.getPointerType(ArgType);
3634 else {
3635 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3636 // type are ignored for type deduction.
3637 ArgType = ArgType.getUnqualifiedType();
3638 }
3639 }
3640
3641 // C++0x [temp.deduct.call]p4:
3642 // In general, the deduction process attempts to find template argument
3643 // values that will make the deduced A identical to A (after the type A
3644 // is transformed as described above). [...]
3645 TDF = TDF_SkipNonDependent;
3646
3647 // - If the original P is a reference type, the deduced A (i.e., the
3648 // type referred to by the reference) can be more cv-qualified than
3649 // the transformed A.
3650 if (ParamRefType)
3651 TDF |= TDF_ParamWithReferenceType;
3652 // - The transformed A can be another pointer or pointer to member
3653 // type that can be converted to the deduced A via a qualification
3654 // conversion (4.4).
3655 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3656 ArgType->isObjCObjectPointerType())
3657 TDF |= TDF_IgnoreQualifiers;
3658 // - If P is a class and P has the form simple-template-id, then the
3659 // transformed A can be a derived class of the deduced A. Likewise,
3660 // if P is a pointer to a class of the form simple-template-id, the
3661 // transformed A can be a pointer to a derived class pointed to by
3662 // the deduced A.
3663 if (isSimpleTemplateIdType(ParamType) ||
3664 (isa<PointerType>(ParamType) &&
3665 isSimpleTemplateIdType(
3666 ParamType->getAs<PointerType>()->getPointeeType())))
3667 TDF |= TDF_DerivedClass;
3668
3669 return false;
3670}
3671
3672static bool
3673hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3674 QualType T);
3675
3676static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3677 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3678 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3679 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3680 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3681 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
3682
3683/// Attempt template argument deduction from an initializer list
3684/// deemed to be an argument in a function call.
3685static Sema::TemplateDeductionResult DeduceFromInitializerList(
3686 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3687 InitListExpr *ILE, TemplateDeductionInfo &Info,
3688 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3689 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3690 unsigned TDF) {
3691 // C++ [temp.deduct.call]p1: (CWG 1591)
3692 // If removing references and cv-qualifiers from P gives
3693 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3694 // a non-empty initializer list, then deduction is performed instead for
3695 // each element of the initializer list, taking P0 as a function template
3696 // parameter type and the initializer element as its argument
3697 //
3698 // We've already removed references and cv-qualifiers here.
3699 if (!ILE->getNumInits())
3700 return Sema::TDK_Success;
3701
3702 QualType ElTy;
3703 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3704 if (ArrTy)
3705 ElTy = ArrTy->getElementType();
3706 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3707 // Otherwise, an initializer list argument causes the parameter to be
3708 // considered a non-deduced context
3709 return Sema::TDK_Success;
3710 }
3711
3712 // Resolving a core issue: a braced-init-list containing any designators is
3713 // a non-deduced context.
3714 for (Expr *E : ILE->inits())
3715 if (isa<DesignatedInitExpr>(E))
3716 return Sema::TDK_Success;
3717
3718 // Deduction only needs to be done for dependent types.
3719 if (ElTy->isDependentType()) {
3720 for (Expr *E : ILE->inits()) {
3721 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
3722 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
3723 ArgIdx, TDF))
3724 return Result;
3725 }
3726 }
3727
3728 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3729 // from the length of the initializer list.
3730 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
3731 // Determine the array bound is something we can deduce.
3732 if (NonTypeTemplateParmDecl *NTTP =
3733 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
3734 // We can perform template argument deduction for the given non-type
3735 // template parameter.
3736 // C++ [temp.deduct.type]p13:
3737 // The type of N in the type T[N] is std::size_t.
3738 QualType T = S.Context.getSizeType();
3739 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
3740 if (auto Result = DeduceNonTypeTemplateArgument(
3741 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
3742 /*ArrayBound=*/true, Info, Deduced))
3743 return Result;
3744 }
3745 }
3746
3747 return Sema::TDK_Success;
3748}
3749
3750/// Perform template argument deduction per [temp.deduct.call] for a
3751/// single parameter / argument pair.
3752static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3753 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3754 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3755 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3756 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3757 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
3758 QualType ArgType = Arg->getType();
3759 QualType OrigParamType = ParamType;
3760
3761 // If P is a reference type [...]
3762 // If P is a cv-qualified type [...]
3763 if (AdjustFunctionParmAndArgTypesForDeduction(
3764 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
3765 return Sema::TDK_Success;
3766
3767 // If [...] the argument is a non-empty initializer list [...]
3768 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3769 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
3770 Deduced, OriginalCallArgs, ArgIdx, TDF);
3771
3772 // [...] the deduction process attempts to find template argument values
3773 // that will make the deduced A identical to A
3774 //
3775 // Keep track of the argument type and corresponding parameter index,
3776 // so we can check for compatibility between the deduced A and A.
3777 OriginalCallArgs.push_back(
3778 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
3779 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3780 ArgType, Info, Deduced, TDF);
3781}
3782
3783/// Perform template argument deduction from a function call
3784/// (C++ [temp.deduct.call]).
3785///
3786/// \param FunctionTemplate the function template for which we are performing
3787/// template argument deduction.
3788///
3789/// \param ExplicitTemplateArgs the explicit template arguments provided
3790/// for this call.
3791///
3792/// \param Args the function call arguments
3793///
3794/// \param Specialization if template argument deduction was successful,
3795/// this will be set to the function template specialization produced by
3796/// template argument deduction.
3797///
3798/// \param Info the argument will be updated to provide additional information
3799/// about template argument deduction.
3800///
3801/// \param CheckNonDependent A callback to invoke to check conversions for
3802/// non-dependent parameters, between deduction and substitution, per DR1391.
3803/// If this returns true, substitution will be skipped and we return
3804/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3805/// types (after substituting explicit template arguments).
3806///
3807/// \returns the result of template argument deduction.
3808Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3809 FunctionTemplateDecl *FunctionTemplate,
3810 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3811 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3812 bool PartialOverloading,
3813 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
3814 if (FunctionTemplate->isInvalidDecl())
1
Assuming the condition is false
2
Taking false branch
3815 return TDK_Invalid;
3816
3817 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3818 unsigned NumParams = Function->getNumParams();
3819
3820 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3821
3822 // C++ [temp.deduct.call]p1:
3823 // Template argument deduction is done by comparing each function template
3824 // parameter type (call it P) with the type of the corresponding argument
3825 // of the call (call it A) as described below.
3826 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
3
Assuming the condition is false
3827 return TDK_TooFewArguments;
3828 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
4
Calling 'Sema::TooManyArguments'
10
Returning from 'Sema::TooManyArguments'
11
Taking true branch
3829 const FunctionProtoType *Proto
13
'Proto' initialized to a null pointer value
3830 = Function->getType()->getAs<FunctionProtoType>();
12
Assuming the object is not a 'FunctionProtoType'
3831 if (Proto->isTemplateVariadic())
14
Called C++ object pointer is null
3832 /* Do nothing */;
3833 else if (!Proto->isVariadic())
3834 return TDK_TooManyArguments;
3835 }
3836
3837 // The types of the parameters from which we will perform template argument
3838 // deduction.
3839 LocalInstantiationScope InstScope(*this);
3840 TemplateParameterList *TemplateParams
3841 = FunctionTemplate->getTemplateParameters();
3842 SmallVector<DeducedTemplateArgument, 4> Deduced;
3843 SmallVector<QualType, 8> ParamTypes;
3844 unsigned NumExplicitlySpecified = 0;
3845 if (ExplicitTemplateArgs) {
3846 TemplateDeductionResult Result =
3847 SubstituteExplicitTemplateArguments(FunctionTemplate,
3848 *ExplicitTemplateArgs,
3849 Deduced,
3850 ParamTypes,
3851 nullptr,
3852 Info);
3853 if (Result)
3854 return Result;
3855
3856 NumExplicitlySpecified = Deduced.size();
3857 } else {
3858 // Just fill in the parameter types from the function declaration.
3859 for (unsigned I = 0; I != NumParams; ++I)
3860 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3861 }
3862
3863 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
3864
3865 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3866 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
3867 // C++ [demp.deduct.call]p1: (DR1391)
3868 // Template argument deduction is done by comparing each function template
3869 // parameter that contains template-parameters that participate in
3870 // template argument deduction ...
3871 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3872 return Sema::TDK_Success;
3873
3874 // ... with the type of the corresponding argument
3875 return DeduceTemplateArgumentsFromCallArgument(
3876 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
3877 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
3878 };
3879
3880 // Deduce template arguments from the function parameters.
3881 Deduced.resize(TemplateParams->size());
3882 SmallVector<QualType, 8> ParamTypesForArgChecking;
3883 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
3884 ParamIdx != NumParamTypes; ++ParamIdx) {
3885 QualType ParamType = ParamTypes[ParamIdx];
3886
3887 const PackExpansionType *ParamExpansion =
3888 dyn_cast<PackExpansionType>(ParamType);
3889 if (!ParamExpansion) {
3890 // Simple case: matching a function parameter to a function argument.
3891 if (ArgIdx >= Args.size())
3892 break;
3893
3894 ParamTypesForArgChecking.push_back(ParamType);
3895 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
3896 return Result;
3897
3898 continue;
3899 }
3900
3901 QualType ParamPattern = ParamExpansion->getPattern();
3902 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3903 ParamPattern);
3904
3905 // C++0x [temp.deduct.call]p1:
3906 // For a function parameter pack that occurs at the end of the
3907 // parameter-declaration-list, the type A of each remaining argument of
3908 // the call is compared with the type P of the declarator-id of the
3909 // function parameter pack. Each comparison deduces template arguments
3910 // for subsequent positions in the template parameter packs expanded by
3911 // the function parameter pack. When a function parameter pack appears
3912 // in a non-deduced context [not at the end of the list], the type of
3913 // that parameter pack is never deduced.
3914 //
3915 // FIXME: The above rule allows the size of the parameter pack to change
3916 // after we skip it (in the non-deduced case). That makes no sense, so
3917 // we instead notionally deduce the pack against N arguments, where N is
3918 // the length of the explicitly-specified pack if it's expanded by the
3919 // parameter pack and 0 otherwise, and we treat each deduction as a
3920 // non-deduced context.
3921 if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) {
3922 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
3923 PackScope.nextPackElement(), ++ArgIdx) {
3924 ParamTypesForArgChecking.push_back(ParamPattern);
3925 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3926 return Result;
3927 }
3928 } else {
3929 // If the parameter type contains an explicitly-specified pack that we
3930 // could not expand, skip the number of parameters notionally created
3931 // by the expansion.
3932 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
3933 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
3934 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
3935 ++I, ++ArgIdx) {
3936 ParamTypesForArgChecking.push_back(ParamPattern);
3937 // FIXME: Should we add OriginalCallArgs for these? What if the
3938 // corresponding argument is a list?
3939 PackScope.nextPackElement();
3940 }
3941 }
3942 }
3943
3944 // Build argument packs for each of the parameter packs expanded by this
3945 // pack expansion.
3946 if (auto Result = PackScope.finish())
3947 return Result;
3948 }
3949
3950 // Capture the context in which the function call is made. This is the context
3951 // that is needed when the accessibility of template arguments is checked.
3952 DeclContext *CallingCtx = CurContext;
3953
3954 return FinishTemplateArgumentDeduction(
3955 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3956 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
3957 ContextRAII SavedContext(*this, CallingCtx);
3958 return CheckNonDependent(ParamTypesForArgChecking);
3959 });
3960}
3961
3962QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3963 QualType FunctionType,
3964 bool AdjustExceptionSpec) {
3965 if (ArgFunctionType.isNull())
3966 return ArgFunctionType;
3967
3968 const FunctionProtoType *FunctionTypeP =
3969 FunctionType->castAs<FunctionProtoType>();
3970 const FunctionProtoType *ArgFunctionTypeP =
3971 ArgFunctionType->getAs<FunctionProtoType>();
3972
3973 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3974 bool Rebuild = false;
3975
3976 CallingConv CC = FunctionTypeP->getCallConv();
3977 if (EPI.ExtInfo.getCC() != CC) {
3978 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3979 Rebuild = true;
3980 }
3981
3982 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3983 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3984 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3985 Rebuild = true;
3986 }
3987
3988 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3989 ArgFunctionTypeP->hasExceptionSpec())) {
3990 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3991 Rebuild = true;
3992 }
3993
3994 if (!Rebuild)
3995 return ArgFunctionType;
3996
3997 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3998 ArgFunctionTypeP->getParamTypes(), EPI);
3999}
4000
4001/// Deduce template arguments when taking the address of a function
4002/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
4003/// a template.
4004///
4005/// \param FunctionTemplate the function template for which we are performing
4006/// template argument deduction.
4007///
4008/// \param ExplicitTemplateArgs the explicitly-specified template
4009/// arguments.
4010///
4011/// \param ArgFunctionType the function type that will be used as the
4012/// "argument" type (A) when performing template argument deduction from the
4013/// function template's function type. This type may be NULL, if there is no
4014/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
4015///
4016/// \param Specialization if template argument deduction was successful,
4017/// this will be set to the function template specialization produced by
4018/// template argument deduction.
4019///
4020/// \param Info the argument will be updated to provide additional information
4021/// about template argument deduction.
4022///
4023/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4024/// the address of a function template per [temp.deduct.funcaddr] and
4025/// [over.over]. If \c false, we are looking up a function template
4026/// specialization based on its signature, per [temp.deduct.decl].
4027///
4028/// \returns the result of template argument deduction.
4029Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4030 FunctionTemplateDecl *FunctionTemplate,
4031 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4032 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4033 bool IsAddressOfFunction) {
4034 if (FunctionTemplate->isInvalidDecl())
4035 return TDK_Invalid;
4036
4037 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4038 TemplateParameterList *TemplateParams
4039 = FunctionTemplate->getTemplateParameters();
4040 QualType FunctionType = Function->getType();
4041
4042 // Substitute any explicit template arguments.
4043 LocalInstantiationScope InstScope(*this);
4044 SmallVector<DeducedTemplateArgument, 4> Deduced;
4045 unsigned NumExplicitlySpecified = 0;
4046 SmallVector<QualType, 4> ParamTypes;
4047 if (ExplicitTemplateArgs) {
4048 if (TemplateDeductionResult Result
4049 = SubstituteExplicitTemplateArguments(FunctionTemplate,
4050 *ExplicitTemplateArgs,
4051 Deduced, ParamTypes,
4052 &FunctionType, Info))
4053 return Result;
4054
4055 NumExplicitlySpecified = Deduced.size();
4056 }
4057
4058 // When taking the address of a function, we require convertibility of
4059 // the resulting function type. Otherwise, we allow arbitrary mismatches
4060 // of calling convention and noreturn.
4061 if (!IsAddressOfFunction)
4062 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4063 /*AdjustExceptionSpec*/false);
4064
4065 // Unevaluated SFINAE context.
4066 EnterExpressionEvaluationContext Unevaluated(
4067 *this, Sema::ExpressionEvaluationContext::Unevaluated);
4068 SFINAETrap Trap(*this);
4069
4070 Deduced.resize(TemplateParams->size());
4071
4072 // If the function has a deduced return type, substitute it for a dependent
4073 // type so that we treat it as a non-deduced context in what follows. If we
4074 // are looking up by signature, the signature type should also have a deduced
4075 // return type, which we instead expect to exactly match.
4076 bool HasDeducedReturnType = false;
4077 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
4078 Function->getReturnType()->getContainedAutoType()) {
4079 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
4080 HasDeducedReturnType = true;
4081 }
4082
4083 if (!ArgFunctionType.isNull()) {
4084 unsigned TDF =
4085 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
4086 // Deduce template arguments from the function type.
4087 if (TemplateDeductionResult Result
4088 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4089 FunctionType, ArgFunctionType,
4090 Info, Deduced, TDF))
4091 return Result;
4092 }
4093
4094 if (TemplateDeductionResult Result
4095 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4096 NumExplicitlySpecified,
4097 Specialization, Info))
4098 return Result;
4099
4100 // If the function has a deduced return type, deduce it now, so we can check
4101 // that the deduced function type matches the requested type.
4102 if (HasDeducedReturnType &&
4103 Specialization->getReturnType()->isUndeducedType() &&
4104 DeduceReturnType(Specialization, Info.getLocation(), false))
4105 return TDK_MiscellaneousDeductionFailure;
4106
4107 // If the function has a dependent exception specification, resolve it now,
4108 // so we can check that the exception specification matches.
4109 auto *SpecializationFPT =
4110 Specialization->getType()->castAs<FunctionProtoType>();
4111 if (getLangOpts().CPlusPlus17 &&
4112 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
4113 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
4114 return TDK_MiscellaneousDeductionFailure;
4115
4116 // Adjust the exception specification of the argument to match the
4117 // substituted and resolved type we just formed. (Calling convention and
4118 // noreturn can't be dependent, so we don't actually need this for them
4119 // right now.)
4120 QualType SpecializationType = Specialization->getType();
4121 if (!IsAddressOfFunction)
4122 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4123 /*AdjustExceptionSpec*/true);
4124
4125 // If the requested function type does not match the actual type of the
4126 // specialization with respect to arguments of compatible pointer to function
4127 // types, template argument deduction fails.
4128 if (!ArgFunctionType.isNull()) {
4129 if (IsAddressOfFunction &&
4130 !isSameOrCompatibleFunctionType(
4131 Context.getCanonicalType(SpecializationType),
4132 Context.getCanonicalType(ArgFunctionType)))
4133 return TDK_MiscellaneousDeductionFailure;
4134
4135 if (!IsAddressOfFunction &&
4136 !Context.hasSameType(SpecializationType, ArgFunctionType))
4137 return TDK_MiscellaneousDeductionFailure;
4138 }
4139
4140 return TDK_Success;
4141}
4142
4143/// Deduce template arguments for a templated conversion
4144/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4145/// conversion function template specialization.
4146Sema::TemplateDeductionResult
4147Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
4148 QualType ToType,
4149 CXXConversionDecl *&Specialization,
4150 TemplateDeductionInfo &Info) {
4151 if (ConversionTemplate->isInvalidDecl())
4152 return TDK_Invalid;
4153
4154 CXXConversionDecl *ConversionGeneric
4155 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4156
4157 QualType FromType = ConversionGeneric->getConversionType();
4158
4159 // Canonicalize the types for deduction.
4160 QualType P = Context.getCanonicalType(FromType);
4161 QualType A = Context.getCanonicalType(ToType);
4162
4163 // C++0x [temp.deduct.conv]p2:
4164 // If P is a reference type, the type referred to by P is used for
4165 // type deduction.
4166 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4167 P = PRef->getPointeeType();
4168
4169 // C++0x [temp.deduct.conv]p4:
4170 // [...] If A is a reference type, the type referred to by A is used
4171 // for type deduction.
4172 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4173 A = ARef->getPointeeType();
4174 // We work around a defect in the standard here: cv-qualifiers are also
4175 // removed from P and A in this case, unless P was a reference type. This
4176 // seems to mostly match what other compilers are doing.
4177 if (!FromType->getAs<ReferenceType>()) {
4178 A = A.getUnqualifiedType();
4179 P = P.getUnqualifiedType();
4180 }
4181
4182 // C++ [temp.deduct.conv]p3:
4183 //
4184 // If A is not a reference type:
4185 } else {
4186 assert(!A->isReferenceType() && "Reference types were handled above")((!A->isReferenceType() && "Reference types were handled above"
) ? static_cast<void> (0) : __assert_fail ("!A->isReferenceType() && \"Reference types were handled above\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4186, __PRETTY_FUNCTION__))
;
4187
4188 // - If P is an array type, the pointer type produced by the
4189 // array-to-pointer standard conversion (4.2) is used in place
4190 // of P for type deduction; otherwise,
4191 if (P->isArrayType())
4192 P = Context.getArrayDecayedType(P);
4193 // - If P is a function type, the pointer type produced by the
4194 // function-to-pointer standard conversion (4.3) is used in
4195 // place of P for type deduction; otherwise,
4196 else if (P->isFunctionType())
4197 P = Context.getPointerType(P);
4198 // - If P is a cv-qualified type, the top level cv-qualifiers of
4199 // P's type are ignored for type deduction.
4200 else
4201 P = P.getUnqualifiedType();
4202
4203 // C++0x [temp.deduct.conv]p4:
4204 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4205 // type are ignored for type deduction. If A is a reference type, the type
4206 // referred to by A is used for type deduction.
4207 A = A.getUnqualifiedType();
4208 }
4209
4210 // Unevaluated SFINAE context.
4211 EnterExpressionEvaluationContext Unevaluated(
4212 *this, Sema::ExpressionEvaluationContext::Unevaluated);
4213 SFINAETrap Trap(*this);
4214
4215 // C++ [temp.deduct.conv]p1:
4216 // Template argument deduction is done by comparing the return
4217 // type of the template conversion function (call it P) with the
4218 // type that is required as the result of the conversion (call it
4219 // A) as described in 14.8.2.4.
4220 TemplateParameterList *TemplateParams
4221 = ConversionTemplate->getTemplateParameters();
4222 SmallVector<DeducedTemplateArgument, 4> Deduced;
4223 Deduced.resize(TemplateParams->size());
4224
4225 // C++0x [temp.deduct.conv]p4:
4226 // In general, the deduction process attempts to find template
4227 // argument values that will make the deduced A identical to
4228 // A. However, there are two cases that allow a difference:
4229 unsigned TDF = 0;
4230 // - If the original A is a reference type, A can be more
4231 // cv-qualified than the deduced A (i.e., the type referred to
4232 // by the reference)
4233 if (ToType->isReferenceType())
4234 TDF |= TDF_ArgWithReferenceType;
4235 // - The deduced A can be another pointer or pointer to member
4236 // type that can be converted to A via a qualification
4237 // conversion.
4238 //
4239 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4240 // both P and A are pointers or member pointers. In this case, we
4241 // just ignore cv-qualifiers completely).
4242 if ((P->isPointerType() && A->isPointerType()) ||
4243 (P->isMemberPointerType() && A->isMemberPointerType()))
4244 TDF |= TDF_IgnoreQualifiers;
4245 if (TemplateDeductionResult Result
4246 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4247 P, A, Info, Deduced, TDF))
4248 return Result;
4249
4250 // Create an Instantiation Scope for finalizing the operator.
4251 LocalInstantiationScope InstScope(*this);
4252 // Finish template argument deduction.
4253 FunctionDecl *ConversionSpecialized = nullptr;
4254 TemplateDeductionResult Result
4255 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4256 ConversionSpecialized, Info);
4257 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4258 return Result;
4259}
4260
4261/// Deduce template arguments for a function template when there is
4262/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4263///
4264/// \param FunctionTemplate the function template for which we are performing
4265/// template argument deduction.
4266///
4267/// \param ExplicitTemplateArgs the explicitly-specified template
4268/// arguments.
4269///
4270/// \param Specialization if template argument deduction was successful,
4271/// this will be set to the function template specialization produced by
4272/// template argument deduction.
4273///
4274/// \param Info the argument will be updated to provide additional information
4275/// about template argument deduction.
4276///
4277/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4278/// the address of a function template in a context where we do not have a
4279/// target type, per [over.over]. If \c false, we are looking up a function
4280/// template specialization based on its signature, which only happens when
4281/// deducing a function parameter type from an argument that is a template-id
4282/// naming a function template specialization.
4283///
4284/// \returns the result of template argument deduction.
4285Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4286 FunctionTemplateDecl *FunctionTemplate,
4287 TemplateArgumentListInfo *ExplicitTemplateArgs,
4288 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4289 bool IsAddressOfFunction) {
4290 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4291 QualType(), Specialization, Info,
4292 IsAddressOfFunction);
4293}
4294
4295namespace {
4296 struct DependentAuto { bool IsPack; };
4297
4298 /// Substitute the 'auto' specifier or deduced template specialization type
4299 /// specifier within a type for a given replacement type.
4300 class SubstituteDeducedTypeTransform :
4301 public TreeTransform<SubstituteDeducedTypeTransform> {
4302 QualType Replacement;
4303 bool ReplacementIsPack;
4304 bool UseTypeSugar;
4305
4306 public:
4307 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
4308 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), Replacement(),
4309 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
4310
4311 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4312 bool UseTypeSugar = true)
4313 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4314 Replacement(Replacement), ReplacementIsPack(false),
4315 UseTypeSugar(UseTypeSugar) {}
4316
4317 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4318 assert(isa<TemplateTypeParmType>(Replacement) &&((isa<TemplateTypeParmType>(Replacement) && "unexpected unsugared replacement kind"
) ? static_cast<void> (0) : __assert_fail ("isa<TemplateTypeParmType>(Replacement) && \"unexpected unsugared replacement kind\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4319, __PRETTY_FUNCTION__))
4319 "unexpected unsugared replacement kind")((isa<TemplateTypeParmType>(Replacement) && "unexpected unsugared replacement kind"
) ? static_cast<void> (0) : __assert_fail ("isa<TemplateTypeParmType>(Replacement) && \"unexpected unsugared replacement kind\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4319, __PRETTY_FUNCTION__))
;
4320 QualType Result = Replacement;
4321 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4322 NewTL.setNameLoc(TL.getNameLoc());
4323 return Result;
4324 }
4325
4326 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4327 // If we're building the type pattern to deduce against, don't wrap the
4328 // substituted type in an AutoType. Certain template deduction rules
4329 // apply only when a template type parameter appears directly (and not if
4330 // the parameter is found through desugaring). For instance:
4331 // auto &&lref = lvalue;
4332 // must transform into "rvalue reference to T" not "rvalue reference to
4333 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4334 //
4335 // FIXME: Is this still necessary?
4336 if (!UseTypeSugar)
4337 return TransformDesugared(TLB, TL);
4338
4339 QualType Result = SemaRef.Context.getAutoType(
4340 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
4341 ReplacementIsPack);
4342 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4343 NewTL.setNameLoc(TL.getNameLoc());
4344 return Result;
4345 }
4346
4347 QualType TransformDeducedTemplateSpecializationType(
4348 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4349 if (!UseTypeSugar)
4350 return TransformDesugared(TLB, TL);
4351
4352 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4353 TL.getTypePtr()->getTemplateName(),
4354 Replacement, Replacement.isNull());
4355 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4356 NewTL.setNameLoc(TL.getNameLoc());
4357 return Result;
4358 }
4359
4360 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4361 // Lambdas never need to be transformed.
4362 return E;
4363 }
4364
4365 QualType Apply(TypeLoc TL) {
4366 // Create some scratch storage for the transformed type locations.
4367 // FIXME: We're just going to throw this information away. Don't build it.
4368 TypeLocBuilder TLB;
4369 TLB.reserve(TL.getFullDataSize());
4370 return TransformType(TLB, TL);
4371 }
4372 };
4373
4374} // namespace
4375
4376Sema::DeduceAutoResult
4377Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4378 Optional<unsigned> DependentDeductionDepth) {
4379 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4380 DependentDeductionDepth);
4381}
4382
4383/// Attempt to produce an informative diagostic explaining why auto deduction
4384/// failed.
4385/// \return \c true if diagnosed, \c false if not.
4386static bool diagnoseAutoDeductionFailure(Sema &S,
4387 Sema::TemplateDeductionResult TDK,
4388 TemplateDeductionInfo &Info,
4389 ArrayRef<SourceRange> Ranges) {
4390 switch (TDK) {
4391 case Sema::TDK_Inconsistent: {
4392 // Inconsistent deduction means we were deducing from an initializer list.
4393 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
4394 D << Info.FirstArg << Info.SecondArg;
4395 for (auto R : Ranges)
4396 D << R;
4397 return true;
4398 }
4399
4400 // FIXME: Are there other cases for which a custom diagnostic is more useful
4401 // than the basic "types don't match" diagnostic?
4402
4403 default:
4404 return false;
4405 }
4406}
4407
4408/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
4409///
4410/// Note that this is done even if the initializer is dependent. (This is
4411/// necessary to support partial ordering of templates using 'auto'.)
4412/// A dependent type will be produced when deducing from a dependent type.
4413///
4414/// \param Type the type pattern using the auto type-specifier.
4415/// \param Init the initializer for the variable whose type is to be deduced.
4416/// \param Result if type deduction was successful, this will be set to the
4417/// deduced type.
4418/// \param DependentDeductionDepth Set if we should permit deduction in
4419/// dependent cases. This is necessary for template partial ordering with
4420/// 'auto' template parameters. The value specified is the template
4421/// parameter depth at which we should perform 'auto' deduction.
4422Sema::DeduceAutoResult
4423Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4424 Optional<unsigned> DependentDeductionDepth) {
4425 if (Init->getType()->isNonOverloadPlaceholderType()) {
4426 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4427 if (NonPlaceholder.isInvalid())
4428 return DAR_FailedAlreadyDiagnosed;
4429 Init = NonPlaceholder.get();
4430 }
4431
4432 DependentAuto DependentResult = {
4433 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
4434
4435 if (!DependentDeductionDepth &&
4436 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4437 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
4438 assert(!Result.isNull() && "substituting DependentTy can't fail")((!Result.isNull() && "substituting DependentTy can't fail"
) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"substituting DependentTy can't fail\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4438, __PRETTY_FUNCTION__))
;
4439 return DAR_Succeeded;
4440 }
4441
4442 // Find the depth of template parameter to synthesize.
4443 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4444
4445 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4446 // Since 'decltype(auto)' can only occur at the top of the type, we
4447 // don't need to go digging for it.
4448 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
4449 if (AT->isDecltypeAuto()) {
4450 if (isa<InitListExpr>(Init)) {
4451 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
4452 return DAR_FailedAlreadyDiagnosed;
4453 }
4454
4455 ExprResult ER = CheckPlaceholderExpr(Init);
4456 if (ER.isInvalid())
4457 return DAR_FailedAlreadyDiagnosed;
4458 Init = ER.get();
4459 QualType Deduced = BuildDecltypeType(Init, Init->getBeginLoc(), false);
4460 if (Deduced.isNull())
4461 return DAR_FailedAlreadyDiagnosed;
4462 // FIXME: Support a non-canonical deduced type for 'auto'.
4463 Deduced = Context.getCanonicalType(Deduced);
4464 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
4465 if (Result.isNull())
4466 return DAR_FailedAlreadyDiagnosed;
4467 return DAR_Succeeded;
4468 } else if (!getLangOpts().CPlusPlus) {
4469 if (isa<InitListExpr>(Init)) {
4470 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c);
4471 return DAR_FailedAlreadyDiagnosed;
4472 }
4473 }
4474 }
4475
4476 SourceLocation Loc = Init->getExprLoc();
4477
4478 LocalInstantiationScope InstScope(*this);
4479
4480 // Build template<class TemplParam> void Func(FuncParam);
4481 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4482 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
4483 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4484 NamedDecl *TemplParamPtr = TemplParam;
4485 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4486 Loc, Loc, TemplParamPtr, Loc, nullptr);
4487
4488 QualType FuncParam =
4489 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
4490 .Apply(Type);
4491 assert(!FuncParam.isNull() &&((!FuncParam.isNull() && "substituting template parameter for 'auto' failed"
) ? static_cast<void> (0) : __assert_fail ("!FuncParam.isNull() && \"substituting template parameter for 'auto' failed\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4492, __PRETTY_FUNCTION__))
4492 "substituting template parameter for 'auto' failed")((!FuncParam.isNull() && "substituting template parameter for 'auto' failed"
) ? static_cast<void> (0) : __assert_fail ("!FuncParam.isNull() && \"substituting template parameter for 'auto' failed\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4492, __PRETTY_FUNCTION__))
;
4493
4494 // Deduce type of TemplParam in Func(Init)
4495 SmallVector<DeducedTemplateArgument, 1> Deduced;
4496 Deduced.resize(1);
4497
4498 TemplateDeductionInfo Info(Loc, Depth);
4499
4500 // If deduction failed, don't diagnose if the initializer is dependent; it
4501 // might acquire a matching type in the instantiation.
4502 auto DeductionFailed = [&](TemplateDeductionResult TDK,
4503 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
4504 if (Init->isTypeDependent()) {
4505 Result =
4506 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
4507 assert(!Result.isNull() && "substituting DependentTy can't fail")((!Result.isNull() && "substituting DependentTy can't fail"
) ? static_cast<void> (0) : __assert_fail ("!Result.isNull() && \"substituting DependentTy can't fail\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4507, __PRETTY_FUNCTION__))
;
4508 return DAR_Succeeded;
4509 }
4510 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
4511 return DAR_FailedAlreadyDiagnosed;
4512 return DAR_Failed;
4513 };
4514
4515 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4516
4517 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
4518 if (InitList) {
4519 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4520 // against that. Such deduction only succeeds if removing cv-qualifiers and
4521 // references results in std::initializer_list<T>.
4522 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4523 return DAR_Failed;
4524
4525 // Resolving a core issue: a braced-init-list containing any designators is
4526 // a non-deduced context.
4527 for (Expr *E : InitList->inits())
4528 if (isa<DesignatedInitExpr>(E))
4529 return DAR_Failed;
4530
4531 SourceRange DeducedFromInitRange;
4532 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
4533 Expr *Init = InitList->getInit(i);
4534
4535 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4536 *this, TemplateParamsSt.get(), 0, TemplArg, Init,
4537 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4538 /*ArgIdx*/ 0, /*TDF*/ 0))
4539 return DeductionFailed(TDK, {DeducedFromInitRange,
4540 Init->getSourceRange()});
4541
4542 if (DeducedFromInitRange.isInvalid() &&
4543 Deduced[0].getKind() != TemplateArgument::Null)
4544 DeducedFromInitRange = Init->getSourceRange();
4545 }
4546 } else {
4547 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4548 Diag(Loc, diag::err_auto_bitfield);
4549 return DAR_FailedAlreadyDiagnosed;
4550 }
4551
4552 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4553 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
4554 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
4555 return DeductionFailed(TDK, {});
4556 }
4557
4558 // Could be null if somehow 'auto' appears in a non-deduced context.
4559 if (Deduced[0].getKind() != TemplateArgument::Type)
4560 return DeductionFailed(TDK_Incomplete, {});
4561
4562 QualType DeducedType = Deduced[0].getAsType();
4563
4564 if (InitList) {
4565 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4566 if (DeducedType.isNull())
4567 return DAR_FailedAlreadyDiagnosed;
4568 }
4569
4570 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
4571 if (Result.isNull())
4572 return DAR_FailedAlreadyDiagnosed;
4573
4574 // Check that the deduced argument type is compatible with the original
4575 // argument type per C++ [temp.deduct.call]p4.
4576 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
4577 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
4578 assert((bool)InitList == OriginalArg.DecomposedParam &&(((bool)InitList == OriginalArg.DecomposedParam && "decomposed non-init-list in auto deduction?"
) ? static_cast<void> (0) : __assert_fail ("(bool)InitList == OriginalArg.DecomposedParam && \"decomposed non-init-list in auto deduction?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4579, __PRETTY_FUNCTION__))
4579 "decomposed non-init-list in auto deduction?")(((bool)InitList == OriginalArg.DecomposedParam && "decomposed non-init-list in auto deduction?"
) ? static_cast<void> (0) : __assert_fail ("(bool)InitList == OriginalArg.DecomposedParam && \"decomposed non-init-list in auto deduction?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4579, __PRETTY_FUNCTION__))
;
4580 if (auto TDK =
4581 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
4582 Result = QualType();
4583 return DeductionFailed(TDK, {});
4584 }
4585 }
4586
4587 return DAR_Succeeded;
4588}
4589
4590QualType Sema::SubstAutoType(QualType TypeWithAuto,
4591 QualType TypeToReplaceAuto) {
4592 if (TypeToReplaceAuto->isDependentType())
4593 return SubstituteDeducedTypeTransform(
4594 *this, DependentAuto{
4595 TypeToReplaceAuto->containsUnexpandedParameterPack()})
4596 .TransformType(TypeWithAuto);
4597 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4598 .TransformType(TypeWithAuto);
4599}
4600
4601TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4602 QualType TypeToReplaceAuto) {
4603 if (TypeToReplaceAuto->isDependentType())
4604 return SubstituteDeducedTypeTransform(
4605 *this,
4606 DependentAuto{
4607 TypeToReplaceAuto->containsUnexpandedParameterPack()})
4608 .TransformType(TypeWithAuto);
4609 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4610 .TransformType(TypeWithAuto);
4611}
4612
4613QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4614 QualType TypeToReplaceAuto) {
4615 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4616 /*UseTypeSugar*/ false)
4617 .TransformType(TypeWithAuto);
4618}
4619
4620void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4621 if (isa<InitListExpr>(Init))
4622 Diag(VDecl->getLocation(),
4623 VDecl->isInitCapture()
4624 ? diag::err_init_capture_deduction_failure_from_init_list
4625 : diag::err_auto_var_deduction_failure_from_init_list)
4626 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4627 else
4628 Diag(VDecl->getLocation(),
4629 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4630 : diag::err_auto_var_deduction_failure)
4631 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4632 << Init->getSourceRange();
4633}
4634
4635bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4636 bool Diagnose) {
4637 assert(FD->getReturnType()->isUndeducedType())((FD->getReturnType()->isUndeducedType()) ? static_cast
<void> (0) : __assert_fail ("FD->getReturnType()->isUndeducedType()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4637, __PRETTY_FUNCTION__))
;
4638
4639 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
4640 // within the return type from the call operator's type.
4641 if (isLambdaConversionOperator(FD)) {
4642 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
4643 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
4644
4645 // For a generic lambda, instantiate the call operator if needed.
4646 if (auto *Args = FD->getTemplateSpecializationArgs()) {
4647 CallOp = InstantiateFunctionDeclaration(
4648 CallOp->getDescribedFunctionTemplate(), Args, Loc);
4649 if (!CallOp || CallOp->isInvalidDecl())
4650 return true;
4651
4652 // We might need to deduce the return type by instantiating the definition
4653 // of the operator() function.
4654 if (CallOp->getReturnType()->isUndeducedType()) {
4655 runWithSufficientStackSpace(Loc, [&] {
4656 InstantiateFunctionDefinition(Loc, CallOp);
4657 });
4658 }
4659 }
4660
4661 if (CallOp->isInvalidDecl())
4662 return true;
4663 assert(!CallOp->getReturnType()->isUndeducedType() &&((!CallOp->getReturnType()->isUndeducedType() &&
"failed to deduce lambda return type") ? static_cast<void
> (0) : __assert_fail ("!CallOp->getReturnType()->isUndeducedType() && \"failed to deduce lambda return type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4664, __PRETTY_FUNCTION__))
4664 "failed to deduce lambda return type")((!CallOp->getReturnType()->isUndeducedType() &&
"failed to deduce lambda return type") ? static_cast<void
> (0) : __assert_fail ("!CallOp->getReturnType()->isUndeducedType() && \"failed to deduce lambda return type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4664, __PRETTY_FUNCTION__))
;
4665
4666 // Build the new return type from scratch.
4667 QualType RetType = getLambdaConversionFunctionResultType(
4668 CallOp->getType()->castAs<FunctionProtoType>());
4669 if (FD->getReturnType()->getAs<PointerType>())
4670 RetType = Context.getPointerType(RetType);
4671 else {
4672 assert(FD->getReturnType()->getAs<BlockPointerType>())((FD->getReturnType()->getAs<BlockPointerType>())
? static_cast<void> (0) : __assert_fail ("FD->getReturnType()->getAs<BlockPointerType>()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4672, __PRETTY_FUNCTION__))
;
4673 RetType = Context.getBlockPointerType(RetType);
4674 }
4675 Context.adjustDeducedFunctionResultType(FD, RetType);
4676 return false;
4677 }
4678
4679 if (FD->getTemplateInstantiationPattern()) {
4680 runWithSufficientStackSpace(Loc, [&] {
4681 InstantiateFunctionDefinition(Loc, FD);
4682 });
4683 }
4684
4685 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
4686 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4687 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4688 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4689 }
4690
4691 return StillUndeduced;
4692}
4693
4694/// If this is a non-static member function,
4695static void
4696AddImplicitObjectParameterType(ASTContext &Context,
4697 CXXMethodDecl *Method,
4698 SmallVectorImpl<QualType> &ArgTypes) {
4699 // C++11 [temp.func.order]p3:
4700 // [...] The new parameter is of type "reference to cv A," where cv are
4701 // the cv-qualifiers of the function template (if any) and A is
4702 // the class of which the function template is a member.
4703 //
4704 // The standard doesn't say explicitly, but we pick the appropriate kind of
4705 // reference type based on [over.match.funcs]p4.
4706 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4707 ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers());
4708 if (Method->getRefQualifier() == RQ_RValue)
4709 ArgTy = Context.getRValueReferenceType(ArgTy);
4710 else
4711 ArgTy = Context.getLValueReferenceType(ArgTy);
4712 ArgTypes.push_back(ArgTy);
4713}
4714
4715/// Determine whether the function template \p FT1 is at least as
4716/// specialized as \p FT2.
4717static bool isAtLeastAsSpecializedAs(Sema &S,
4718 SourceLocation Loc,
4719 FunctionTemplateDecl *FT1,
4720 FunctionTemplateDecl *FT2,
4721 TemplatePartialOrderingContext TPOC,
4722 unsigned NumCallArguments1) {
4723 FunctionDecl *FD1 = FT1->getTemplatedDecl();
4724 FunctionDecl *FD2 = FT2->getTemplatedDecl();
4725 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4726 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
4727
4728 assert(Proto1 && Proto2 && "Function templates must have prototypes")((Proto1 && Proto2 && "Function templates must have prototypes"
) ? static_cast<void> (0) : __assert_fail ("Proto1 && Proto2 && \"Function templates must have prototypes\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4728, __PRETTY_FUNCTION__))
;
4729 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
4730 SmallVector<DeducedTemplateArgument, 4> Deduced;
4731 Deduced.resize(TemplateParams->size());
4732
4733 // C++0x [temp.deduct.partial]p3:
4734 // The types used to determine the ordering depend on the context in which
4735 // the partial ordering is done:
4736 TemplateDeductionInfo Info(Loc);
4737 SmallVector<QualType, 4> Args2;
4738 switch (TPOC) {
4739 case TPOC_Call: {
4740 // - In the context of a function call, the function parameter types are
4741 // used.
4742 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4743 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
4744
4745 // C++11 [temp.func.order]p3:
4746 // [...] If only one of the function templates is a non-static
4747 // member, that function template is considered to have a new
4748 // first parameter inserted in its function parameter list. The
4749 // new parameter is of type "reference to cv A," where cv are
4750 // the cv-qualifiers of the function template (if any) and A is
4751 // the class of which the function template is a member.
4752 //
4753 // Note that we interpret this to mean "if one of the function
4754 // templates is a non-static member and the other is a non-member";
4755 // otherwise, the ordering rules for static functions against non-static
4756 // functions don't make any sense.
4757 //
4758 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4759 // it as wording was broken prior to it.
4760 SmallVector<QualType, 4> Args1;
4761
4762 unsigned NumComparedArguments = NumCallArguments1;
4763
4764 if (!Method2 && Method1 && !Method1->isStatic()) {
4765 // Compare 'this' from Method1 against first parameter from Method2.
4766 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4767 ++NumComparedArguments;
4768 } else if (!Method1 && Method2 && !Method2->isStatic()) {
4769 // Compare 'this' from Method2 against first parameter from Method1.
4770 AddImplicitObjectParameterType(S.Context, Method2, Args2);
4771 }
4772
4773 Args1.insert(Args1.end(), Proto1->param_type_begin(),
4774 Proto1->param_type_end());
4775 Args2.insert(Args2.end(), Proto2->param_type_begin(),
4776 Proto2->param_type_end());
4777
4778 // C++ [temp.func.order]p5:
4779 // The presence of unused ellipsis and default arguments has no effect on
4780 // the partial ordering of function templates.
4781 if (Args1.size() > NumComparedArguments)
4782 Args1.resize(NumComparedArguments);
4783 if (Args2.size() > NumComparedArguments)
4784 Args2.resize(NumComparedArguments);
4785 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4786 Args1.data(), Args1.size(), Info, Deduced,
4787 TDF_None, /*PartialOrdering=*/true))
4788 return false;
4789
4790 break;
4791 }
4792
4793 case TPOC_Conversion:
4794 // - In the context of a call to a conversion operator, the return types
4795 // of the conversion function templates are used.
4796 if (DeduceTemplateArgumentsByTypeMatch(
4797 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4798 Info, Deduced, TDF_None,
4799 /*PartialOrdering=*/true))
4800 return false;
4801 break;
4802
4803 case TPOC_Other:
4804 // - In other contexts (14.6.6.2) the function template's function type
4805 // is used.
4806 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4807 FD2->getType(), FD1->getType(),
4808 Info, Deduced, TDF_None,
4809 /*PartialOrdering=*/true))
4810 return false;
4811 break;
4812 }
4813
4814 // C++0x [temp.deduct.partial]p11:
4815 // In most cases, all template parameters must have values in order for
4816 // deduction to succeed, but for partial ordering purposes a template
4817 // parameter may remain without a value provided it is not used in the
4818 // types being used for partial ordering. [ Note: a template parameter used
4819 // in a non-deduced context is considered used. -end note]
4820 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4821 for (; ArgIdx != NumArgs; ++ArgIdx)
4822 if (Deduced[ArgIdx].isNull())
4823 break;
4824
4825 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4826 // to substitute the deduced arguments back into the template and check that
4827 // we get the right type.
4828
4829 if (ArgIdx == NumArgs) {
4830 // All template arguments were deduced. FT1 is at least as specialized
4831 // as FT2.
4832 return true;
4833 }
4834
4835 // Figure out which template parameters were used.
4836 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4837 switch (TPOC) {
4838 case TPOC_Call:
4839 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4840 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4841 TemplateParams->getDepth(),
4842 UsedParameters);
4843 break;
4844
4845 case TPOC_Conversion:
4846 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4847 TemplateParams->getDepth(), UsedParameters);
4848 break;
4849
4850 case TPOC_Other:
4851 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4852 TemplateParams->getDepth(),
4853 UsedParameters);
4854 break;
4855 }
4856
4857 for (; ArgIdx != NumArgs; ++ArgIdx)
4858 // If this argument had no value deduced but was used in one of the types
4859 // used for partial ordering, then deduction fails.
4860 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4861 return false;
4862
4863 return true;
4864}
4865
4866/// Determine whether this a function template whose parameter-type-list
4867/// ends with a function parameter pack.
4868static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4869 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4870 unsigned NumParams = Function->getNumParams();
4871 if (NumParams == 0)
4872 return false;
4873
4874 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4875 if (!Last->isParameterPack())
4876 return false;
4877
4878 // Make sure that no previous parameter is a parameter pack.
4879 while (--NumParams > 0) {
4880 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4881 return false;
4882 }
4883
4884 return true;
4885}
4886
4887/// Returns the more specialized function template according
4888/// to the rules of function template partial ordering (C++ [temp.func.order]).
4889///
4890/// \param FT1 the first function template
4891///
4892/// \param FT2 the second function template
4893///
4894/// \param TPOC the context in which we are performing partial ordering of
4895/// function templates.
4896///
4897/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4898/// only when \c TPOC is \c TPOC_Call.
4899///
4900/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4901/// only when \c TPOC is \c TPOC_Call.
4902///
4903/// \returns the more specialized function template. If neither
4904/// template is more specialized, returns NULL.
4905FunctionTemplateDecl *
4906Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4907 FunctionTemplateDecl *FT2,
4908 SourceLocation Loc,
4909 TemplatePartialOrderingContext TPOC,
4910 unsigned NumCallArguments1,
4911 unsigned NumCallArguments2) {
4912 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
4913 NumCallArguments1);
4914 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
4915 NumCallArguments2);
4916
4917 if (Better1 != Better2) // We have a clear winner
4918 return Better1 ? FT1 : FT2;
4919
4920 if (!Better1 && !Better2) // Neither is better than the other
4921 return nullptr;
4922
4923 // FIXME: This mimics what GCC implements, but doesn't match up with the
4924 // proposed resolution for core issue 692. This area needs to be sorted out,
4925 // but for now we attempt to maintain compatibility.
4926 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4927 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4928 if (Variadic1 != Variadic2)
4929 return Variadic1? FT2 : FT1;
4930
4931 return nullptr;
4932}
4933
4934/// Determine if the two templates are equivalent.
4935static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4936 if (T1 == T2)
4937 return true;
4938
4939 if (!T1 || !T2)
4940 return false;
4941
4942 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4943}
4944
4945/// Retrieve the most specialized of the given function template
4946/// specializations.
4947///
4948/// \param SpecBegin the start iterator of the function template
4949/// specializations that we will be comparing.
4950///
4951/// \param SpecEnd the end iterator of the function template
4952/// specializations, paired with \p SpecBegin.
4953///
4954/// \param Loc the location where the ambiguity or no-specializations
4955/// diagnostic should occur.
4956///
4957/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4958/// no matching candidates.
4959///
4960/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4961/// occurs.
4962///
4963/// \param CandidateDiag partial diagnostic used for each function template
4964/// specialization that is a candidate in the ambiguous ordering. One parameter
4965/// in this diagnostic should be unbound, which will correspond to the string
4966/// describing the template arguments for the function template specialization.
4967///
4968/// \returns the most specialized function template specialization, if
4969/// found. Otherwise, returns SpecEnd.
4970UnresolvedSetIterator Sema::getMostSpecialized(
4971 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4972 TemplateSpecCandidateSet &FailedCandidates,
4973 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4974 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4975 bool Complain, QualType TargetType) {
4976 if (SpecBegin == SpecEnd) {
4977 if (Complain) {
4978 Diag(Loc, NoneDiag);
4979 FailedCandidates.NoteCandidates(*this, Loc);
4980 }
4981 return SpecEnd;
4982 }
4983
4984 if (SpecBegin + 1 == SpecEnd)
4985 return SpecBegin;
4986
4987 // Find the function template that is better than all of the templates it
4988 // has been compared to.
4989 UnresolvedSetIterator Best = SpecBegin;
4990 FunctionTemplateDecl *BestTemplate
4991 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
4992 assert(BestTemplate && "Not a function template specialization?")((BestTemplate && "Not a function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("BestTemplate && \"Not a function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4992, __PRETTY_FUNCTION__))
;
4993 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4994 FunctionTemplateDecl *Challenger
4995 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4996 assert(Challenger && "Not a function template specialization?")((Challenger && "Not a function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Challenger && \"Not a function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4996, __PRETTY_FUNCTION__))
;
4997 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4998 Loc, TPOC_Other, 0, 0),
4999 Challenger)) {
5000 Best = I;
5001 BestTemplate = Challenger;
5002 }
5003 }
5004
5005 // Make sure that the "best" function template is more specialized than all
5006 // of the others.
5007 bool Ambiguous = false;
5008 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5009 FunctionTemplateDecl *Challenger
5010 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5011 if (I != Best &&
5012 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5013 Loc, TPOC_Other, 0, 0),
5014 BestTemplate)) {
5015 Ambiguous = true;
5016 break;
5017 }
5018 }
5019
5020 if (!Ambiguous) {
5021 // We found an answer. Return it.
5022 return Best;
5023 }
5024
5025 // Diagnose the ambiguity.
5026 if (Complain) {
5027 Diag(Loc, AmbigDiag);
5028
5029 // FIXME: Can we order the candidates in some sane way?
5030 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5031 PartialDiagnostic PD = CandidateDiag;
5032 const auto *FD = cast<FunctionDecl>(*I);
5033 PD << FD << getTemplateArgumentBindingsText(
5034 FD->getPrimaryTemplate()->getTemplateParameters(),
5035 *FD->getTemplateSpecializationArgs());
5036 if (!TargetType.isNull())
5037 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
5038 Diag((*I)->getLocation(), PD);
5039 }
5040 }
5041
5042 return SpecEnd;
5043}
5044
5045/// Determine whether one partial specialization, P1, is at least as
5046/// specialized than another, P2.
5047///
5048/// \tparam TemplateLikeDecl The kind of P2, which must be a
5049/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
5050/// \param T1 The injected-class-name of P1 (faked for a variable template).
5051/// \param T2 The injected-class-name of P2 (faked for a variable template).
5052template<typename TemplateLikeDecl>
5053static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
5054 TemplateLikeDecl *P2,
5055 TemplateDeductionInfo &Info) {
5056 // C++ [temp.class.order]p1:
5057 // For two class template partial specializations, the first is at least as
5058 // specialized as the second if, given the following rewrite to two
5059 // function templates, the first function template is at least as
5060 // specialized as the second according to the ordering rules for function
5061 // templates (14.6.6.2):
5062 // - the first function template has the same template parameters as the
5063 // first partial specialization and has a single function parameter
5064 // whose type is a class template specialization with the template
5065 // arguments of the first partial specialization, and
5066 // - the second function template has the same template parameters as the
5067 // second partial specialization and has a single function parameter
5068 // whose type is a class template specialization with the template
5069 // arguments of the second partial specialization.
5070 //
5071 // Rather than synthesize function templates, we merely perform the
5072 // equivalent partial ordering by performing deduction directly on
5073 // the template arguments of the class template partial
5074 // specializations. This computation is slightly simpler than the
5075 // general problem of function template partial ordering, because
5076 // class template partial specializations are more constrained. We
5077 // know that every template parameter is deducible from the class
5078 // template partial specialization's template arguments, for
5079 // example.
5080 SmallVector<DeducedTemplateArgument, 4> Deduced;
5081
5082 // Determine whether P1 is at least as specialized as P2.
5083 Deduced.resize(P2->getTemplateParameters()->size());
5084 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
5085 T2, T1, Info, Deduced, TDF_None,
5086 /*PartialOrdering=*/true))
5087 return false;
5088
5089 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5090 Deduced.end());
5091 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5092 Info);
5093 auto *TST1 = T1->castAs<TemplateSpecializationType>();
5094 if (FinishTemplateArgumentDeduction(
5095 S, P2, /*IsPartialOrdering=*/true,
5096 TemplateArgumentList(TemplateArgumentList::OnStack,
5097 TST1->template_arguments()),
5098 Deduced, Info))
5099 return false;
5100
5101 return true;
5102}
5103
5104/// Returns the more specialized class template partial specialization
5105/// according to the rules of partial ordering of class template partial
5106/// specializations (C++ [temp.class.order]).
5107///
5108/// \param PS1 the first class template partial specialization
5109///
5110/// \param PS2 the second class template partial specialization
5111///
5112/// \returns the more specialized class template partial specialization. If
5113/// neither partial specialization is more specialized, returns NULL.
5114ClassTemplatePartialSpecializationDecl *
5115Sema::getMoreSpecializedPartialSpecialization(
5116 ClassTemplatePartialSpecializationDecl *PS1,
5117 ClassTemplatePartialSpecializationDecl *PS2,
5118 SourceLocation Loc) {
5119 QualType PT1 = PS1->getInjectedSpecializationType();
5120 QualType PT2 = PS2->getInjectedSpecializationType();
5121
5122 TemplateDeductionInfo Info(Loc);
5123 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5124 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
5125
5126 if (Better1 == Better2)
5127 return nullptr;
5128
5129 return Better1 ? PS1 : PS2;
5130}
5131
5132bool Sema::isMoreSpecializedThanPrimary(
5133 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5134 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
5135 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
5136 QualType PartialT = Spec->getInjectedSpecializationType();
5137 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5138 return false;
5139 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5140 Info.clearSFINAEDiagnostic();
5141 return false;
5142 }
5143 return true;
5144}
5145
5146VarTemplatePartialSpecializationDecl *
5147Sema::getMoreSpecializedPartialSpecialization(
5148 VarTemplatePartialSpecializationDecl *PS1,
5149 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
5150 // Pretend the variable template specializations are class template
5151 // specializations and form a fake injected class name type for comparison.
5152 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&((PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate
() && "the partial specializations being compared should specialize"
" the same template.") ? static_cast<void> (0) : __assert_fail
("PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && \"the partial specializations being compared should specialize\" \" the same template.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5154, __PRETTY_FUNCTION__))
5153 "the partial specializations being compared should specialize"((PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate
() && "the partial specializations being compared should specialize"
" the same template.") ? static_cast<void> (0) : __assert_fail
("PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && \"the partial specializations being compared should specialize\" \" the same template.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5154, __PRETTY_FUNCTION__))
5154 " the same template.")((PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate
() && "the partial specializations being compared should specialize"
" the same template.") ? static_cast<void> (0) : __assert_fail
("PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && \"the partial specializations being compared should specialize\" \" the same template.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5154, __PRETTY_FUNCTION__))
;
5155 TemplateName Name(PS1->getSpecializedTemplate());
5156 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5157 QualType PT1 = Context.getTemplateSpecializationType(
5158 CanonTemplate, PS1->getTemplateArgs().asArray());
5159 QualType PT2 = Context.getTemplateSpecializationType(
5160 CanonTemplate, PS2->getTemplateArgs().asArray());
5161
5162 TemplateDeductionInfo Info(Loc);
5163 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5164 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
5165
5166 if (Better1 == Better2)
5167 return nullptr;
5168
5169 return Better1 ? PS1 : PS2;
5170}
5171
5172bool Sema::isMoreSpecializedThanPrimary(
5173 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5174 TemplateDecl *Primary = Spec->getSpecializedTemplate();
5175 // FIXME: Cache the injected template arguments rather than recomputing
5176 // them for each partial specialization.
5177 SmallVector<TemplateArgument, 8> PrimaryArgs;
5178 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
5179 PrimaryArgs);
5180
5181 TemplateName CanonTemplate =
5182 Context.getCanonicalTemplateName(TemplateName(Primary));
5183 QualType PrimaryT = Context.getTemplateSpecializationType(
5184 CanonTemplate, PrimaryArgs);
5185 QualType PartialT = Context.getTemplateSpecializationType(
5186 CanonTemplate, Spec->getTemplateArgs().asArray());
5187 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5188 return false;
5189 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5190 Info.clearSFINAEDiagnostic();
5191 return false;
5192 }
5193 return true;
5194}
5195
5196bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5197 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5198 // C++1z [temp.arg.template]p4: (DR 150)
5199 // A template template-parameter P is at least as specialized as a
5200 // template template-argument A if, given the following rewrite to two
5201 // function templates...
5202
5203 // Rather than synthesize function templates, we merely perform the
5204 // equivalent partial ordering by performing deduction directly on
5205 // the template parameter lists of the template template parameters.
5206 //
5207 // Given an invented class template X with the template parameter list of
5208 // A (including default arguments):
5209 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5210 TemplateParameterList *A = AArg->getTemplateParameters();
5211
5212 // - Each function template has a single function parameter whose type is
5213 // a specialization of X with template arguments corresponding to the
5214 // template parameters from the respective function template
5215 SmallVector<TemplateArgument, 8> AArgs;
5216 Context.getInjectedTemplateArgs(A, AArgs);
5217
5218 // Check P's arguments against A's parameter list. This will fill in default
5219 // template arguments as needed. AArgs are already correct by construction.
5220 // We can't just use CheckTemplateIdType because that will expand alias
5221 // templates.
5222 SmallVector<TemplateArgument, 4> PArgs;
5223 {
5224 SFINAETrap Trap(*this);
5225
5226 Context.getInjectedTemplateArgs(P, PArgs);
5227 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
5228 for (unsigned I = 0, N = P->size(); I != N; ++I) {
5229 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5230 // expansions, to form an "as written" argument list.
5231 TemplateArgument Arg = PArgs[I];
5232 if (Arg.getKind() == TemplateArgument::Pack) {
5233 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion())((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion
()) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5233, __PRETTY_FUNCTION__))
;
5234 Arg = *Arg.pack_begin();
5235 }
5236 PArgList.addArgument(getTrivialTemplateArgumentLoc(
5237 Arg, QualType(), P->getParam(I)->getLocation()));
5238 }
5239 PArgs.clear();
5240
5241 // C++1z [temp.arg.template]p3:
5242 // If the rewrite produces an invalid type, then P is not at least as
5243 // specialized as A.
5244 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
5245 Trap.hasErrorOccurred())
5246 return false;
5247 }
5248
5249 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
5250 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
5251
5252 // ... the function template corresponding to P is at least as specialized
5253 // as the function template corresponding to A according to the partial
5254 // ordering rules for function templates.
5255 TemplateDeductionInfo Info(Loc, A->getDepth());
5256 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5257}
5258
5259/// Mark the template parameters that are used by the given
5260/// expression.
5261static void
5262MarkUsedTemplateParameters(ASTContext &Ctx,
5263 const Expr *E,
5264 bool OnlyDeduced,
5265 unsigned Depth,
5266 llvm::SmallBitVector &Used) {
5267 // We can deduce from a pack expansion.
5268 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5269 E = Expansion->getPattern();
5270
5271 // Skip through any implicit casts we added while type-checking, and any
5272 // substitutions performed by template alias expansion.
5273 while (true) {
5274 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
5275 E = ICE->getSubExpr();
5276 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
5277 E = CE->getSubExpr();
5278 else if (const SubstNonTypeTemplateParmExpr *Subst =
5279 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
5280 E = Subst->getReplacement();
5281 else
5282 break;
5283 }
5284
5285 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
5286 // find other occurrences of template parameters.
5287 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
5288 if (!DRE)
5289 return;
5290
5291 const NonTypeTemplateParmDecl *NTTP
5292 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5293 if (!NTTP)
5294 return;
5295
5296 if (NTTP->getDepth() == Depth)
5297 Used[NTTP->getIndex()] = true;
5298
5299 // In C++17 mode, additional arguments may be deduced from the type of a
5300 // non-type argument.
5301 if (Ctx.getLangOpts().CPlusPlus17)
5302 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
5303}
5304
5305/// Mark the template parameters that are used by the given
5306/// nested name specifier.
5307static void
5308MarkUsedTemplateParameters(ASTContext &Ctx,
5309 NestedNameSpecifier *NNS,
5310 bool OnlyDeduced,
5311 unsigned Depth,
5312 llvm::SmallBitVector &Used) {
5313 if (!NNS)
5314 return;
5315
5316 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
5317 Used);
5318 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
5319 OnlyDeduced, Depth, Used);
5320}
5321
5322/// Mark the template parameters that are used by the given
5323/// template name.
5324static void
5325MarkUsedTemplateParameters(ASTContext &Ctx,
5326 TemplateName Name,
5327 bool OnlyDeduced,
5328 unsigned Depth,
5329 llvm::SmallBitVector &Used) {
5330 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5331 if (TemplateTemplateParmDecl *TTP
5332 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5333 if (TTP->getDepth() == Depth)
5334 Used[TTP->getIndex()] = true;
5335 }
5336 return;
5337 }
5338
5339 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
5340 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
5341 Depth, Used);
5342 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
5343 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
5344 Depth, Used);
5345}
5346
5347/// Mark the template parameters that are used by the given
5348/// type.
5349static void
5350MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
5351 bool OnlyDeduced,
5352 unsigned Depth,
5353 llvm::SmallBitVector &Used) {
5354 if (T.isNull())
5355 return;
5356
5357 // Non-dependent types have nothing deducible
5358 if (!T->isDependentType())
5359 return;
5360
5361 T = Ctx.getCanonicalType(T);
5362 switch (T->getTypeClass()) {
5363 case Type::Pointer:
5364 MarkUsedTemplateParameters(Ctx,
5365 cast<PointerType>(T)->getPointeeType(),
5366 OnlyDeduced,
5367 Depth,
5368 Used);
5369 break;
5370
5371 case Type::BlockPointer:
5372 MarkUsedTemplateParameters(Ctx,
5373 cast<BlockPointerType>(T)->getPointeeType(),
5374 OnlyDeduced,
5375 Depth,
5376 Used);
5377 break;
5378
5379 case Type::LValueReference:
5380 case Type::RValueReference:
5381 MarkUsedTemplateParameters(Ctx,
5382 cast<ReferenceType>(T)->getPointeeType(),
5383 OnlyDeduced,
5384 Depth,
5385 Used);
5386 break;
5387
5388 case Type::MemberPointer: {
5389 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
5390 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
5391 Depth, Used);
5392 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
5393 OnlyDeduced, Depth, Used);
5394 break;
5395 }
5396
5397 case Type::DependentSizedArray:
5398 MarkUsedTemplateParameters(Ctx,
5399 cast<DependentSizedArrayType>(T)->getSizeExpr(),
5400 OnlyDeduced, Depth, Used);
5401 // Fall through to check the element type
5402 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5403
5404 case Type::ConstantArray:
5405 case Type::IncompleteArray:
5406 MarkUsedTemplateParameters(Ctx,
5407 cast<ArrayType>(T)->getElementType(),
5408 OnlyDeduced, Depth, Used);
5409 break;
5410
5411 case Type::Vector:
5412 case Type::ExtVector:
5413 MarkUsedTemplateParameters(Ctx,
5414 cast<VectorType>(T)->getElementType(),
5415 OnlyDeduced, Depth, Used);
5416 break;
5417
5418 case Type::DependentVector: {
5419 const auto *VecType = cast<DependentVectorType>(T);
5420 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5421 Depth, Used);
5422 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
5423 Used);
5424 break;
5425 }
5426 case Type::DependentSizedExtVector: {
5427 const DependentSizedExtVectorType *VecType
5428 = cast<DependentSizedExtVectorType>(T);
5429 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5430 Depth, Used);
5431 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
5432 Depth, Used);
5433 break;
5434 }
5435
5436 case Type::DependentAddressSpace: {
5437 const DependentAddressSpaceType *DependentASType =
5438 cast<DependentAddressSpaceType>(T);
5439 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
5440 OnlyDeduced, Depth, Used);
5441 MarkUsedTemplateParameters(Ctx,
5442 DependentASType->getAddrSpaceExpr(),
5443 OnlyDeduced, Depth, Used);
5444 break;
5445 }
5446
5447 case Type::FunctionProto: {
5448 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
5449 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5450 Used);
5451 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
5452 // C++17 [temp.deduct.type]p5:
5453 // The non-deduced contexts are: [...]
5454 // -- A function parameter pack that does not occur at the end of the
5455 // parameter-declaration-list.
5456 if (!OnlyDeduced || I + 1 == N ||
5457 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
5458 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
5459 Depth, Used);
5460 } else {
5461 // FIXME: C++17 [temp.deduct.call]p1:
5462 // When a function parameter pack appears in a non-deduced context,
5463 // the type of that pack is never deduced.
5464 //
5465 // We should also track a set of "never deduced" parameters, and
5466 // subtract that from the list of deduced parameters after marking.
5467 }
5468 }
5469 if (auto *E = Proto->getNoexceptExpr())
5470 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
5471 break;
5472 }
5473
5474 case Type::TemplateTypeParm: {
5475 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5476 if (TTP->getDepth() == Depth)
5477 Used[TTP->getIndex()] = true;
5478 break;
5479 }
5480
5481 case Type::SubstTemplateTypeParmPack: {
5482 const SubstTemplateTypeParmPackType *Subst
5483 = cast<SubstTemplateTypeParmPackType>(T);
5484 MarkUsedTemplateParameters(Ctx,
5485 QualType(Subst->getReplacedParameter(), 0),
5486 OnlyDeduced, Depth, Used);
5487 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
5488 OnlyDeduced, Depth, Used);
5489 break;
5490 }
5491
5492 case Type::InjectedClassName:
5493 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5494 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5495
5496 case Type::TemplateSpecialization: {
5497 const TemplateSpecializationType *Spec
5498 = cast<TemplateSpecializationType>(T);
5499 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
5500 Depth, Used);
5501
5502 // C++0x [temp.deduct.type]p9:
5503 // If the template argument list of P contains a pack expansion that is
5504 // not the last template argument, the entire template argument list is a
5505 // non-deduced context.
5506 if (OnlyDeduced &&
5507 hasPackExpansionBeforeEnd(Spec->template_arguments()))
5508 break;
5509
5510 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5511 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5512 Used);
5513 break;
5514 }
5515
5516 case Type::Complex:
5517 if (!OnlyDeduced)
5518 MarkUsedTemplateParameters(Ctx,
5519 cast<ComplexType>(T)->getElementType(),
5520 OnlyDeduced, Depth, Used);
5521 break;
5522
5523 case Type::Atomic:
5524 if (!OnlyDeduced)
5525 MarkUsedTemplateParameters(Ctx,
5526 cast<AtomicType>(T)->getValueType(),
5527 OnlyDeduced, Depth, Used);
5528 break;
5529
5530 case Type::DependentName:
5531 if (!OnlyDeduced)
5532 MarkUsedTemplateParameters(Ctx,
5533 cast<DependentNameType>(T)->getQualifier(),
5534 OnlyDeduced, Depth, Used);
5535 break;
5536
5537 case Type::DependentTemplateSpecialization: {
5538 // C++14 [temp.deduct.type]p5:
5539 // The non-deduced contexts are:
5540 // -- The nested-name-specifier of a type that was specified using a
5541 // qualified-id
5542 //
5543 // C++14 [temp.deduct.type]p6:
5544 // When a type name is specified in a way that includes a non-deduced
5545 // context, all of the types that comprise that type name are also
5546 // non-deduced.
5547 if (OnlyDeduced)
5548 break;
5549
5550 const DependentTemplateSpecializationType *Spec
5551 = cast<DependentTemplateSpecializationType>(T);
5552
5553 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5554 OnlyDeduced, Depth, Used);
5555
5556 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5557 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5558 Used);
5559 break;
5560 }
5561
5562 case Type::TypeOf:
5563 if (!OnlyDeduced)
5564 MarkUsedTemplateParameters(Ctx,
5565 cast<TypeOfType>(T)->getUnderlyingType(),
5566 OnlyDeduced, Depth, Used);
5567 break;
5568
5569 case Type::TypeOfExpr:
5570 if (!OnlyDeduced)
5571 MarkUsedTemplateParameters(Ctx,
5572 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5573 OnlyDeduced, Depth, Used);
5574 break;
5575
5576 case Type::Decltype:
5577 if (!OnlyDeduced)
5578 MarkUsedTemplateParameters(Ctx,
5579 cast<DecltypeType>(T)->getUnderlyingExpr(),
5580 OnlyDeduced, Depth, Used);
5581 break;
5582
5583 case Type::UnaryTransform:
5584 if (!OnlyDeduced)
5585 MarkUsedTemplateParameters(Ctx,
5586 cast<UnaryTransformType>(T)->getUnderlyingType(),
5587 OnlyDeduced, Depth, Used);
5588 break;
5589
5590 case Type::PackExpansion:
5591 MarkUsedTemplateParameters(Ctx,
5592 cast<PackExpansionType>(T)->getPattern(),
5593 OnlyDeduced, Depth, Used);
5594 break;
5595
5596 case Type::Auto:
5597 case Type::DeducedTemplateSpecialization:
5598 MarkUsedTemplateParameters(Ctx,
5599 cast<DeducedType>(T)->getDeducedType(),
5600 OnlyDeduced, Depth, Used);
5601 break;
5602
5603 // None of these types have any template parameters in them.
5604 case Type::Builtin:
5605 case Type::VariableArray:
5606 case Type::FunctionNoProto:
5607 case Type::Record:
5608 case Type::Enum:
5609 case Type::ObjCInterface:
5610 case Type::ObjCObject:
5611 case Type::ObjCObjectPointer:
5612 case Type::UnresolvedUsing:
5613 case Type::Pipe:
5614#define TYPE(Class, Base)
5615#define ABSTRACT_TYPE(Class, Base)
5616#define DEPENDENT_TYPE(Class, Base)
5617#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5618#include "clang/AST/TypeNodes.inc"
5619 break;
5620 }
5621}
5622
5623/// Mark the template parameters that are used by this
5624/// template argument.
5625static void
5626MarkUsedTemplateParameters(ASTContext &Ctx,
5627 const TemplateArgument &TemplateArg,
5628 bool OnlyDeduced,
5629 unsigned Depth,
5630 llvm::SmallBitVector &Used) {
5631 switch (TemplateArg.getKind()) {
5632 case TemplateArgument::Null:
5633 case TemplateArgument::Integral:
5634 case TemplateArgument::Declaration:
5635 break;
5636
5637 case TemplateArgument::NullPtr:
5638 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5639 Depth, Used);
5640 break;
5641
5642 case TemplateArgument::Type:
5643 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
5644 Depth, Used);
5645 break;
5646
5647 case TemplateArgument::Template:
5648 case TemplateArgument::TemplateExpansion:
5649 MarkUsedTemplateParameters(Ctx,
5650 TemplateArg.getAsTemplateOrTemplatePattern(),
5651 OnlyDeduced, Depth, Used);
5652 break;
5653
5654 case TemplateArgument::Expression:
5655 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
5656 Depth, Used);
5657 break;
5658
5659 case TemplateArgument::Pack:
5660 for (const auto &P : TemplateArg.pack_elements())
5661 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
5662 break;
5663 }
5664}
5665
5666/// Mark which template parameters can be deduced from a given
5667/// template argument list.
5668///
5669/// \param TemplateArgs the template argument list from which template
5670/// parameters will be deduced.
5671///
5672/// \param Used a bit vector whose elements will be set to \c true
5673/// to indicate when the corresponding template parameter will be
5674/// deduced.
5675void
5676Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5677 bool OnlyDeduced, unsigned Depth,
5678 llvm::SmallBitVector &Used) {
5679 // C++0x [temp.deduct.type]p9:
5680 // If the template argument list of P contains a pack expansion that is not
5681 // the last template argument, the entire template argument list is a
5682 // non-deduced context.
5683 if (OnlyDeduced &&
5684 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
5685 return;
5686
5687 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5688 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
5689 Depth, Used);
5690}
5691
5692/// Marks all of the template parameters that will be deduced by a
5693/// call to the given function template.
5694void Sema::MarkDeducedTemplateParameters(
5695 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5696 llvm::SmallBitVector &Deduced) {
5697 TemplateParameterList *TemplateParams
5698 = FunctionTemplate->getTemplateParameters();
5699 Deduced.clear();
5700 Deduced.resize(TemplateParams->size());
5701
5702 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5703 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
5704 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
5705 true, TemplateParams->getDepth(), Deduced);
5706}
5707
5708bool hasDeducibleTemplateParameters(Sema &S,
5709 FunctionTemplateDecl *FunctionTemplate,
5710 QualType T) {
5711 if (!T->isDependentType())
5712 return false;
5713
5714 TemplateParameterList *TemplateParams
5715 = FunctionTemplate->getTemplateParameters();
5716 llvm::SmallBitVector Deduced(TemplateParams->size());
5717 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5718 Deduced);
5719
5720 return Deduced.any();
5721}

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Availability.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LocInfoType.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NSAPI.h"
29#include "clang/AST/PrettyPrinter.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Basic/ExpressionTraits.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/TypoCorrection.h"
49#include "clang/Sema/Weak.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/SetVector.h"
53#include "llvm/ADT/SmallBitVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <tuple>
61#include <vector>
62
63namespace llvm {
64 class APSInt;
65 template <typename ValueT> struct DenseMapInfo;
66 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class SmallBitVector;
68 struct InlineAsmIdentifierInfo;
69}
70
71namespace clang {
72 class ADLResult;
73 class ASTConsumer;
74 class ASTContext;
75 class ASTMutationListener;
76 class ASTReader;
77 class ASTWriter;
78 class ArrayType;
79 class ParsedAttr;
80 class BindingDecl;
81 class BlockDecl;
82 class CapturedDecl;
83 class CXXBasePath;
84 class CXXBasePaths;
85 class CXXBindTemporaryExpr;
86 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
87 class CXXConstructorDecl;
88 class CXXConversionDecl;
89 class CXXDeleteExpr;
90 class CXXDestructorDecl;
91 class CXXFieldCollector;
92 class CXXMemberCallExpr;
93 class CXXMethodDecl;
94 class CXXScopeSpec;
95 class CXXTemporary;
96 class CXXTryStmt;
97 class CallExpr;
98 class ClassTemplateDecl;
99 class ClassTemplatePartialSpecializationDecl;
100 class ClassTemplateSpecializationDecl;
101 class VarTemplatePartialSpecializationDecl;
102 class CodeCompleteConsumer;
103 class CodeCompletionAllocator;
104 class CodeCompletionTUInfo;
105 class CodeCompletionResult;
106 class CoroutineBodyStmt;
107 class Decl;
108 class DeclAccessPair;
109 class DeclContext;
110 class DeclRefExpr;
111 class DeclaratorDecl;
112 class DeducedTemplateArgument;
113 class DependentDiagnostic;
114 class DesignatedInitExpr;
115 class Designation;
116 class EnableIfAttr;
117 class EnumConstantDecl;
118 class Expr;
119 class ExtVectorType;
120 class FormatAttr;
121 class FriendDecl;
122 class FunctionDecl;
123 class FunctionProtoType;
124 class FunctionTemplateDecl;
125 class ImplicitConversionSequence;
126 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitListExpr;
128 class InitializationKind;
129 class InitializationSequence;
130 class InitializedEntity;
131 class IntegerLiteral;
132 class LabelStmt;
133 class LambdaExpr;
134 class LangOptions;
135 class LocalInstantiationScope;
136 class LookupResult;
137 class MacroInfo;
138 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139 class ModuleLoader;
140 class MultiLevelTemplateArgumentList;
141 class NamedDecl;
142 class ObjCCategoryDecl;
143 class ObjCCategoryImplDecl;
144 class ObjCCompatibleAliasDecl;
145 class ObjCContainerDecl;
146 class ObjCImplDecl;
147 class ObjCImplementationDecl;
148 class ObjCInterfaceDecl;
149 class ObjCIvarDecl;
150 template <class T> class ObjCList;
151 class ObjCMessageExpr;
152 class ObjCMethodDecl;
153 class ObjCPropertyDecl;
154 class ObjCProtocolDecl;
155 class OMPThreadPrivateDecl;
156 class OMPRequiresDecl;
157 class OMPDeclareReductionDecl;
158 class OMPDeclareSimdDecl;
159 class OMPClause;
160 struct OMPVarListLocTy;
161 struct OverloadCandidate;
162 class OverloadCandidateSet;
163 class OverloadExpr;
164 class ParenListExpr;
165 class ParmVarDecl;
166 class Preprocessor;
167 class PseudoDestructorTypeStorage;
168 class PseudoObjectExpr;
169 class QualType;
170 class StandardConversionSequence;
171 class Stmt;
172 class StringLiteral;
173 class SwitchStmt;
174 class TemplateArgument;
175 class TemplateArgumentList;
176 class TemplateArgumentLoc;
177 class TemplateDecl;
178 class TemplateInstantiationCallback;
179 class TemplateParameterList;
180 class TemplatePartialOrderingContext;
181 class TemplateTemplateParmDecl;
182 class Token;
183 class TypeAliasDecl;
184 class TypedefDecl;
185 class TypedefNameDecl;
186 class TypeLoc;
187 class TypoCorrectionConsumer;
188 class UnqualifiedId;
189 class UnresolvedLookupExpr;
190 class UnresolvedMemberExpr;
191 class UnresolvedSetImpl;
192 class UnresolvedSetIterator;
193 class UsingDecl;
194 class UsingShadowDecl;
195 class ValueDecl;
196 class VarDecl;
197 class VarTemplateSpecializationDecl;
198 class VisibilityAttr;
199 class VisibleDeclConsumer;
200 class IndirectFieldDecl;
201 struct DeductionFailureInfo;
202 class TemplateSpecCandidateSet;
203
204namespace sema {
205 class AccessedEntity;
206 class BlockScopeInfo;
207 class Capture;
208 class CapturedRegionScopeInfo;
209 class CapturingScopeInfo;
210 class CompoundScopeInfo;
211 class DelayedDiagnostic;
212 class DelayedDiagnosticPool;
213 class FunctionScopeInfo;
214 class LambdaScopeInfo;
215 class PossiblyUnreachableDiag;
216 class SemaPPCallbacks;
217 class TemplateDeductionInfo;
218}
219
220namespace threadSafety {
221 class BeforeSet;
222 void threadSafetyCleanup(BeforeSet* Cache);
223}
224
225// FIXME: No way to easily map from TemplateTypeParmTypes to
226// TemplateTypeParmDecls, so we have this horrible PointerUnion.
227typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
228 SourceLocation> UnexpandedParameterPack;
229
230/// Describes whether we've seen any nullability information for the given
231/// file.
232struct FileNullability {
233 /// The first pointer declarator (of any pointer kind) in the file that does
234 /// not have a corresponding nullability annotation.
235 SourceLocation PointerLoc;
236
237 /// The end location for the first pointer declarator in the file. Used for
238 /// placing fix-its.
239 SourceLocation PointerEndLoc;
240
241 /// Which kind of pointer declarator we saw.
242 uint8_t PointerKind;
243
244 /// Whether we saw any type nullability annotations in the given file.
245 bool SawTypeNullability = false;
246};
247
248/// A mapping from file IDs to a record of whether we've seen nullability
249/// information in that file.
250class FileNullabilityMap {
251 /// A mapping from file IDs to the nullability information for each file ID.
252 llvm::DenseMap<FileID, FileNullability> Map;
253
254 /// A single-element cache based on the file ID.
255 struct {
256 FileID File;
257 FileNullability Nullability;
258 } Cache;
259
260public:
261 FileNullability &operator[](FileID file) {
262 // Check the single-element cache.
263 if (file == Cache.File)
264 return Cache.Nullability;
265
266 // It's not in the single-element cache; flush the cache if we have one.
267 if (!Cache.File.isInvalid()) {
268 Map[Cache.File] = Cache.Nullability;
269 }
270
271 // Pull this entry into the cache.
272 Cache.File = file;
273 Cache.Nullability = Map[file];
274 return Cache.Nullability;
275 }
276};
277
278/// Keeps track of expected type during expression parsing. The type is tied to
279/// a particular token, all functions that update or consume the type take a
280/// start location of the token they are looking at as a parameter. This allows
281/// to avoid updating the type on hot paths in the parser.
282class PreferredTypeBuilder {
283public:
284 PreferredTypeBuilder() = default;
285 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
286
287 void enterCondition(Sema &S, SourceLocation Tok);
288 void enterReturn(Sema &S, SourceLocation Tok);
289 void enterVariableInit(SourceLocation Tok, Decl *D);
290 /// Computing a type for the function argument may require running
291 /// overloading, so we postpone its computation until it is actually needed.
292 ///
293 /// Clients should be very careful when using this funciton, as it stores a
294 /// function_ref, clients should make sure all calls to get() with the same
295 /// location happen while function_ref is alive.
296 void enterFunctionArgument(SourceLocation Tok,
297 llvm::function_ref<QualType()> ComputeType);
298
299 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
300 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
301 SourceLocation OpLoc);
302 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
303 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
304 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
305 /// Handles all type casts, including C-style cast, C++ casts, etc.
306 void enterTypeCast(SourceLocation Tok, QualType CastType);
307
308 QualType get(SourceLocation Tok) const {
309 if (Tok != ExpectedLoc)
310 return QualType();
311 if (!Type.isNull())
312 return Type;
313 if (ComputeType)
314 return ComputeType();
315 return QualType();
316 }
317
318private:
319 /// Start position of a token for which we store expected type.
320 SourceLocation ExpectedLoc;
321 /// Expected type for a token starting at ExpectedLoc.
322 QualType Type;
323 /// A function to compute expected type at ExpectedLoc. It is only considered
324 /// if Type is null.
325 llvm::function_ref<QualType()> ComputeType;
326};
327
328/// Sema - This implements semantic analysis and AST building for C.
329class Sema {
330 Sema(const Sema &) = delete;
331 void operator=(const Sema &) = delete;
332
333 ///Source of additional semantic information.
334 ExternalSemaSource *ExternalSource;
335
336 ///Whether Sema has generated a multiplexer and has to delete it.
337 bool isMultiplexExternalSource;
338
339 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
340
341 bool isVisibleSlow(const NamedDecl *D);
342
343 /// Determine whether two declarations should be linked together, given that
344 /// the old declaration might not be visible and the new declaration might
345 /// not have external linkage.
346 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
347 const NamedDecl *New) {
348 if (isVisible(Old))
349 return true;
350 // See comment in below overload for why it's safe to compute the linkage
351 // of the new declaration here.
352 if (New->isExternallyDeclarable()) {
353 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 354, __PRETTY_FUNCTION__))
354 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 354, __PRETTY_FUNCTION__))
;
355 return true;
356 }
357 return false;
358 }
359 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
360
361 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
362 QualType ResultTy,
363 ArrayRef<QualType> Args);
364
365public:
366 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
367 typedef OpaquePtr<TemplateName> TemplateTy;
368 typedef OpaquePtr<QualType> TypeTy;
369
370 OpenCLOptions OpenCLFeatures;
371 FPOptions FPFeatures;
372
373 const LangOptions &LangOpts;
374 Preprocessor &PP;
375 ASTContext &Context;
376 ASTConsumer &Consumer;
377 DiagnosticsEngine &Diags;
378 SourceManager &SourceMgr;
379
380 /// Flag indicating whether or not to collect detailed statistics.
381 bool CollectStats;
382
383 /// Code-completion consumer.
384 CodeCompleteConsumer *CodeCompleter;
385
386 /// CurContext - This is the current declaration context of parsing.
387 DeclContext *CurContext;
388
389 /// Generally null except when we temporarily switch decl contexts,
390 /// like in \see ActOnObjCTemporaryExitContainerContext.
391 DeclContext *OriginalLexicalContext;
392
393 /// VAListTagName - The declaration name corresponding to __va_list_tag.
394 /// This is used as part of a hack to omit that class from ADL results.
395 DeclarationName VAListTagName;
396
397 bool MSStructPragmaOn; // True when \#pragma ms_struct on
398
399 /// Controls member pointer representation format under the MS ABI.
400 LangOptions::PragmaMSPointersToMembersKind
401 MSPointerToMemberRepresentationMethod;
402
403 /// Stack of active SEH __finally scopes. Can be empty.
404 SmallVector<Scope*, 2> CurrentSEHFinally;
405
406 /// Source location for newly created implicit MSInheritanceAttrs
407 SourceLocation ImplicitMSInheritanceAttrLoc;
408
409 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
410 /// `TransformTypos` in order to keep track of any TypoExprs that are created
411 /// recursively during typo correction and wipe them away if the correction
412 /// fails.
413 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
414
415 /// pragma clang section kind
416 enum PragmaClangSectionKind {
417 PCSK_Invalid = 0,
418 PCSK_BSS = 1,
419 PCSK_Data = 2,
420 PCSK_Rodata = 3,
421 PCSK_Text = 4
422 };
423
424 enum PragmaClangSectionAction {
425 PCSA_Set = 0,
426 PCSA_Clear = 1
427 };
428
429 struct PragmaClangSection {
430 std::string SectionName;
431 bool Valid = false;
432 SourceLocation PragmaLocation;
433
434 void Act(SourceLocation PragmaLocation,
435 PragmaClangSectionAction Action,
436 StringLiteral* Name);
437 };
438
439 PragmaClangSection PragmaClangBSSSection;
440 PragmaClangSection PragmaClangDataSection;
441 PragmaClangSection PragmaClangRodataSection;
442 PragmaClangSection PragmaClangTextSection;
443
444 enum PragmaMsStackAction {
445 PSK_Reset = 0x0, // #pragma ()
446 PSK_Set = 0x1, // #pragma (value)
447 PSK_Push = 0x2, // #pragma (push[, id])
448 PSK_Pop = 0x4, // #pragma (pop[, id])
449 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
450 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
451 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
452 };
453
454 template<typename ValueType>
455 struct PragmaStack {
456 struct Slot {
457 llvm::StringRef StackSlotLabel;
458 ValueType Value;
459 SourceLocation PragmaLocation;
460 SourceLocation PragmaPushLocation;
461 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
462 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
463 : StackSlotLabel(StackSlotLabel), Value(Value),
464 PragmaLocation(PragmaLocation),
465 PragmaPushLocation(PragmaPushLocation) {}
466 };
467 void Act(SourceLocation PragmaLocation,
468 PragmaMsStackAction Action,
469 llvm::StringRef StackSlotLabel,
470 ValueType Value);
471
472 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
473 // method body to restore the stacks on exit, so it works like this:
474 //
475 // struct S {
476 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
477 // void Method {}
478 // #pragma <name>(pop, InternalPragmaSlot)
479 // };
480 //
481 // It works even with #pragma vtordisp, although MSVC doesn't support
482 // #pragma vtordisp(push [, id], n)
483 // syntax.
484 //
485 // Push / pop a named sentinel slot.
486 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
487 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 488, __PRETTY_FUNCTION__))
488 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 488, __PRETTY_FUNCTION__))
;
489 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
490 }
491
492 // Constructors.
493 explicit PragmaStack(const ValueType &Default)
494 : DefaultValue(Default), CurrentValue(Default) {}
495
496 bool hasValue() const { return CurrentValue != DefaultValue; }
497
498 SmallVector<Slot, 2> Stack;
499 ValueType DefaultValue; // Value used for PSK_Reset action.
500 ValueType CurrentValue;
501 SourceLocation CurrentPragmaLocation;
502 };
503 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
504 // we shouldn't do so if they're in a module).
505
506 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
507 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
508 ///
509 /// 0: Suppress all vtordisps
510 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
511 /// structors
512 /// 2: Always insert vtordisps to support RTTI on partially constructed
513 /// objects
514 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
515 // #pragma pack.
516 // Sentinel to represent when the stack is set to mac68k alignment.
517 static const unsigned kMac68kAlignmentSentinel = ~0U;
518 PragmaStack<unsigned> PackStack;
519 // The current #pragma pack values and locations at each #include.
520 struct PackIncludeState {
521 unsigned CurrentValue;
522 SourceLocation CurrentPragmaLocation;
523 bool HasNonDefaultValue, ShouldWarnOnInclude;
524 };
525 SmallVector<PackIncludeState, 8> PackIncludeStack;
526 // Segment #pragmas.
527 PragmaStack<StringLiteral *> DataSegStack;
528 PragmaStack<StringLiteral *> BSSSegStack;
529 PragmaStack<StringLiteral *> ConstSegStack;
530 PragmaStack<StringLiteral *> CodeSegStack;
531
532 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
533 // Actions should be performed only if we enter / exit a C++ method body.
534 class PragmaStackSentinelRAII {
535 public:
536 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
537 ~PragmaStackSentinelRAII();
538
539 private:
540 Sema &S;
541 StringRef SlotLabel;
542 bool ShouldAct;
543 };
544
545 /// A mapping that describes the nullability we've seen in each header file.
546 FileNullabilityMap NullabilityMap;
547
548 /// Last section used with #pragma init_seg.
549 StringLiteral *CurInitSeg;
550 SourceLocation CurInitSegLoc;
551
552 /// VisContext - Manages the stack for \#pragma GCC visibility.
553 void *VisContext; // Really a "PragmaVisStack*"
554
555 /// This an attribute introduced by \#pragma clang attribute.
556 struct PragmaAttributeEntry {
557 SourceLocation Loc;
558 ParsedAttr *Attribute;
559 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
560 bool IsUsed;
561 };
562
563 /// A push'd group of PragmaAttributeEntries.
564 struct PragmaAttributeGroup {
565 /// The location of the push attribute.
566 SourceLocation Loc;
567 /// The namespace of this push group.
568 const IdentifierInfo *Namespace;
569 SmallVector<PragmaAttributeEntry, 2> Entries;
570 };
571
572 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
573
574 /// The declaration that is currently receiving an attribute from the
575 /// #pragma attribute stack.
576 const Decl *PragmaAttributeCurrentTargetDecl;
577
578 /// This represents the last location of a "#pragma clang optimize off"
579 /// directive if such a directive has not been closed by an "on" yet. If
580 /// optimizations are currently "on", this is set to an invalid location.
581 SourceLocation OptimizeOffPragmaLocation;
582
583 /// Flag indicating if Sema is building a recovery call expression.
584 ///
585 /// This flag is used to avoid building recovery call expressions
586 /// if Sema is already doing so, which would cause infinite recursions.
587 bool IsBuildingRecoveryCallExpr;
588
589 /// Used to control the generation of ExprWithCleanups.
590 CleanupInfo Cleanup;
591
592 /// ExprCleanupObjects - This is the stack of objects requiring
593 /// cleanup that are created by the current full expression. The
594 /// element type here is ExprWithCleanups::Object.
595 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
596
597 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
598 /// to a variable (constant) that may or may not be odr-used in this Expr, and
599 /// we won't know until all lvalue-to-rvalue and discarded value conversions
600 /// have been applied to all subexpressions of the enclosing full expression.
601 /// This is cleared at the end of each full expression.
602 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
603 MaybeODRUseExprSet MaybeODRUseExprs;
604
605 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
606
607 /// Stack containing information about each of the nested
608 /// function, block, and method scopes that are currently active.
609 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
610
611 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
612 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
613 ExtVectorDeclsType;
614
615 /// ExtVectorDecls - This is a list all the extended vector types. This allows
616 /// us to associate a raw vector type with one of the ext_vector type names.
617 /// This is only necessary for issuing pretty diagnostics.
618 ExtVectorDeclsType ExtVectorDecls;
619
620 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
621 std::unique_ptr<CXXFieldCollector> FieldCollector;
622
623 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
624
625 /// Set containing all declared private fields that are not used.
626 NamedDeclSetType UnusedPrivateFields;
627
628 /// Set containing all typedefs that are likely unused.
629 llvm::SmallSetVector<const TypedefNameDecl *, 4>
630 UnusedLocalTypedefNameCandidates;
631
632 /// Delete-expressions to be analyzed at the end of translation unit
633 ///
634 /// This list contains class members, and locations of delete-expressions
635 /// that could not be proven as to whether they mismatch with new-expression
636 /// used in initializer of the field.
637 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
638 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
639 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
640
641 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
642
643 /// PureVirtualClassDiagSet - a set of class declarations which we have
644 /// emitted a list of pure virtual functions. Used to prevent emitting the
645 /// same list more than once.
646 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
647
648 /// ParsingInitForAutoVars - a set of declarations with auto types for which
649 /// we are currently parsing the initializer.
650 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
651
652 /// Look for a locally scoped extern "C" declaration by the given name.
653 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
654
655 typedef LazyVector<VarDecl *, ExternalSemaSource,
656 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
657 TentativeDefinitionsType;
658
659 /// All the tentative definitions encountered in the TU.
660 TentativeDefinitionsType TentativeDefinitions;
661
662 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
663 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
664 UnusedFileScopedDeclsType;
665
666 /// The set of file scoped decls seen so far that have not been used
667 /// and must warn if not used. Only contains the first declaration.
668 UnusedFileScopedDeclsType UnusedFileScopedDecls;
669
670 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
671 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
672 DelegatingCtorDeclsType;
673
674 /// All the delegating constructors seen so far in the file, used for
675 /// cycle detection at the end of the TU.
676 DelegatingCtorDeclsType DelegatingCtorDecls;
677
678 /// All the overriding functions seen during a class definition
679 /// that had their exception spec checks delayed, plus the overridden
680 /// function.
681 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
682 DelayedOverridingExceptionSpecChecks;
683
684 /// All the function redeclarations seen during a class definition that had
685 /// their exception spec checks delayed, plus the prior declaration they
686 /// should be checked against. Except during error recovery, the new decl
687 /// should always be a friend declaration, as that's the only valid way to
688 /// redeclare a special member before its class is complete.
689 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
690 DelayedEquivalentExceptionSpecChecks;
691
692 typedef llvm::MapVector<const FunctionDecl *,
693 std::unique_ptr<LateParsedTemplate>>
694 LateParsedTemplateMapT;
695 LateParsedTemplateMapT LateParsedTemplateMap;
696
697 /// Callback to the parser to parse templated functions when needed.
698 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
699 typedef void LateTemplateParserCleanupCB(void *P);
700 LateTemplateParserCB *LateTemplateParser;
701 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
702 void *OpaqueParser;
703
704 void SetLateTemplateParser(LateTemplateParserCB *LTP,
705 LateTemplateParserCleanupCB *LTPCleanup,
706 void *P) {
707 LateTemplateParser = LTP;
708 LateTemplateParserCleanup = LTPCleanup;
709 OpaqueParser = P;
710 }
711
712 class DelayedDiagnostics;
713
714 class DelayedDiagnosticsState {
715 sema::DelayedDiagnosticPool *SavedPool;
716 friend class Sema::DelayedDiagnostics;
717 };
718 typedef DelayedDiagnosticsState ParsingDeclState;
719 typedef DelayedDiagnosticsState ProcessingContextState;
720
721 /// A class which encapsulates the logic for delaying diagnostics
722 /// during parsing and other processing.
723 class DelayedDiagnostics {
724 /// The current pool of diagnostics into which delayed
725 /// diagnostics should go.
726 sema::DelayedDiagnosticPool *CurPool;
727
728 public:
729 DelayedDiagnostics() : CurPool(nullptr) {}
730
731 /// Adds a delayed diagnostic.
732 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
733
734 /// Determines whether diagnostics should be delayed.
735 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
736
737 /// Returns the current delayed-diagnostics pool.
738 sema::DelayedDiagnosticPool *getCurrentPool() const {
739 return CurPool;
740 }
741
742 /// Enter a new scope. Access and deprecation diagnostics will be
743 /// collected in this pool.
744 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
745 DelayedDiagnosticsState state;
746 state.SavedPool = CurPool;
747 CurPool = &pool;
748 return state;
749 }
750
751 /// Leave a delayed-diagnostic state that was previously pushed.
752 /// Do not emit any of the diagnostics. This is performed as part
753 /// of the bookkeeping of popping a pool "properly".
754 void popWithoutEmitting(DelayedDiagnosticsState state) {
755 CurPool = state.SavedPool;
756 }
757
758 /// Enter a new scope where access and deprecation diagnostics are
759 /// not delayed.
760 DelayedDiagnosticsState pushUndelayed() {
761 DelayedDiagnosticsState state;
762 state.SavedPool = CurPool;
763 CurPool = nullptr;
764 return state;
765 }
766
767 /// Undo a previous pushUndelayed().
768 void popUndelayed(DelayedDiagnosticsState state) {
769 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 769, __PRETTY_FUNCTION__))
;
770 CurPool = state.SavedPool;
771 }
772 } DelayedDiagnostics;
773
774 /// A RAII object to temporarily push a declaration context.
775 class ContextRAII {
776 private:
777 Sema &S;
778 DeclContext *SavedContext;
779 ProcessingContextState SavedContextState;
780 QualType SavedCXXThisTypeOverride;
781
782 public:
783 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
784 : S(S), SavedContext(S.CurContext),
785 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
786 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
787 {
788 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 788, __PRETTY_FUNCTION__))
;
789 S.CurContext = ContextToPush;
790 if (NewThisContext)
791 S.CXXThisTypeOverride = QualType();
792 }
793
794 void pop() {
795 if (!SavedContext) return;
796 S.CurContext = SavedContext;
797 S.DelayedDiagnostics.popUndelayed(SavedContextState);
798 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
799 SavedContext = nullptr;
800 }
801
802 ~ContextRAII() {
803 pop();
804 }
805 };
806
807 /// Used to change context to isConstantEvaluated without pushing a heavy
808 /// ExpressionEvaluationContextRecord object.
809 bool isConstantEvaluatedOverride;
810
811 bool isConstantEvaluated() {
812 return ExprEvalContexts.back().isConstantEvaluated() ||
813 isConstantEvaluatedOverride;
814 }
815
816 /// RAII object to handle the state changes required to synthesize
817 /// a function body.
818 class SynthesizedFunctionScope {
819 Sema &S;
820 Sema::ContextRAII SavedContext;
821 bool PushedCodeSynthesisContext = false;
822
823 public:
824 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
825 : S(S), SavedContext(S, DC) {
826 S.PushFunctionScope();
827 S.PushExpressionEvaluationContext(
828 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
829 if (auto *FD = dyn_cast<FunctionDecl>(DC))
830 FD->setWillHaveBody(true);
831 else
832 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 832, __PRETTY_FUNCTION__))
;
833 }
834
835 void addContextNote(SourceLocation UseLoc) {
836 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 836, __PRETTY_FUNCTION__))
;
837
838 Sema::CodeSynthesisContext Ctx;
839 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
840 Ctx.PointOfInstantiation = UseLoc;
841 Ctx.Entity = cast<Decl>(S.CurContext);
842 S.pushCodeSynthesisContext(Ctx);
843
844 PushedCodeSynthesisContext = true;
845 }
846
847 ~SynthesizedFunctionScope() {
848 if (PushedCodeSynthesisContext)
849 S.popCodeSynthesisContext();
850 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
851 FD->setWillHaveBody(false);
852 S.PopExpressionEvaluationContext();
853 S.PopFunctionScopeInfo();
854 }
855 };
856
857 /// WeakUndeclaredIdentifiers - Identifiers contained in
858 /// \#pragma weak before declared. rare. may alias another
859 /// identifier, declared or undeclared
860 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
861
862 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
863 /// \#pragma redefine_extname before declared. Used in Solaris system headers
864 /// to define functions that occur in multiple standards to call the version
865 /// in the currently selected standard.
866 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
867
868
869 /// Load weak undeclared identifiers from the external source.
870 void LoadExternalWeakUndeclaredIdentifiers();
871
872 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
873 /// \#pragma weak during processing of other Decls.
874 /// I couldn't figure out a clean way to generate these in-line, so
875 /// we store them here and handle separately -- which is a hack.
876 /// It would be best to refactor this.
877 SmallVector<Decl*,2> WeakTopLevelDecl;
878
879 IdentifierResolver IdResolver;
880
881 /// Translation Unit Scope - useful to Objective-C actions that need
882 /// to lookup file scope declarations in the "ordinary" C decl namespace.
883 /// For example, user-defined classes, built-in "id" type, etc.
884 Scope *TUScope;
885
886 /// The C++ "std" namespace, where the standard library resides.
887 LazyDeclPtr StdNamespace;
888
889 /// The C++ "std::bad_alloc" class, which is defined by the C++
890 /// standard library.
891 LazyDeclPtr StdBadAlloc;
892
893 /// The C++ "std::align_val_t" enum class, which is defined by the C++
894 /// standard library.
895 LazyDeclPtr StdAlignValT;
896
897 /// The C++ "std::experimental" namespace, where the experimental parts
898 /// of the standard library resides.
899 NamespaceDecl *StdExperimentalNamespaceCache;
900
901 /// The C++ "std::initializer_list" template, which is defined in
902 /// \<initializer_list>.
903 ClassTemplateDecl *StdInitializerList;
904
905 /// The C++ "std::coroutine_traits" template, which is defined in
906 /// \<coroutine_traits>
907 ClassTemplateDecl *StdCoroutineTraitsCache;
908
909 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
910 RecordDecl *CXXTypeInfoDecl;
911
912 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
913 RecordDecl *MSVCGuidDecl;
914
915 /// Caches identifiers/selectors for NSFoundation APIs.
916 std::unique_ptr<NSAPI> NSAPIObj;
917
918 /// The declaration of the Objective-C NSNumber class.
919 ObjCInterfaceDecl *NSNumberDecl;
920
921 /// The declaration of the Objective-C NSValue class.
922 ObjCInterfaceDecl *NSValueDecl;
923
924 /// Pointer to NSNumber type (NSNumber *).
925 QualType NSNumberPointer;
926
927 /// Pointer to NSValue type (NSValue *).
928 QualType NSValuePointer;
929
930 /// The Objective-C NSNumber methods used to create NSNumber literals.
931 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
932
933 /// The declaration of the Objective-C NSString class.
934 ObjCInterfaceDecl *NSStringDecl;
935
936 /// Pointer to NSString type (NSString *).
937 QualType NSStringPointer;
938
939 /// The declaration of the stringWithUTF8String: method.
940 ObjCMethodDecl *StringWithUTF8StringMethod;
941
942 /// The declaration of the valueWithBytes:objCType: method.
943 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
944
945 /// The declaration of the Objective-C NSArray class.
946 ObjCInterfaceDecl *NSArrayDecl;
947
948 /// The declaration of the arrayWithObjects:count: method.
949 ObjCMethodDecl *ArrayWithObjectsMethod;
950
951 /// The declaration of the Objective-C NSDictionary class.
952 ObjCInterfaceDecl *NSDictionaryDecl;
953
954 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
955 ObjCMethodDecl *DictionaryWithObjectsMethod;
956
957 /// id<NSCopying> type.
958 QualType QIDNSCopying;
959
960 /// will hold 'respondsToSelector:'
961 Selector RespondsToSelectorSel;
962
963 /// A flag to remember whether the implicit forms of operator new and delete
964 /// have been declared.
965 bool GlobalNewDeleteDeclared;
966
967 /// A flag to indicate that we're in a context that permits abstract
968 /// references to fields. This is really a
969 bool AllowAbstractFieldReference;
970
971 /// Describes how the expressions currently being parsed are
972 /// evaluated at run-time, if at all.
973 enum class ExpressionEvaluationContext {
974 /// The current expression and its subexpressions occur within an
975 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
976 /// \c sizeof, where the type of the expression may be significant but
977 /// no code will be generated to evaluate the value of the expression at
978 /// run time.
979 Unevaluated,
980
981 /// The current expression occurs within a braced-init-list within
982 /// an unevaluated operand. This is mostly like a regular unevaluated
983 /// context, except that we still instantiate constexpr functions that are
984 /// referenced here so that we can perform narrowing checks correctly.
985 UnevaluatedList,
986
987 /// The current expression occurs within a discarded statement.
988 /// This behaves largely similarly to an unevaluated operand in preventing
989 /// definitions from being required, but not in other ways.
990 DiscardedStatement,
991
992 /// The current expression occurs within an unevaluated
993 /// operand that unconditionally permits abstract references to
994 /// fields, such as a SIZE operator in MS-style inline assembly.
995 UnevaluatedAbstract,
996
997 /// The current context is "potentially evaluated" in C++11 terms,
998 /// but the expression is evaluated at compile-time (like the values of
999 /// cases in a switch statement).
1000 ConstantEvaluated,
1001
1002 /// The current expression is potentially evaluated at run time,
1003 /// which means that code may be generated to evaluate the value of the
1004 /// expression at run time.
1005 PotentiallyEvaluated,
1006
1007 /// The current expression is potentially evaluated, but any
1008 /// declarations referenced inside that expression are only used if
1009 /// in fact the current expression is used.
1010 ///
1011 /// This value is used when parsing default function arguments, for which
1012 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1013 /// through varargs) but do not want to mark declarations as "referenced"
1014 /// until the default argument is used.
1015 PotentiallyEvaluatedIfUsed
1016 };
1017
1018 /// Data structure used to record current or nested
1019 /// expression evaluation contexts.
1020 struct ExpressionEvaluationContextRecord {
1021 /// The expression evaluation context.
1022 ExpressionEvaluationContext Context;
1023
1024 /// Whether the enclosing context needed a cleanup.
1025 CleanupInfo ParentCleanup;
1026
1027 /// Whether we are in a decltype expression.
1028 bool IsDecltype;
1029
1030 /// The number of active cleanup objects when we entered
1031 /// this expression evaluation context.
1032 unsigned NumCleanupObjects;
1033
1034 /// The number of typos encountered during this expression evaluation
1035 /// context (i.e. the number of TypoExprs created).
1036 unsigned NumTypos;
1037
1038 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1039
1040 /// The lambdas that are present within this context, if it
1041 /// is indeed an unevaluated context.
1042 SmallVector<LambdaExpr *, 2> Lambdas;
1043
1044 /// The declaration that provides context for lambda expressions
1045 /// and block literals if the normal declaration context does not
1046 /// suffice, e.g., in a default function argument.
1047 Decl *ManglingContextDecl;
1048
1049 /// If we are processing a decltype type, a set of call expressions
1050 /// for which we have deferred checking the completeness of the return type.
1051 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1052
1053 /// If we are processing a decltype type, a set of temporary binding
1054 /// expressions for which we have deferred checking the destructor.
1055 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1056
1057 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1058
1059 /// Expressions appearing as the LHS of a volatile assignment in this
1060 /// context. We produce a warning for these when popping the context if
1061 /// they are not discarded-value expressions nor unevaluated operands.
1062 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1063
1064 /// \brief Describes whether we are in an expression constext which we have
1065 /// to handle differently.
1066 enum ExpressionKind {
1067 EK_Decltype, EK_TemplateArgument, EK_Other
1068 } ExprContext;
1069
1070 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1071 unsigned NumCleanupObjects,
1072 CleanupInfo ParentCleanup,
1073 Decl *ManglingContextDecl,
1074 ExpressionKind ExprContext)
1075 : Context(Context), ParentCleanup(ParentCleanup),
1076 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1077 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1078
1079 bool isUnevaluated() const {
1080 return Context == ExpressionEvaluationContext::Unevaluated ||
1081 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1082 Context == ExpressionEvaluationContext::UnevaluatedList;
1083 }
1084 bool isConstantEvaluated() const {
1085 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1086 }
1087 };
1088
1089 /// A stack of expression evaluation contexts.
1090 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1091
1092 /// Emit a warning for all pending noderef expressions that we recorded.
1093 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1094
1095 /// Compute the mangling number context for a lambda expression or
1096 /// block literal. Also return the extra mangling decl if any.
1097 ///
1098 /// \param DC - The DeclContext containing the lambda expression or
1099 /// block literal.
1100 std::tuple<MangleNumberingContext *, Decl *>
1101 getCurrentMangleNumberContext(const DeclContext *DC);
1102
1103
1104 /// SpecialMemberOverloadResult - The overloading result for a special member
1105 /// function.
1106 ///
1107 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1108 /// integer are used to determine whether overload resolution succeeded.
1109 class SpecialMemberOverloadResult {
1110 public:
1111 enum Kind {
1112 NoMemberOrDeleted,
1113 Ambiguous,
1114 Success
1115 };
1116
1117 private:
1118 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1119
1120 public:
1121 SpecialMemberOverloadResult() : Pair() {}
1122 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1123 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1124
1125 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1126 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1127
1128 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1129 void setKind(Kind K) { Pair.setInt(K); }
1130 };
1131
1132 class SpecialMemberOverloadResultEntry
1133 : public llvm::FastFoldingSetNode,
1134 public SpecialMemberOverloadResult {
1135 public:
1136 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1137 : FastFoldingSetNode(ID)
1138 {}
1139 };
1140
1141 /// A cache of special member function overload resolution results
1142 /// for C++ records.
1143 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1144
1145 /// A cache of the flags available in enumerations with the flag_bits
1146 /// attribute.
1147 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1148
1149 /// The kind of translation unit we are processing.
1150 ///
1151 /// When we're processing a complete translation unit, Sema will perform
1152 /// end-of-translation-unit semantic tasks (such as creating
1153 /// initializers for tentative definitions in C) once parsing has
1154 /// completed. Modules and precompiled headers perform different kinds of
1155 /// checks.
1156 TranslationUnitKind TUKind;
1157
1158 llvm::BumpPtrAllocator BumpAlloc;
1159
1160 /// The number of SFINAE diagnostics that have been trapped.
1161 unsigned NumSFINAEErrors;
1162
1163 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1164 UnparsedDefaultArgInstantiationsMap;
1165
1166 /// A mapping from parameters with unparsed default arguments to the
1167 /// set of instantiations of each parameter.
1168 ///
1169 /// This mapping is a temporary data structure used when parsing
1170 /// nested class templates or nested classes of class templates,
1171 /// where we might end up instantiating an inner class before the
1172 /// default arguments of its methods have been parsed.
1173 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1174
1175 // Contains the locations of the beginning of unparsed default
1176 // argument locations.
1177 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1178
1179 /// UndefinedInternals - all the used, undefined objects which require a
1180 /// definition in this translation unit.
1181 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1182
1183 /// Determine if VD, which must be a variable or function, is an external
1184 /// symbol that nonetheless can't be referenced from outside this translation
1185 /// unit because its type has no linkage and it's not extern "C".
1186 bool isExternalWithNoLinkageType(ValueDecl *VD);
1187
1188 /// Obtain a sorted list of functions that are undefined but ODR-used.
1189 void getUndefinedButUsed(
1190 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1191
1192 /// Retrieves list of suspicious delete-expressions that will be checked at
1193 /// the end of translation unit.
1194 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1195 getMismatchingDeleteExpressions() const;
1196
1197 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1198 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1199
1200 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1201 /// We need to maintain a list, since selectors can have differing signatures
1202 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1203 /// of selectors are "overloaded").
1204 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1205 /// methods inside categories with a particular selector.
1206 GlobalMethodPool MethodPool;
1207
1208 /// Method selectors used in a \@selector expression. Used for implementation
1209 /// of -Wselector.
1210 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1211
1212 /// List of SourceLocations where 'self' is implicitly retained inside a
1213 /// block.
1214 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1215 ImplicitlyRetainedSelfLocs;
1216
1217 /// Kinds of C++ special members.
1218 enum CXXSpecialMember {
1219 CXXDefaultConstructor,
1220 CXXCopyConstructor,
1221 CXXMoveConstructor,
1222 CXXCopyAssignment,
1223 CXXMoveAssignment,
1224 CXXDestructor,
1225 CXXInvalid
1226 };
1227
1228 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1229 SpecialMemberDecl;
1230
1231 /// The C++ special members which we are currently in the process of
1232 /// declaring. If this process recursively triggers the declaration of the
1233 /// same special member, we should act as if it is not yet declared.
1234 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1235
1236 /// The function definitions which were renamed as part of typo-correction
1237 /// to match their respective declarations. We want to keep track of them
1238 /// to ensure that we don't emit a "redefinition" error if we encounter a
1239 /// correctly named definition after the renamed definition.
1240 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1241
1242 /// Stack of types that correspond to the parameter entities that are
1243 /// currently being copy-initialized. Can be empty.
1244 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1245
1246 void ReadMethodPool(Selector Sel);
1247 void updateOutOfDateSelector(Selector Sel);
1248
1249 /// Private Helper predicate to check for 'self'.
1250 bool isSelfExpr(Expr *RExpr);
1251 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1252
1253 /// Cause the active diagnostic on the DiagosticsEngine to be
1254 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1255 /// should not be used elsewhere.
1256 void EmitCurrentDiagnostic(unsigned DiagID);
1257
1258 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1259 /// statements.
1260 class FPContractStateRAII {
1261 public:
1262 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1263 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1264
1265 private:
1266 Sema& S;
1267 FPOptions OldFPFeaturesState;
1268 };
1269
1270 void addImplicitTypedef(StringRef Name, QualType T);
1271
1272 bool WarnedStackExhausted = false;
1273
1274public:
1275 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1276 TranslationUnitKind TUKind = TU_Complete,
1277 CodeCompleteConsumer *CompletionConsumer = nullptr);
1278 ~Sema();
1279
1280 /// Perform initialization that occurs after the parser has been
1281 /// initialized but before it parses anything.
1282 void Initialize();
1283
1284 const LangOptions &getLangOpts() const { return LangOpts; }
1285 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1286 FPOptions &getFPOptions() { return FPFeatures; }
1287
1288 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1289 SourceManager &getSourceManager() const { return SourceMgr; }
1290 Preprocessor &getPreprocessor() const { return PP; }
1291 ASTContext &getASTContext() const { return Context; }
1292 ASTConsumer &getASTConsumer() const { return Consumer; }
1293 ASTMutationListener *getASTMutationListener() const;
1294 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1295
1296 ///Registers an external source. If an external source already exists,
1297 /// creates a multiplex external source and appends to it.
1298 ///
1299 ///\param[in] E - A non-null external sema source.
1300 ///
1301 void addExternalSource(ExternalSemaSource *E);
1302
1303 void PrintStats() const;
1304
1305 /// Warn that the stack is nearly exhausted.
1306 void warnStackExhausted(SourceLocation Loc);
1307
1308 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1309 /// guaranteed). Produces a warning if we're low on stack space and allocates
1310 /// more in that case. Use this in code that may recurse deeply (for example,
1311 /// in template instantiation) to avoid stack overflow.
1312 void runWithSufficientStackSpace(SourceLocation Loc,
1313 llvm::function_ref<void()> Fn);
1314
1315 /// Helper class that creates diagnostics with optional
1316 /// template instantiation stacks.
1317 ///
1318 /// This class provides a wrapper around the basic DiagnosticBuilder
1319 /// class that emits diagnostics. SemaDiagnosticBuilder is
1320 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1321 /// does) and, if the diagnostic comes from inside a template
1322 /// instantiation, printing the template instantiation stack as
1323 /// well.
1324 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1325 Sema &SemaRef;
1326 unsigned DiagID;
1327
1328 public:
1329 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1330 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1331
1332 // This is a cunning lie. DiagnosticBuilder actually performs move
1333 // construction in its copy constructor (but due to varied uses, it's not
1334 // possible to conveniently express this as actual move construction). So
1335 // the default copy ctor here is fine, because the base class disables the
1336 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1337 // in that case anwyay.
1338 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1339
1340 ~SemaDiagnosticBuilder() {
1341 // If we aren't active, there is nothing to do.
1342 if (!isActive()) return;
1343
1344 // Otherwise, we need to emit the diagnostic. First flush the underlying
1345 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1346 // won't emit the diagnostic in its own destructor.
1347 //
1348 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1349 // do its own needless checks to see if the diagnostic needs to be
1350 // emitted. However, because we take care to ensure that the builder
1351 // objects never escape, a sufficiently smart compiler will be able to
1352 // eliminate that code.
1353 FlushCounts();
1354 Clear();
1355
1356 // Dispatch to Sema to emit the diagnostic.
1357 SemaRef.EmitCurrentDiagnostic(DiagID);
1358 }
1359
1360 /// Teach operator<< to produce an object of the correct type.
1361 template<typename T>
1362 friend const SemaDiagnosticBuilder &operator<<(
1363 const SemaDiagnosticBuilder &Diag, const T &Value) {
1364 const DiagnosticBuilder &BaseDiag = Diag;
1365 BaseDiag << Value;
1366 return Diag;
1367 }
1368 };
1369
1370 /// Emit a diagnostic.
1371 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1372 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1373 return SemaDiagnosticBuilder(DB, *this, DiagID);
1374 }
1375
1376 /// Emit a partial diagnostic.
1377 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1378
1379 /// Build a partial diagnostic.
1380 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1381
1382 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1383
1384 /// Get a string to suggest for zero-initialization of a type.
1385 std::string
1386 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1387 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1388
1389 /// Calls \c Lexer::getLocForEndOfToken()
1390 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1391
1392 /// Retrieve the module loader associated with the preprocessor.
1393 ModuleLoader &getModuleLoader() const;
1394
1395 void emitAndClearUnusedLocalTypedefWarnings();
1396
1397 enum TUFragmentKind {
1398 /// The global module fragment, between 'module;' and a module-declaration.
1399 Global,
1400 /// A normal translation unit fragment. For a non-module unit, this is the
1401 /// entire translation unit. Otherwise, it runs from the module-declaration
1402 /// to the private-module-fragment (if any) or the end of the TU (if not).
1403 Normal,
1404 /// The private module fragment, between 'module :private;' and the end of
1405 /// the translation unit.
1406 Private
1407 };
1408
1409 void ActOnStartOfTranslationUnit();
1410 void ActOnEndOfTranslationUnit();
1411 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1412
1413 void CheckDelegatingCtorCycles();
1414
1415 Scope *getScopeForContext(DeclContext *Ctx);
1416
1417 void PushFunctionScope();
1418 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1419 sema::LambdaScopeInfo *PushLambdaScope();
1420
1421 /// This is used to inform Sema what the current TemplateParameterDepth
1422 /// is during Parsing. Currently it is used to pass on the depth
1423 /// when parsing generic lambda 'auto' parameters.
1424 void RecordParsingTemplateParameterDepth(unsigned Depth);
1425
1426 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1427 RecordDecl *RD, CapturedRegionKind K,
1428 unsigned OpenMPCaptureLevel = 0);
1429
1430 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1431 /// time after they've been popped.
1432 class PoppedFunctionScopeDeleter {
1433 Sema *Self;
1434
1435 public:
1436 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1437 void operator()(sema::FunctionScopeInfo *Scope) const;
1438 };
1439
1440 using PoppedFunctionScopePtr =
1441 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1442
1443 PoppedFunctionScopePtr
1444 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1445 const Decl *D = nullptr,
1446 QualType BlockType = QualType());
1447
1448 sema::FunctionScopeInfo *getCurFunction() const {
1449 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1450 }
1451
1452 sema::FunctionScopeInfo *getEnclosingFunction() const;
1453
1454 void setFunctionHasBranchIntoScope();
1455 void setFunctionHasBranchProtectedScope();
1456 void setFunctionHasIndirectGoto();
1457
1458 void PushCompoundScope(bool IsStmtExpr);
1459 void PopCompoundScope();
1460
1461 sema::CompoundScopeInfo &getCurCompoundScope() const;
1462
1463 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1464
1465 /// Retrieve the current block, if any.
1466 sema::BlockScopeInfo *getCurBlock();
1467
1468 /// Get the innermost lambda enclosing the current location, if any. This
1469 /// looks through intervening non-lambda scopes such as local functions and
1470 /// blocks.
1471 sema::LambdaScopeInfo *getEnclosingLambda() const;
1472
1473 /// Retrieve the current lambda scope info, if any.
1474 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1475 /// lambda scope info ignoring all inner capturing scopes that are not
1476 /// lambda scopes.
1477 sema::LambdaScopeInfo *
1478 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1479
1480 /// Retrieve the current generic lambda info, if any.
1481 sema::LambdaScopeInfo *getCurGenericLambda();
1482
1483 /// Retrieve the current captured region, if any.
1484 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1485
1486 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1487 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1488
1489 void ActOnComment(SourceRange Comment);
1490
1491 //===--------------------------------------------------------------------===//
1492 // Type Analysis / Processing: SemaType.cpp.
1493 //
1494
1495 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1496 const DeclSpec *DS = nullptr);
1497 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1498 const DeclSpec *DS = nullptr);
1499 QualType BuildPointerType(QualType T,
1500 SourceLocation Loc, DeclarationName Entity);
1501 QualType BuildReferenceType(QualType T, bool LValueRef,
1502 SourceLocation Loc, DeclarationName Entity);
1503 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1504 Expr *ArraySize, unsigned Quals,
1505 SourceRange Brackets, DeclarationName Entity);
1506 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1507 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1508 SourceLocation AttrLoc);
1509 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1510 SourceLocation AttrLoc);
1511
1512 /// Same as above, but constructs the AddressSpace index if not provided.
1513 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1514 SourceLocation AttrLoc);
1515
1516 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1517
1518 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1519
1520 /// Build a function type.
1521 ///
1522 /// This routine checks the function type according to C++ rules and
1523 /// under the assumption that the result type and parameter types have
1524 /// just been instantiated from a template. It therefore duplicates
1525 /// some of the behavior of GetTypeForDeclarator, but in a much
1526 /// simpler form that is only suitable for this narrow use case.
1527 ///
1528 /// \param T The return type of the function.
1529 ///
1530 /// \param ParamTypes The parameter types of the function. This array
1531 /// will be modified to account for adjustments to the types of the
1532 /// function parameters.
1533 ///
1534 /// \param Loc The location of the entity whose type involves this
1535 /// function type or, if there is no such entity, the location of the
1536 /// type that will have function type.
1537 ///
1538 /// \param Entity The name of the entity that involves the function
1539 /// type, if known.
1540 ///
1541 /// \param EPI Extra information about the function type. Usually this will
1542 /// be taken from an existing function with the same prototype.
1543 ///
1544 /// \returns A suitable function type, if there are no errors. The
1545 /// unqualified type will always be a FunctionProtoType.
1546 /// Otherwise, returns a NULL type.
1547 QualType BuildFunctionType(QualType T,
1548 MutableArrayRef<QualType> ParamTypes,
1549 SourceLocation Loc, DeclarationName Entity,
1550 const FunctionProtoType::ExtProtoInfo &EPI);
1551
1552 QualType BuildMemberPointerType(QualType T, QualType Class,
1553 SourceLocation Loc,
1554 DeclarationName Entity);
1555 QualType BuildBlockPointerType(QualType T,
1556 SourceLocation Loc, DeclarationName Entity);
1557 QualType BuildParenType(QualType T);
1558 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1559 QualType BuildReadPipeType(QualType T,
1560 SourceLocation Loc);
1561 QualType BuildWritePipeType(QualType T,
1562 SourceLocation Loc);
1563
1564 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1565 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1566
1567 /// Package the given type and TSI into a ParsedType.
1568 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1569 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1570 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1571 static QualType GetTypeFromParser(ParsedType Ty,
1572 TypeSourceInfo **TInfo = nullptr);
1573 CanThrowResult canThrow(const Expr *E);
1574 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1575 const FunctionProtoType *FPT);
1576 void UpdateExceptionSpec(FunctionDecl *FD,
1577 const FunctionProtoType::ExceptionSpecInfo &ESI);
1578 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1579 bool CheckDistantExceptionSpec(QualType T);
1580 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1581 bool CheckEquivalentExceptionSpec(
1582 const FunctionProtoType *Old, SourceLocation OldLoc,
1583 const FunctionProtoType *New, SourceLocation NewLoc);
1584 bool CheckEquivalentExceptionSpec(
1585 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1586 const FunctionProtoType *Old, SourceLocation OldLoc,
1587 const FunctionProtoType *New, SourceLocation NewLoc);
1588 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1589 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1590 const PartialDiagnostic &NestedDiagID,
1591 const PartialDiagnostic &NoteID,
1592 const PartialDiagnostic &NoThrowDiagID,
1593 const FunctionProtoType *Superset,
1594 SourceLocation SuperLoc,
1595 const FunctionProtoType *Subset,
1596 SourceLocation SubLoc);
1597 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1598 const PartialDiagnostic &NoteID,
1599 const FunctionProtoType *Target,
1600 SourceLocation TargetLoc,
1601 const FunctionProtoType *Source,
1602 SourceLocation SourceLoc);
1603
1604 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1605
1606 /// The parser has parsed the context-sensitive type 'instancetype'
1607 /// in an Objective-C message declaration. Return the appropriate type.
1608 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1609
1610 /// Abstract class used to diagnose incomplete types.
1611 struct TypeDiagnoser {
1612 TypeDiagnoser() {}
1613
1614 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1615 virtual ~TypeDiagnoser() {}
1616 };
1617
1618 static int getPrintable(int I) { return I; }
1619 static unsigned getPrintable(unsigned I) { return I; }
1620 static bool getPrintable(bool B) { return B; }
1621 static const char * getPrintable(const char *S) { return S; }
1622 static StringRef getPrintable(StringRef S) { return S; }
1623 static const std::string &getPrintable(const std::string &S) { return S; }
1624 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1625 return II;
1626 }
1627 static DeclarationName getPrintable(DeclarationName N) { return N; }
1628 static QualType getPrintable(QualType T) { return T; }
1629 static SourceRange getPrintable(SourceRange R) { return R; }
1630 static SourceRange getPrintable(SourceLocation L) { return L; }
1631 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1632 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1633
1634 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1635 unsigned DiagID;
1636 std::tuple<const Ts &...> Args;
1637
1638 template <std::size_t... Is>
1639 void emit(const SemaDiagnosticBuilder &DB,
1640 std::index_sequence<Is...>) const {
1641 // Apply all tuple elements to the builder in order.
1642 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1643 (void)Dummy;
1644 }
1645
1646 public:
1647 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1648 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1649 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1649, __PRETTY_FUNCTION__))
;
1650 }
1651
1652 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1653 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1654 emit(DB, std::index_sequence_for<Ts...>());
1655 DB << T;
1656 }
1657 };
1658
1659private:
1660 /// Methods for marking which expressions involve dereferencing a pointer
1661 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1662 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1663 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1664 /// `*p`, but need to check that `address of` is called on it. This requires
1665 /// keeping a container of all pending expressions and checking if the address
1666 /// of them are eventually taken.
1667 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1668 void CheckAddressOfNoDeref(const Expr *E);
1669 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1670
1671 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1672 TypeDiagnoser *Diagnoser);
1673
1674 struct ModuleScope {
1675 SourceLocation BeginLoc;
1676 clang::Module *Module = nullptr;
1677 bool ModuleInterface = false;
1678 bool ImplicitGlobalModuleFragment = false;
1679 VisibleModuleSet OuterVisibleModules;
1680 };
1681 /// The modules we're currently parsing.
1682 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1683
1684 /// Namespace definitions that we will export when they finish.
1685 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1686
1687 /// Get the module whose scope we are currently within.
1688 Module *getCurrentModule() const {
1689 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1690 }
1691
1692 VisibleModuleSet VisibleModules;
1693
1694public:
1695 /// Get the module owning an entity.
1696 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1697
1698 /// Make a merged definition of an existing hidden definition \p ND
1699 /// visible at the specified location.
1700 void makeMergedDefinitionVisible(NamedDecl *ND);
1701
1702 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1703
1704 /// Determine whether a declaration is visible to name lookup.
1705 bool isVisible(const NamedDecl *D) {
1706 return !D->isHidden() || isVisibleSlow(D);
1707 }
1708
1709 /// Determine whether any declaration of an entity is visible.
1710 bool
1711 hasVisibleDeclaration(const NamedDecl *D,
1712 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1713 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1714 }
1715 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1716 llvm::SmallVectorImpl<Module *> *Modules);
1717
1718 bool hasVisibleMergedDefinition(NamedDecl *Def);
1719 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1720
1721 /// Determine if \p D and \p Suggested have a structurally compatible
1722 /// layout as described in C11 6.2.7/1.
1723 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1724
1725 /// Determine if \p D has a visible definition. If not, suggest a declaration
1726 /// that should be made visible to expose the definition.
1727 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1728 bool OnlyNeedComplete = false);
1729 bool hasVisibleDefinition(const NamedDecl *D) {
1730 NamedDecl *Hidden;
1731 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1732 }
1733
1734 /// Determine if the template parameter \p D has a visible default argument.
1735 bool
1736 hasVisibleDefaultArgument(const NamedDecl *D,
1737 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1738
1739 /// Determine if there is a visible declaration of \p D that is an explicit
1740 /// specialization declaration for a specialization of a template. (For a
1741 /// member specialization, use hasVisibleMemberSpecialization.)
1742 bool hasVisibleExplicitSpecialization(
1743 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1744
1745 /// Determine if there is a visible declaration of \p D that is a member
1746 /// specialization declaration (as opposed to an instantiated declaration).
1747 bool hasVisibleMemberSpecialization(
1748 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1749
1750 /// Determine if \p A and \p B are equivalent internal linkage declarations
1751 /// from different modules, and thus an ambiguity error can be downgraded to
1752 /// an extension warning.
1753 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1754 const NamedDecl *B);
1755 void diagnoseEquivalentInternalLinkageDeclarations(
1756 SourceLocation Loc, const NamedDecl *D,
1757 ArrayRef<const NamedDecl *> Equiv);
1758
1759 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1760
1761 bool isCompleteType(SourceLocation Loc, QualType T) {
1762 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1763 }
1764 bool RequireCompleteType(SourceLocation Loc, QualType T,
1765 TypeDiagnoser &Diagnoser);
1766 bool RequireCompleteType(SourceLocation Loc, QualType T,
1767 unsigned DiagID);
1768
1769 template <typename... Ts>
1770 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1771 const Ts &...Args) {
1772 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1773 return RequireCompleteType(Loc, T, Diagnoser);
1774 }
1775
1776 void completeExprArrayBound(Expr *E);
1777 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1778 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1779
1780 template <typename... Ts>
1781 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1782 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1783 return RequireCompleteExprType(E, Diagnoser);
1784 }
1785
1786 bool RequireLiteralType(SourceLocation Loc, QualType T,
1787 TypeDiagnoser &Diagnoser);
1788 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1789
1790 template <typename... Ts>
1791 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1792 const Ts &...Args) {
1793 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1794 return RequireLiteralType(Loc, T, Diagnoser);
1795 }
1796
1797 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1798 const CXXScopeSpec &SS, QualType T,
1799 TagDecl *OwnedTagDecl = nullptr);
1800
1801 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1802 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1803 /// context, such as when building a type for decltype(auto).
1804 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1805 bool AsUnevaluated = true);
1806 QualType BuildUnaryTransformType(QualType BaseType,
1807 UnaryTransformType::UTTKind UKind,
1808 SourceLocation Loc);
1809
1810 //===--------------------------------------------------------------------===//
1811 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1812 //
1813
1814 struct SkipBodyInfo {
1815 SkipBodyInfo()
1816 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1817 New(nullptr) {}
1818 bool ShouldSkip;
1819 bool CheckSameAsPrevious;
1820 NamedDecl *Previous;
1821 NamedDecl *New;
1822 };
1823
1824 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1825
1826 void DiagnoseUseOfUnimplementedSelectors();
1827
1828 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1829
1830 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1831 Scope *S, CXXScopeSpec *SS = nullptr,
1832 bool isClassName = false, bool HasTrailingDot = false,
1833 ParsedType ObjectType = nullptr,
1834 bool IsCtorOrDtorName = false,
1835 bool WantNontrivialTypeSourceInfo = false,
1836 bool IsClassTemplateDeductionContext = true,
1837 IdentifierInfo **CorrectedII = nullptr);
1838 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1839 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1840 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1841 SourceLocation IILoc,
1842 Scope *S,
1843 CXXScopeSpec *SS,
1844 ParsedType &SuggestedType,
1845 bool IsTemplateName = false);
1846
1847 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1848 /// type name has failed in a dependent context. In these situations, we
1849 /// automatically form a DependentTypeName that will retry lookup in a related
1850 /// scope during instantiation.
1851 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1852 SourceLocation NameLoc,
1853 bool IsTemplateTypeArg);
1854
1855 /// Describes the result of the name lookup and resolution performed
1856 /// by \c ClassifyName().
1857 enum NameClassificationKind {
1858 /// This name is not a type or template in this context, but might be
1859 /// something else.
1860 NC_Unknown,
1861 /// Classification failed; an error has been produced.
1862 NC_Error,
1863 /// The name has been typo-corrected to a keyword.
1864 NC_Keyword,
1865 /// The name was classified as a type.
1866 NC_Type,
1867 /// The name was classified as a specific non-type, non-template
1868 /// declaration. ActOnNameClassifiedAsNonType should be called to
1869 /// convert the declaration to an expression.
1870 NC_NonType,
1871 /// The name was classified as an ADL-only function name.
1872 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1873 /// result to an expression.
1874 NC_UndeclaredNonType,
1875 /// The name denotes a member of a dependent type that could not be
1876 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1877 /// convert the result to an expression.
1878 NC_DependentNonType,
1879 /// The name was classified as a non-type, and an expression representing
1880 /// that name has been formed.
1881 NC_ContextIndependentExpr,
1882 /// The name was classified as a template whose specializations are types.
1883 NC_TypeTemplate,
1884 /// The name was classified as a variable template name.
1885 NC_VarTemplate,
1886 /// The name was classified as a function template name.
1887 NC_FunctionTemplate,
1888 /// The name was classified as an ADL-only function template name.
1889 NC_UndeclaredTemplate,
1890 };
1891
1892 class NameClassification {
1893 NameClassificationKind Kind;
1894 union {
1895 ExprResult Expr;
1896 NamedDecl *NonTypeDecl;
1897 TemplateName Template;
1898 ParsedType Type;
1899 };
1900
1901 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1902
1903 public:
1904 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1905
1906 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1907
1908 static NameClassification Error() {
1909 return NameClassification(NC_Error);
1910 }
1911
1912 static NameClassification Unknown() {
1913 return NameClassification(NC_Unknown);
1914 }
1915
1916 static NameClassification ContextIndependentExpr(ExprResult E) {
1917 NameClassification Result(NC_ContextIndependentExpr);
1918 Result.Expr = E;
1919 return Result;
1920 }
1921
1922 static NameClassification NonType(NamedDecl *D) {
1923 NameClassification Result(NC_NonType);
1924 Result.NonTypeDecl = D;
1925 return Result;
1926 }
1927
1928 static NameClassification UndeclaredNonType() {
1929 return NameClassification(NC_UndeclaredNonType);
1930 }
1931
1932 static NameClassification DependentNonType() {
1933 return NameClassification(NC_DependentNonType);
1934 }
1935
1936 static NameClassification TypeTemplate(TemplateName Name) {
1937 NameClassification Result(NC_TypeTemplate);
1938 Result.Template = Name;
1939 return Result;
1940 }
1941
1942 static NameClassification VarTemplate(TemplateName Name) {
1943 NameClassification Result(NC_VarTemplate);
1944 Result.Template = Name;
1945 return Result;
1946 }
1947
1948 static NameClassification FunctionTemplate(TemplateName Name) {
1949 NameClassification Result(NC_FunctionTemplate);
1950 Result.Template = Name;
1951 return Result;
1952 }
1953
1954 static NameClassification UndeclaredTemplate(TemplateName Name) {
1955 NameClassification Result(NC_UndeclaredTemplate);
1956 Result.Template = Name;
1957 return Result;
1958 }
1959
1960 NameClassificationKind getKind() const { return Kind; }
1961
1962 ExprResult getExpression() const {
1963 assert(Kind == NC_ContextIndependentExpr)((Kind == NC_ContextIndependentExpr) ? static_cast<void>
(0) : __assert_fail ("Kind == NC_ContextIndependentExpr", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1963, __PRETTY_FUNCTION__))
;
1964 return Expr;
1965 }
1966
1967 ParsedType getType() const {
1968 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1968, __PRETTY_FUNCTION__))
;
1969 return Type;
1970 }
1971
1972 NamedDecl *getNonTypeDecl() const {
1973 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1973, __PRETTY_FUNCTION__))
;
1974 return NonTypeDecl;
1975 }
1976
1977 TemplateName getTemplateName() const {
1978 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1979, __PRETTY_FUNCTION__))
1979 Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1979, __PRETTY_FUNCTION__))
;
1980 return Template;
1981 }
1982
1983 TemplateNameKind getTemplateNameKind() const {
1984 switch (Kind) {
1985 case NC_TypeTemplate:
1986 return TNK_Type_template;
1987 case NC_FunctionTemplate:
1988 return TNK_Function_template;
1989 case NC_VarTemplate:
1990 return TNK_Var_template;
1991 case NC_UndeclaredTemplate:
1992 return TNK_Undeclared_template;
1993 default:
1994 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 1994)
;
1995 }
1996 }
1997 };
1998
1999 /// Perform name lookup on the given name, classifying it based on
2000 /// the results of name lookup and the following token.
2001 ///
2002 /// This routine is used by the parser to resolve identifiers and help direct
2003 /// parsing. When the identifier cannot be found, this routine will attempt
2004 /// to correct the typo and classify based on the resulting name.
2005 ///
2006 /// \param S The scope in which we're performing name lookup.
2007 ///
2008 /// \param SS The nested-name-specifier that precedes the name.
2009 ///
2010 /// \param Name The identifier. If typo correction finds an alternative name,
2011 /// this pointer parameter will be updated accordingly.
2012 ///
2013 /// \param NameLoc The location of the identifier.
2014 ///
2015 /// \param NextToken The token following the identifier. Used to help
2016 /// disambiguate the name.
2017 ///
2018 /// \param CCC The correction callback, if typo correction is desired.
2019 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2020 IdentifierInfo *&Name, SourceLocation NameLoc,
2021 const Token &NextToken,
2022 CorrectionCandidateCallback *CCC = nullptr);
2023
2024 /// Act on the result of classifying a name as an undeclared (ADL-only)
2025 /// non-type declaration.
2026 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2027 SourceLocation NameLoc);
2028 /// Act on the result of classifying a name as an undeclared member of a
2029 /// dependent base class.
2030 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2031 IdentifierInfo *Name,
2032 SourceLocation NameLoc,
2033 bool IsAddressOfOperand);
2034 /// Act on the result of classifying a name as a specific non-type
2035 /// declaration.
2036 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2037 NamedDecl *Found,
2038 SourceLocation NameLoc,
2039 const Token &NextToken);
2040
2041 /// Describes the detailed kind of a template name. Used in diagnostics.
2042 enum class TemplateNameKindForDiagnostics {
2043 ClassTemplate,
2044 FunctionTemplate,
2045 VarTemplate,
2046 AliasTemplate,
2047 TemplateTemplateParam,
2048 Concept,
2049 DependentTemplate
2050 };
2051 TemplateNameKindForDiagnostics
2052 getTemplateNameKindForDiagnostics(TemplateName Name);
2053
2054 /// Determine whether it's plausible that E was intended to be a
2055 /// template-name.
2056 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2057 if (!getLangOpts().CPlusPlus || E.isInvalid())
2058 return false;
2059 Dependent = false;
2060 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2061 return !DRE->hasExplicitTemplateArgs();
2062 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2063 return !ME->hasExplicitTemplateArgs();
2064 Dependent = true;
2065 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2066 return !DSDRE->hasExplicitTemplateArgs();
2067 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2068 return !DSME->hasExplicitTemplateArgs();
2069 // Any additional cases recognized here should also be handled by
2070 // diagnoseExprIntendedAsTemplateName.
2071 return false;
2072 }
2073 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2074 SourceLocation Less,
2075 SourceLocation Greater);
2076
2077 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2078
2079 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2080 MultiTemplateParamsArg TemplateParameterLists);
2081 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2082 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2083 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2084 DeclarationName Name, SourceLocation Loc,
2085 bool IsTemplateId);
2086 void
2087 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2088 SourceLocation FallbackLoc,
2089 SourceLocation ConstQualLoc = SourceLocation(),
2090 SourceLocation VolatileQualLoc = SourceLocation(),
2091 SourceLocation RestrictQualLoc = SourceLocation(),
2092 SourceLocation AtomicQualLoc = SourceLocation(),
2093 SourceLocation UnalignedQualLoc = SourceLocation());
2094
2095 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2096 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2097 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2098 const LookupResult &R);
2099 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2100 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2101 const LookupResult &R);
2102 void CheckShadow(Scope *S, VarDecl *D);
2103
2104 /// Warn if 'E', which is an expression that is about to be modified, refers
2105 /// to a shadowing declaration.
2106 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2107
2108 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2109
2110private:
2111 /// Map of current shadowing declarations to shadowed declarations. Warn if
2112 /// it looks like the user is trying to modify the shadowing declaration.
2113 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2114
2115public:
2116 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2117 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2118 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2119 TypedefNameDecl *NewTD);
2120 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2121 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2122 TypeSourceInfo *TInfo,
2123 LookupResult &Previous);
2124 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2125 LookupResult &Previous, bool &Redeclaration);
2126 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2127 TypeSourceInfo *TInfo,
2128 LookupResult &Previous,
2129 MultiTemplateParamsArg TemplateParamLists,
2130 bool &AddToScope,
2131 ArrayRef<BindingDecl *> Bindings = None);
2132 NamedDecl *
2133 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2134 MultiTemplateParamsArg TemplateParamLists);
2135 // Returns true if the variable declaration is a redeclaration
2136 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2137 void CheckVariableDeclarationType(VarDecl *NewVD);
2138 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2139 Expr *Init);
2140 void CheckCompleteVariableDeclaration(VarDecl *VD);
2141 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2142 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2143
2144 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2145 TypeSourceInfo *TInfo,
2146 LookupResult &Previous,
2147 MultiTemplateParamsArg TemplateParamLists,
2148 bool &AddToScope);
2149 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2150
2151 enum class CheckConstexprKind {
2152 /// Diagnose issues that are non-constant or that are extensions.
2153 Diagnose,
2154 /// Identify whether this function satisfies the formal rules for constexpr
2155 /// functions in the current lanugage mode (with no extensions).
2156 CheckValid
2157 };
2158
2159 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2160 CheckConstexprKind Kind);
2161
2162 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2163 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2164 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2165 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2166 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2167 // Returns true if the function declaration is a redeclaration
2168 bool CheckFunctionDeclaration(Scope *S,
2169 FunctionDecl *NewFD, LookupResult &Previous,
2170 bool IsMemberSpecialization);
2171 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2172 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2173 QualType NewT, QualType OldT);
2174 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2175 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2176 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2177 bool IsDefinition);
2178 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2179 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2180 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2181 SourceLocation Loc,
2182 QualType T);
2183 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2184 SourceLocation NameLoc, IdentifierInfo *Name,
2185 QualType T, TypeSourceInfo *TSInfo,
2186 StorageClass SC);
2187 void ActOnParamDefaultArgument(Decl *param,
2188 SourceLocation EqualLoc,
2189 Expr *defarg);
2190 void ActOnParamUnparsedDefaultArgument(Decl *param,
2191 SourceLocation EqualLoc,
2192 SourceLocation ArgLoc);
2193 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2194 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2195 SourceLocation EqualLoc);
2196
2197 // Contexts where using non-trivial C union types can be disallowed. This is
2198 // passed to err_non_trivial_c_union_in_invalid_context.
2199 enum NonTrivialCUnionContext {
2200 // Function parameter.
2201 NTCUC_FunctionParam,
2202 // Function return.
2203 NTCUC_FunctionReturn,
2204 // Default-initialized object.
2205 NTCUC_DefaultInitializedObject,
2206 // Variable with automatic storage duration.
2207 NTCUC_AutoVar,
2208 // Initializer expression that might copy from another object.
2209 NTCUC_CopyInit,
2210 // Assignment.
2211 NTCUC_Assignment,
2212 // Compound literal.
2213 NTCUC_CompoundLiteral,
2214 // Block capture.
2215 NTCUC_BlockCapture,
2216 // lvalue-to-rvalue conversion of volatile type.
2217 NTCUC_LValueToRValueVolatile,
2218 };
2219
2220 /// Emit diagnostics if the initializer or any of its explicit or
2221 /// implicitly-generated subexpressions require copying or
2222 /// default-initializing a type that is or contains a C union type that is
2223 /// non-trivial to copy or default-initialize.
2224 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2225
2226 // These flags are passed to checkNonTrivialCUnion.
2227 enum NonTrivialCUnionKind {
2228 NTCUK_Init = 0x1,
2229 NTCUK_Destruct = 0x2,
2230 NTCUK_Copy = 0x4,
2231 };
2232
2233 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2234 /// a non-trivial C union is used in an invalid context.
2235 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2236 NonTrivialCUnionContext UseContext,
2237 unsigned NonTrivialKind);
2238
2239 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2240 void ActOnUninitializedDecl(Decl *dcl);
2241 void ActOnInitializerError(Decl *Dcl);
2242
2243 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2244 void ActOnCXXForRangeDecl(Decl *D);
2245 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2246 IdentifierInfo *Ident,
2247 ParsedAttributes &Attrs,
2248 SourceLocation AttrEnd);
2249 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2250 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2251 void CheckStaticLocalForDllExport(VarDecl *VD);
2252 void FinalizeDeclaration(Decl *D);
2253 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2254 ArrayRef<Decl *> Group);
2255 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2256
2257 /// Should be called on all declarations that might have attached
2258 /// documentation comments.
2259 void ActOnDocumentableDecl(Decl *D);
2260 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2261
2262 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2263 SourceLocation LocAfterDecls);
2264 void CheckForFunctionRedefinition(
2265 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2266 SkipBodyInfo *SkipBody = nullptr);
2267 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2268 MultiTemplateParamsArg TemplateParamLists,
2269 SkipBodyInfo *SkipBody = nullptr);
2270 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2271 SkipBodyInfo *SkipBody = nullptr);
2272 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2273 bool isObjCMethodDecl(Decl *D) {
2274 return D && isa<ObjCMethodDecl>(D);
2275 }
2276
2277 /// Determine whether we can delay parsing the body of a function or
2278 /// function template until it is used, assuming we don't care about emitting
2279 /// code for that function.
2280 ///
2281 /// This will be \c false if we may need the body of the function in the
2282 /// middle of parsing an expression (where it's impractical to switch to
2283 /// parsing a different function), for instance, if it's constexpr in C++11
2284 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2285 bool canDelayFunctionBody(const Declarator &D);
2286
2287 /// Determine whether we can skip parsing the body of a function
2288 /// definition, assuming we don't care about analyzing its body or emitting
2289 /// code for that function.
2290 ///
2291 /// This will be \c false only if we may need the body of the function in
2292 /// order to parse the rest of the program (for instance, if it is
2293 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2294 bool canSkipFunctionBody(Decl *D);
2295
2296 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2297 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2298 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2299 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2300 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2301
2302 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2303 /// attribute for which parsing is delayed.
2304 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2305
2306 /// Diagnose any unused parameters in the given sequence of
2307 /// ParmVarDecl pointers.
2308 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2309
2310 /// Diagnose whether the size of parameters or return value of a
2311 /// function or obj-c method definition is pass-by-value and larger than a
2312 /// specified threshold.
2313 void
2314 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2315 QualType ReturnTy, NamedDecl *D);
2316
2317 void DiagnoseInvalidJumps(Stmt *Body);
2318 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2319 SourceLocation AsmLoc,
2320 SourceLocation RParenLoc);
2321
2322 /// Handle a C++11 empty-declaration and attribute-declaration.
2323 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2324 SourceLocation SemiLoc);
2325
2326 enum class ModuleDeclKind {
2327 Interface, ///< 'export module X;'
2328 Implementation, ///< 'module X;'
2329 };
2330
2331 /// The parser has processed a module-declaration that begins the definition
2332 /// of a module interface or implementation.
2333 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2334 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2335 ModuleIdPath Path, bool IsFirstDecl);
2336
2337 /// The parser has processed a global-module-fragment declaration that begins
2338 /// the definition of the global module fragment of the current module unit.
2339 /// \param ModuleLoc The location of the 'module' keyword.
2340 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2341
2342 /// The parser has processed a private-module-fragment declaration that begins
2343 /// the definition of the private module fragment of the current module unit.
2344 /// \param ModuleLoc The location of the 'module' keyword.
2345 /// \param PrivateLoc The location of the 'private' keyword.
2346 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2347 SourceLocation PrivateLoc);
2348
2349 /// The parser has processed a module import declaration.
2350 ///
2351 /// \param StartLoc The location of the first token in the declaration. This
2352 /// could be the location of an '@', 'export', or 'import'.
2353 /// \param ExportLoc The location of the 'export' keyword, if any.
2354 /// \param ImportLoc The location of the 'import' keyword.
2355 /// \param Path The module access path.
2356 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2357 SourceLocation ExportLoc,
2358 SourceLocation ImportLoc, ModuleIdPath Path);
2359 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2360 SourceLocation ExportLoc,
2361 SourceLocation ImportLoc, Module *M,
2362 ModuleIdPath Path = {});
2363
2364 /// The parser has processed a module import translated from a
2365 /// #include or similar preprocessing directive.
2366 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2367 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2368
2369 /// The parsed has entered a submodule.
2370 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2371 /// The parser has left a submodule.
2372 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2373
2374 /// Create an implicit import of the given module at the given
2375 /// source location, for error recovery, if possible.
2376 ///
2377 /// This routine is typically used when an entity found by name lookup
2378 /// is actually hidden within a module that we know about but the user
2379 /// has forgotten to import.
2380 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2381 Module *Mod);
2382
2383 /// Kinds of missing import. Note, the values of these enumerators correspond
2384 /// to %select values in diagnostics.
2385 enum class MissingImportKind {
2386 Declaration,
2387 Definition,
2388 DefaultArgument,
2389 ExplicitSpecialization,
2390 PartialSpecialization
2391 };
2392
2393 /// Diagnose that the specified declaration needs to be visible but
2394 /// isn't, and suggest a module import that would resolve the problem.
2395 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2396 MissingImportKind MIK, bool Recover = true);
2397 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2398 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2399 MissingImportKind MIK, bool Recover);
2400
2401 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2402 SourceLocation LBraceLoc);
2403 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2404 SourceLocation RBraceLoc);
2405
2406 /// We've found a use of a templated declaration that would trigger an
2407 /// implicit instantiation. Check that any relevant explicit specializations
2408 /// and partial specializations are visible, and diagnose if not.
2409 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2410
2411 /// We've found a use of a template specialization that would select a
2412 /// partial specialization. Check that the partial specialization is visible,
2413 /// and diagnose if not.
2414 void checkPartialSpecializationVisibility(SourceLocation Loc,
2415 NamedDecl *Spec);
2416
2417 /// Retrieve a suitable printing policy for diagnostics.
2418 PrintingPolicy getPrintingPolicy() const {
2419 return getPrintingPolicy(Context, PP);
2420 }
2421
2422 /// Retrieve a suitable printing policy for diagnostics.
2423 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2424 const Preprocessor &PP);
2425
2426 /// Scope actions.
2427 void ActOnPopScope(SourceLocation Loc, Scope *S);
2428 void ActOnTranslationUnitScope(Scope *S);
2429
2430 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2431 RecordDecl *&AnonRecord);
2432 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2433 MultiTemplateParamsArg TemplateParams,
2434 bool IsExplicitInstantiation,
2435 RecordDecl *&AnonRecord);
2436
2437 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2438 AccessSpecifier AS,
2439 RecordDecl *Record,
2440 const PrintingPolicy &Policy);
2441
2442 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2443 RecordDecl *Record);
2444
2445 /// Common ways to introduce type names without a tag for use in diagnostics.
2446 /// Keep in sync with err_tag_reference_non_tag.
2447 enum NonTagKind {
2448 NTK_NonStruct,
2449 NTK_NonClass,
2450 NTK_NonUnion,
2451 NTK_NonEnum,
2452 NTK_Typedef,
2453 NTK_TypeAlias,
2454 NTK_Template,
2455 NTK_TypeAliasTemplate,
2456 NTK_TemplateTemplateArgument,
2457 };
2458
2459 /// Given a non-tag type declaration, returns an enum useful for indicating
2460 /// what kind of non-tag type this is.
2461 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2462
2463 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2464 TagTypeKind NewTag, bool isDefinition,
2465 SourceLocation NewTagLoc,
2466 const IdentifierInfo *Name);
2467
2468 enum TagUseKind {
2469 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2470 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2471 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2472 TUK_Friend // Friend declaration: 'friend struct foo;'
2473 };
2474
2475 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2476 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2477 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2478 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2479 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2480 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2481 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2482 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2483 SkipBodyInfo *SkipBody = nullptr);
2484
2485 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2486 unsigned TagSpec, SourceLocation TagLoc,
2487 CXXScopeSpec &SS, IdentifierInfo *Name,
2488 SourceLocation NameLoc,
2489 const ParsedAttributesView &Attr,
2490 MultiTemplateParamsArg TempParamLists);
2491
2492 TypeResult ActOnDependentTag(Scope *S,
2493 unsigned TagSpec,
2494 TagUseKind TUK,
2495 const CXXScopeSpec &SS,
2496 IdentifierInfo *Name,
2497 SourceLocation TagLoc,
2498 SourceLocation NameLoc);
2499
2500 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2501 IdentifierInfo *ClassName,
2502 SmallVectorImpl<Decl *> &Decls);
2503 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2504 Declarator &D, Expr *BitfieldWidth);
2505
2506 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2507 Declarator &D, Expr *BitfieldWidth,
2508 InClassInitStyle InitStyle,
2509 AccessSpecifier AS);
2510 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2511 SourceLocation DeclStart, Declarator &D,
2512 Expr *BitfieldWidth,
2513 InClassInitStyle InitStyle,
2514 AccessSpecifier AS,
2515 const ParsedAttr &MSPropertyAttr);
2516
2517 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2518 TypeSourceInfo *TInfo,
2519 RecordDecl *Record, SourceLocation Loc,
2520 bool Mutable, Expr *BitfieldWidth,
2521 InClassInitStyle InitStyle,
2522 SourceLocation TSSL,
2523 AccessSpecifier AS, NamedDecl *PrevDecl,
2524 Declarator *D = nullptr);
2525
2526 bool CheckNontrivialField(FieldDecl *FD);
2527 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2528
2529 enum TrivialABIHandling {
2530 /// The triviality of a method unaffected by "trivial_abi".
2531 TAH_IgnoreTrivialABI,
2532
2533 /// The triviality of a method affected by "trivial_abi".
2534 TAH_ConsiderTrivialABI
2535 };
2536
2537 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2538 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2539 bool Diagnose = false);
2540 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2541 void ActOnLastBitfield(SourceLocation DeclStart,
2542 SmallVectorImpl<Decl *> &AllIvarDecls);
2543 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2544 Declarator &D, Expr *BitfieldWidth,
2545 tok::ObjCKeywordKind visibility);
2546
2547 // This is used for both record definitions and ObjC interface declarations.
2548 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2549 ArrayRef<Decl *> Fields, SourceLocation LBrac,
2550 SourceLocation RBrac, const ParsedAttributesView &AttrList);
2551
2552 /// ActOnTagStartDefinition - Invoked when we have entered the
2553 /// scope of a tag's definition (e.g., for an enumeration, class,
2554 /// struct, or union).
2555 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2556
2557 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2558 /// Differently from C++, actually parse the body and reject / error out
2559 /// in case of a structural mismatch.
2560 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2561 SkipBodyInfo &SkipBody);
2562
2563 typedef void *SkippedDefinitionContext;
2564
2565 /// Invoked when we enter a tag definition that we're skipping.
2566 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2567
2568 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2569
2570 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2571 /// C++ record definition's base-specifiers clause and are starting its
2572 /// member declarations.
2573 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2574 SourceLocation FinalLoc,
2575 bool IsFinalSpelledSealed,
2576 SourceLocation LBraceLoc);
2577
2578 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2579 /// the definition of a tag (enumeration, class, struct, or union).
2580 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2581 SourceRange BraceRange);
2582
2583 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2584
2585 void ActOnObjCContainerFinishDefinition();
2586
2587 /// Invoked when we must temporarily exit the objective-c container
2588 /// scope for parsing/looking-up C constructs.
2589 ///
2590 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2591 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2592 void ActOnObjCReenterContainerContext(DeclContext *DC);
2593
2594 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2595 /// error parsing the definition of a tag.
2596 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2597
2598 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2599 EnumConstantDecl *LastEnumConst,
2600 SourceLocation IdLoc,
2601 IdentifierInfo *Id,
2602 Expr *val);
2603 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2604 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2605 QualType EnumUnderlyingTy, bool IsFixed,
2606 const EnumDecl *Prev);
2607
2608 /// Determine whether the body of an anonymous enumeration should be skipped.
2609 /// \param II The name of the first enumerator.
2610 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2611 SourceLocation IILoc);
2612
2613 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2614 SourceLocation IdLoc, IdentifierInfo *Id,
2615 const ParsedAttributesView &Attrs,
2616 SourceLocation EqualLoc, Expr *Val);
2617 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2618 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2619 const ParsedAttributesView &Attr);
2620
2621 DeclContext *getContainingDC(DeclContext *DC);
2622
2623 /// Set the current declaration context until it gets popped.
2624 void PushDeclContext(Scope *S, DeclContext *DC);
2625 void PopDeclContext();
2626
2627 /// EnterDeclaratorContext - Used when we must lookup names in the context
2628 /// of a declarator's nested name specifier.
2629 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2630 void ExitDeclaratorContext(Scope *S);
2631
2632 /// Push the parameters of D, which must be a function, into scope.
2633 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2634 void ActOnExitFunctionContext();
2635
2636 DeclContext *getFunctionLevelDeclContext();
2637
2638 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2639 /// to the function decl for the function being parsed. If we're currently
2640 /// in a 'block', this returns the containing context.
2641 FunctionDecl *getCurFunctionDecl();
2642
2643 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2644 /// the method decl for the method being parsed. If we're currently
2645 /// in a 'block', this returns the containing context.
2646 ObjCMethodDecl *getCurMethodDecl();
2647
2648 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2649 /// or C function we're in, otherwise return null. If we're currently
2650 /// in a 'block', this returns the containing context.
2651 NamedDecl *getCurFunctionOrMethodDecl();
2652
2653 /// Add this decl to the scope shadowed decl chains.
2654 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2655
2656 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2657 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2658 /// true if 'D' belongs to the given declaration context.
2659 ///
2660 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2661 /// enclosing namespace set of the context, rather than contained
2662 /// directly within it.
2663 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2664 bool AllowInlineNamespace = false);
2665
2666 /// Finds the scope corresponding to the given decl context, if it
2667 /// happens to be an enclosing scope. Otherwise return NULL.
2668 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2669
2670 /// Subroutines of ActOnDeclarator().
2671 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2672 TypeSourceInfo *TInfo);
2673 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2674
2675 /// Describes the kind of merge to perform for availability
2676 /// attributes (including "deprecated", "unavailable", and "availability").
2677 enum AvailabilityMergeKind {
2678 /// Don't merge availability attributes at all.
2679 AMK_None,
2680 /// Merge availability attributes for a redeclaration, which requires
2681 /// an exact match.
2682 AMK_Redeclaration,
2683 /// Merge availability attributes for an override, which requires
2684 /// an exact match or a weakening of constraints.
2685 AMK_Override,
2686 /// Merge availability attributes for an implementation of
2687 /// a protocol requirement.
2688 AMK_ProtocolImplementation,
2689 };
2690
2691 /// Describes the kind of priority given to an availability attribute.
2692 ///
2693 /// The sum of priorities deteremines the final priority of the attribute.
2694 /// The final priority determines how the attribute will be merged.
2695 /// An attribute with a lower priority will always remove higher priority
2696 /// attributes for the specified platform when it is being applied. An
2697 /// attribute with a higher priority will not be applied if the declaration
2698 /// already has an availability attribute with a lower priority for the
2699 /// specified platform. The final prirority values are not expected to match
2700 /// the values in this enumeration, but instead should be treated as a plain
2701 /// integer value. This enumeration just names the priority weights that are
2702 /// used to calculate that final vaue.
2703 enum AvailabilityPriority : int {
2704 /// The availability attribute was specified explicitly next to the
2705 /// declaration.
2706 AP_Explicit = 0,
2707
2708 /// The availability attribute was applied using '#pragma clang attribute'.
2709 AP_PragmaClangAttribute = 1,
2710
2711 /// The availability attribute for a specific platform was inferred from
2712 /// an availability attribute for another platform.
2713 AP_InferredFromOtherPlatform = 2
2714 };
2715
2716 /// Attribute merging methods. Return true if a new attribute was added.
2717 AvailabilityAttr *
2718 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
2719 IdentifierInfo *Platform, bool Implicit,
2720 VersionTuple Introduced, VersionTuple Deprecated,
2721 VersionTuple Obsoleted, bool IsUnavailable,
2722 StringRef Message, bool IsStrict, StringRef Replacement,
2723 AvailabilityMergeKind AMK, int Priority);
2724 TypeVisibilityAttr *
2725 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2726 TypeVisibilityAttr::VisibilityType Vis);
2727 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2728 VisibilityAttr::VisibilityType Vis);
2729 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
2730 StringRef Uuid);
2731 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
2732 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
2733 MSInheritanceAttr *
2734 mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase,
2735 MSInheritanceAttr::Spelling SemanticSpelling);
2736 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
2737 IdentifierInfo *Format, int FormatIdx,
2738 int FirstArg);
2739 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2740 StringRef Name);
2741 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2742 StringRef Name);
2743 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
2744 const AttributeCommonInfo &CI,
2745 const IdentifierInfo *Ident);
2746 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
2747 NoSpeculativeLoadHardeningAttr *
2748 mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2749 const NoSpeculativeLoadHardeningAttr &AL);
2750 SpeculativeLoadHardeningAttr *
2751 mergeSpeculativeLoadHardeningAttr(Decl *D,
2752 const SpeculativeLoadHardeningAttr &AL);
2753 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
2754 const AttributeCommonInfo &CI);
2755 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2756 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2757 const InternalLinkageAttr &AL);
2758 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2759 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2760
2761 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2762 AvailabilityMergeKind AMK = AMK_Redeclaration);
2763 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2764 LookupResult &OldDecls);
2765 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2766 bool MergeTypeWithOld);
2767 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2768 Scope *S, bool MergeTypeWithOld);
2769 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2770 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2771 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2772 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2773 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2774 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2775 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2776
2777 // AssignmentAction - This is used by all the assignment diagnostic functions
2778 // to represent what is actually causing the operation
2779 enum AssignmentAction {
2780 AA_Assigning,
2781 AA_Passing,
2782 AA_Returning,
2783 AA_Converting,
2784 AA_Initializing,
2785 AA_Sending,
2786 AA_Casting,
2787 AA_Passing_CFAudited
2788 };
2789
2790 /// C++ Overloading.
2791 enum OverloadKind {
2792 /// This is a legitimate overload: the existing declarations are
2793 /// functions or function templates with different signatures.
2794 Ovl_Overload,
2795
2796 /// This is not an overload because the signature exactly matches
2797 /// an existing declaration.
2798 Ovl_Match,
2799
2800 /// This is not an overload because the lookup results contain a
2801 /// non-function.
2802 Ovl_NonFunction
2803 };
2804 OverloadKind CheckOverload(Scope *S,
2805 FunctionDecl *New,
2806 const LookupResult &OldDecls,
2807 NamedDecl *&OldDecl,
2808 bool IsForUsingDecl);
2809 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2810 bool ConsiderCudaAttrs = true);
2811
2812 ImplicitConversionSequence
2813 TryImplicitConversion(Expr *From, QualType ToType,
2814 bool SuppressUserConversions,
2815 bool AllowExplicit,
2816 bool InOverloadResolution,
2817 bool CStyle,
2818 bool AllowObjCWritebackConversion);
2819
2820 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2821 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2822 bool IsComplexPromotion(QualType FromType, QualType ToType);
2823 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2824 bool InOverloadResolution,
2825 QualType& ConvertedType, bool &IncompatibleObjC);
2826 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2827 QualType& ConvertedType, bool &IncompatibleObjC);
2828 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2829 QualType &ConvertedType);
2830 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2831 QualType& ConvertedType);
2832 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2833 const FunctionProtoType *NewType,
2834 unsigned *ArgPos = nullptr);
2835 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2836 QualType FromType, QualType ToType);
2837
2838 void maybeExtendBlockObject(ExprResult &E);
2839 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2840 bool CheckPointerConversion(Expr *From, QualType ToType,
2841 CastKind &Kind,
2842 CXXCastPath& BasePath,
2843 bool IgnoreBaseAccess,
2844 bool Diagnose = true);
2845 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2846 bool InOverloadResolution,
2847 QualType &ConvertedType);
2848 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2849 CastKind &Kind,
2850 CXXCastPath &BasePath,
2851 bool IgnoreBaseAccess);
2852 bool IsQualificationConversion(QualType FromType, QualType ToType,
2853 bool CStyle, bool &ObjCLifetimeConversion);
2854 bool IsFunctionConversion(QualType FromType, QualType ToType,
2855 QualType &ResultTy);
2856 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2857 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2858
2859 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2860 const VarDecl *NRVOCandidate,
2861 QualType ResultType,
2862 Expr *Value,
2863 bool AllowNRVO = true);
2864
2865 bool CanPerformAggregateInitializationForOverloadResolution(
2866 const InitializedEntity &Entity, InitListExpr *From);
2867
2868 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2869 ExprResult Init);
2870 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2871 SourceLocation EqualLoc,
2872 ExprResult Init,
2873 bool TopLevelOfInitList = false,
2874 bool AllowExplicit = false);
2875 ExprResult PerformObjectArgumentInitialization(Expr *From,
2876 NestedNameSpecifier *Qualifier,
2877 NamedDecl *FoundDecl,
2878 CXXMethodDecl *Method);
2879
2880 /// Check that the lifetime of the initializer (and its subobjects) is
2881 /// sufficient for initializing the entity, and perform lifetime extension
2882 /// (when permitted) if not.
2883 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
2884
2885 ExprResult PerformContextuallyConvertToBool(Expr *From);
2886 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2887
2888 /// Contexts in which a converted constant expression is required.
2889 enum CCEKind {
2890 CCEK_CaseValue, ///< Expression in a case label.
2891 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2892 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2893 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2894 CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
2895 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
2896 };
2897 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2898 llvm::APSInt &Value, CCEKind CCE);
2899 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2900 APValue &Value, CCEKind CCE);
2901
2902 /// Abstract base class used to perform a contextual implicit
2903 /// conversion from an expression to any type passing a filter.
2904 class ContextualImplicitConverter {
2905 public:
2906 bool Suppress;
2907 bool SuppressConversion;
2908
2909 ContextualImplicitConverter(bool Suppress = false,
2910 bool SuppressConversion = false)
2911 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2912
2913 /// Determine whether the specified type is a valid destination type
2914 /// for this conversion.
2915 virtual bool match(QualType T) = 0;
2916
2917 /// Emits a diagnostic complaining that the expression does not have
2918 /// integral or enumeration type.
2919 virtual SemaDiagnosticBuilder
2920 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2921
2922 /// Emits a diagnostic when the expression has incomplete class type.
2923 virtual SemaDiagnosticBuilder
2924 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2925
2926 /// Emits a diagnostic when the only matching conversion function
2927 /// is explicit.
2928 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2929 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2930
2931 /// Emits a note for the explicit conversion function.
2932 virtual SemaDiagnosticBuilder
2933 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2934
2935 /// Emits a diagnostic when there are multiple possible conversion
2936 /// functions.
2937 virtual SemaDiagnosticBuilder
2938 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2939
2940 /// Emits a note for one of the candidate conversions.
2941 virtual SemaDiagnosticBuilder
2942 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2943
2944 /// Emits a diagnostic when we picked a conversion function
2945 /// (for cases when we are not allowed to pick a conversion function).
2946 virtual SemaDiagnosticBuilder diagnoseConversion(
2947 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2948
2949 virtual ~ContextualImplicitConverter() {}
2950 };
2951
2952 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2953 bool AllowScopedEnumerations;
2954
2955 public:
2956 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2957 bool Suppress, bool SuppressConversion)
2958 : ContextualImplicitConverter(Suppress, SuppressConversion),
2959 AllowScopedEnumerations(AllowScopedEnumerations) {}
2960
2961 /// Match an integral or (possibly scoped) enumeration type.
2962 bool match(QualType T) override;
2963
2964 SemaDiagnosticBuilder
2965 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2966 return diagnoseNotInt(S, Loc, T);
2967 }
2968
2969 /// Emits a diagnostic complaining that the expression does not have
2970 /// integral or enumeration type.
2971 virtual SemaDiagnosticBuilder
2972 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2973 };
2974
2975 /// Perform a contextual implicit conversion.
2976 ExprResult PerformContextualImplicitConversion(
2977 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2978
2979
2980 enum ObjCSubscriptKind {
2981 OS_Array,
2982 OS_Dictionary,
2983 OS_Error
2984 };
2985 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2986
2987 // Note that LK_String is intentionally after the other literals, as
2988 // this is used for diagnostics logic.
2989 enum ObjCLiteralKind {
2990 LK_Array,
2991 LK_Dictionary,
2992 LK_Numeric,
2993 LK_Boxed,
2994 LK_String,
2995 LK_Block,
2996 LK_None
2997 };
2998 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2999
3000 ExprResult PerformObjectMemberConversion(Expr *From,
3001 NestedNameSpecifier *Qualifier,
3002 NamedDecl *FoundDecl,
3003 NamedDecl *Member);
3004
3005 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3006 // TODO: make this is a typesafe union.
3007 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3008 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3009
3010 using ADLCallKind = CallExpr::ADLCallKind;
3011
3012 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3013 ArrayRef<Expr *> Args,
3014 OverloadCandidateSet &CandidateSet,
3015 bool SuppressUserConversions = false,
3016 bool PartialOverloading = false,
3017 bool AllowExplicit = true,
3018 bool AllowExplicitConversion = false,
3019 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3020 ConversionSequenceList EarlyConversions = None);
3021 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3022 ArrayRef<Expr *> Args,
3023 OverloadCandidateSet &CandidateSet,
3024 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3025 bool SuppressUserConversions = false,
3026 bool PartialOverloading = false,
3027 bool FirstArgumentIsBase = false);
3028 void AddMethodCandidate(DeclAccessPair FoundDecl,
3029 QualType ObjectType,
3030 Expr::Classification ObjectClassification,
3031 ArrayRef<Expr *> Args,
3032 OverloadCandidateSet& CandidateSet,
3033 bool SuppressUserConversion = false);
3034 void AddMethodCandidate(CXXMethodDecl *Method,
3035 DeclAccessPair FoundDecl,
3036 CXXRecordDecl *ActingContext, QualType ObjectType,
3037 Expr::Classification ObjectClassification,
3038 ArrayRef<Expr *> Args,
3039 OverloadCandidateSet& CandidateSet,
3040 bool SuppressUserConversions = false,
3041 bool PartialOverloading = false,
3042 ConversionSequenceList EarlyConversions = None);
3043 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3044 DeclAccessPair FoundDecl,
3045 CXXRecordDecl *ActingContext,
3046 TemplateArgumentListInfo *ExplicitTemplateArgs,
3047 QualType ObjectType,
3048 Expr::Classification ObjectClassification,
3049 ArrayRef<Expr *> Args,
3050 OverloadCandidateSet& CandidateSet,
3051 bool SuppressUserConversions = false,
3052 bool PartialOverloading = false);
3053 void AddTemplateOverloadCandidate(
3054 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3055 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3056 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3057 bool PartialOverloading = false, bool AllowExplicit = true,
3058 ADLCallKind IsADLCandidate = ADLCallKind::NotADL);
3059 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
3060 ArrayRef<QualType> ParamTypes,
3061 ArrayRef<Expr *> Args,
3062 OverloadCandidateSet &CandidateSet,
3063 ConversionSequenceList &Conversions,
3064 bool SuppressUserConversions,
3065 CXXRecordDecl *ActingContext = nullptr,
3066 QualType ObjectType = QualType(),
3067 Expr::Classification
3068 ObjectClassification = {});
3069 void AddConversionCandidate(
3070 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3071 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3072 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3073 bool AllowExplicit, bool AllowResultConversion = true);
3074 void AddTemplateConversionCandidate(
3075 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3076 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3077 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3078 bool AllowExplicit, bool AllowResultConversion = true);
3079 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3080 DeclAccessPair FoundDecl,
3081 CXXRecordDecl *ActingContext,
3082 const FunctionProtoType *Proto,
3083 Expr *Object, ArrayRef<Expr *> Args,
3084 OverloadCandidateSet& CandidateSet);
3085 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3086 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3087 OverloadCandidateSet& CandidateSet,
3088 SourceRange OpRange = SourceRange());
3089 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3090 OverloadCandidateSet& CandidateSet,
3091 bool IsAssignmentOperator = false,
3092 unsigned NumContextualBoolArguments = 0);
3093 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3094 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3095 OverloadCandidateSet& CandidateSet);
3096 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3097 SourceLocation Loc,
3098 ArrayRef<Expr *> Args,
3099 TemplateArgumentListInfo *ExplicitTemplateArgs,
3100 OverloadCandidateSet& CandidateSet,
3101 bool PartialOverloading = false);
3102
3103 // Emit as a 'note' the specific overload candidate
3104 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
3105 QualType DestType = QualType(),
3106 bool TakingAddress = false);
3107
3108 // Emit as a series of 'note's all template and non-templates identified by
3109 // the expression Expr
3110 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3111 bool TakingAddress = false);
3112
3113 /// Check the enable_if expressions on the given function. Returns the first
3114 /// failing attribute, or NULL if they were all successful.
3115 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3116 bool MissingImplicitThis = false);
3117
3118 /// Find the failed Boolean condition within a given Boolean
3119 /// constant expression, and describe it with a string.
3120 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3121
3122 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3123 /// non-ArgDependent DiagnoseIfAttrs.
3124 ///
3125 /// Argument-dependent diagnose_if attributes should be checked each time a
3126 /// function is used as a direct callee of a function call.
3127 ///
3128 /// Returns true if any errors were emitted.
3129 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3130 const Expr *ThisArg,
3131 ArrayRef<const Expr *> Args,
3132 SourceLocation Loc);
3133
3134 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3135 /// ArgDependent DiagnoseIfAttrs.
3136 ///
3137 /// Argument-independent diagnose_if attributes should be checked on every use
3138 /// of a function.
3139 ///
3140 /// Returns true if any errors were emitted.
3141 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3142 SourceLocation Loc);
3143
3144 /// Returns whether the given function's address can be taken or not,
3145 /// optionally emitting a diagnostic if the address can't be taken.
3146 ///
3147 /// Returns false if taking the address of the function is illegal.
3148 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3149 bool Complain = false,
3150 SourceLocation Loc = SourceLocation());
3151
3152 // [PossiblyAFunctionType] --> [Return]
3153 // NonFunctionType --> NonFunctionType
3154 // R (A) --> R(A)
3155 // R (*)(A) --> R (A)
3156 // R (&)(A) --> R (A)
3157 // R (S::*)(A) --> R (A)
3158 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3159
3160 FunctionDecl *
3161 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3162 QualType TargetType,
3163 bool Complain,
3164 DeclAccessPair &Found,
3165 bool *pHadMultipleCandidates = nullptr);
3166
3167 FunctionDecl *
3168 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
3169 DeclAccessPair &FoundResult);
3170
3171 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
3172 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3173
3174 FunctionDecl *
3175 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3176 bool Complain = false,
3177 DeclAccessPair *Found = nullptr);
3178
3179 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3180 ExprResult &SrcExpr,
3181 bool DoFunctionPointerConverion = false,
3182 bool Complain = false,
3183 SourceRange OpRangeForComplaining = SourceRange(),
3184 QualType DestTypeForComplaining = QualType(),
3185 unsigned DiagIDForComplaining = 0);
3186
3187
3188 Expr *FixOverloadedFunctionReference(Expr *E,
3189 DeclAccessPair FoundDecl,
3190 FunctionDecl *Fn);
3191 ExprResult FixOverloadedFunctionReference(ExprResult,
3192 DeclAccessPair FoundDecl,
3193 FunctionDecl *Fn);
3194
3195 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3196 ArrayRef<Expr *> Args,
3197 OverloadCandidateSet &CandidateSet,
3198 bool PartialOverloading = false);
3199
3200 // An enum used to represent the different possible results of building a
3201 // range-based for loop.
3202 enum ForRangeStatus {
3203 FRS_Success,
3204 FRS_NoViableFunction,
3205 FRS_DiagnosticIssued
3206 };
3207
3208 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3209 SourceLocation RangeLoc,
3210 const DeclarationNameInfo &NameInfo,
3211 LookupResult &MemberLookup,
3212 OverloadCandidateSet *CandidateSet,
3213 Expr *Range, ExprResult *CallExpr);
3214
3215 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3216 UnresolvedLookupExpr *ULE,
3217 SourceLocation LParenLoc,
3218 MultiExprArg Args,
3219 SourceLocation RParenLoc,
3220 Expr *ExecConfig,
3221 bool AllowTypoCorrection=true,
3222 bool CalleesAddressIsTaken=false);
3223
3224 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3225 MultiExprArg Args, SourceLocation RParenLoc,
3226 OverloadCandidateSet *CandidateSet,
3227 ExprResult *Result);
3228
3229 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3230 UnaryOperatorKind Opc,
3231 const UnresolvedSetImpl &Fns,
3232 Expr *input, bool RequiresADL = true);
3233
3234 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3235 BinaryOperatorKind Opc,
3236 const UnresolvedSetImpl &Fns,
3237 Expr *LHS, Expr *RHS,
3238 bool RequiresADL = true);
3239
3240 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3241 SourceLocation RLoc,
3242 Expr *Base,Expr *Idx);
3243
3244 ExprResult
3245 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3246 SourceLocation LParenLoc,
3247 MultiExprArg Args,
3248 SourceLocation RParenLoc);
3249 ExprResult
3250 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3251 MultiExprArg Args,
3252 SourceLocation RParenLoc);
3253
3254 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3255 SourceLocation OpLoc,
3256 bool *NoArrowOperatorFound = nullptr);
3257
3258 /// CheckCallReturnType - Checks that a call expression's return type is
3259 /// complete. Returns true on failure. The location passed in is the location
3260 /// that best represents the call.
3261 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3262 CallExpr *CE, FunctionDecl *FD);
3263
3264 /// Helpers for dealing with blocks and functions.
3265 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3266 bool CheckParameterNames);
3267 void CheckCXXDefaultArguments(FunctionDecl *FD);
3268 void CheckExtraCXXDefaultArguments(Declarator &D);
3269 Scope *getNonFieldDeclScope(Scope *S);
3270
3271 /// \name Name lookup
3272 ///
3273 /// These routines provide name lookup that is used during semantic
3274 /// analysis to resolve the various kinds of names (identifiers,
3275 /// overloaded operator names, constructor names, etc.) into zero or
3276 /// more declarations within a particular scope. The major entry
3277 /// points are LookupName, which performs unqualified name lookup,
3278 /// and LookupQualifiedName, which performs qualified name lookup.
3279 ///
3280 /// All name lookup is performed based on some specific criteria,
3281 /// which specify what names will be visible to name lookup and how
3282 /// far name lookup should work. These criteria are important both
3283 /// for capturing language semantics (certain lookups will ignore
3284 /// certain names, for example) and for performance, since name
3285 /// lookup is often a bottleneck in the compilation of C++. Name
3286 /// lookup criteria is specified via the LookupCriteria enumeration.
3287 ///
3288 /// The results of name lookup can vary based on the kind of name
3289 /// lookup performed, the current language, and the translation
3290 /// unit. In C, for example, name lookup will either return nothing
3291 /// (no entity found) or a single declaration. In C++, name lookup
3292 /// can additionally refer to a set of overloaded functions or
3293 /// result in an ambiguity. All of the possible results of name
3294 /// lookup are captured by the LookupResult class, which provides
3295 /// the ability to distinguish among them.
3296 //@{
3297
3298 /// Describes the kind of name lookup to perform.
3299 enum LookupNameKind {
3300 /// Ordinary name lookup, which finds ordinary names (functions,
3301 /// variables, typedefs, etc.) in C and most kinds of names
3302 /// (functions, variables, members, types, etc.) in C++.
3303 LookupOrdinaryName = 0,
3304 /// Tag name lookup, which finds the names of enums, classes,
3305 /// structs, and unions.
3306 LookupTagName,
3307 /// Label name lookup.
3308 LookupLabel,
3309 /// Member name lookup, which finds the names of
3310 /// class/struct/union members.
3311 LookupMemberName,
3312 /// Look up of an operator name (e.g., operator+) for use with
3313 /// operator overloading. This lookup is similar to ordinary name
3314 /// lookup, but will ignore any declarations that are class members.
3315 LookupOperatorName,
3316 /// Look up of a name that precedes the '::' scope resolution
3317 /// operator in C++. This lookup completely ignores operator, object,
3318 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3319 LookupNestedNameSpecifierName,
3320 /// Look up a namespace name within a C++ using directive or
3321 /// namespace alias definition, ignoring non-namespace names (C++
3322 /// [basic.lookup.udir]p1).
3323 LookupNamespaceName,
3324 /// Look up all declarations in a scope with the given name,
3325 /// including resolved using declarations. This is appropriate
3326 /// for checking redeclarations for a using declaration.
3327 LookupUsingDeclName,
3328 /// Look up an ordinary name that is going to be redeclared as a
3329 /// name with linkage. This lookup ignores any declarations that
3330 /// are outside of the current scope unless they have linkage. See
3331 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3332 LookupRedeclarationWithLinkage,
3333 /// Look up a friend of a local class. This lookup does not look
3334 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3335 LookupLocalFriendName,
3336 /// Look up the name of an Objective-C protocol.
3337 LookupObjCProtocolName,
3338 /// Look up implicit 'self' parameter of an objective-c method.
3339 LookupObjCImplicitSelfParam,
3340 /// Look up the name of an OpenMP user-defined reduction operation.
3341 LookupOMPReductionName,
3342 /// Look up the name of an OpenMP user-defined mapper.
3343 LookupOMPMapperName,
3344 /// Look up any declaration with any name.
3345 LookupAnyName
3346 };
3347
3348 /// Specifies whether (or how) name lookup is being performed for a
3349 /// redeclaration (vs. a reference).
3350 enum RedeclarationKind {
3351 /// The lookup is a reference to this name that is not for the
3352 /// purpose of redeclaring the name.
3353 NotForRedeclaration = 0,
3354 /// The lookup results will be used for redeclaration of a name,
3355 /// if an entity by that name already exists and is visible.
3356 ForVisibleRedeclaration,
3357 /// The lookup results will be used for redeclaration of a name
3358 /// with external linkage; non-visible lookup results with external linkage
3359 /// may also be found.
3360 ForExternalRedeclaration
3361 };
3362
3363 RedeclarationKind forRedeclarationInCurContext() {
3364 // A declaration with an owning module for linkage can never link against
3365 // anything that is not visible. We don't need to check linkage here; if
3366 // the context has internal linkage, redeclaration lookup won't find things
3367 // from other TUs, and we can't safely compute linkage yet in general.
3368 if (cast<Decl>(CurContext)
3369 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3370 return ForVisibleRedeclaration;
3371 return ForExternalRedeclaration;
3372 }
3373
3374 /// The possible outcomes of name lookup for a literal operator.
3375 enum LiteralOperatorLookupResult {
3376 /// The lookup resulted in an error.
3377 LOLR_Error,
3378 /// The lookup found no match but no diagnostic was issued.
3379 LOLR_ErrorNoDiagnostic,
3380 /// The lookup found a single 'cooked' literal operator, which
3381 /// expects a normal literal to be built and passed to it.
3382 LOLR_Cooked,
3383 /// The lookup found a single 'raw' literal operator, which expects
3384 /// a string literal containing the spelling of the literal token.
3385 LOLR_Raw,
3386 /// The lookup found an overload set of literal operator templates,
3387 /// which expect the characters of the spelling of the literal token to be
3388 /// passed as a non-type template argument pack.
3389 LOLR_Template,
3390 /// The lookup found an overload set of literal operator templates,
3391 /// which expect the character type and characters of the spelling of the
3392 /// string literal token to be passed as template arguments.
3393 LOLR_StringTemplate
3394 };
3395
3396 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3397 CXXSpecialMember SM,
3398 bool ConstArg,
3399 bool VolatileArg,
3400 bool RValueThis,
3401 bool ConstThis,
3402 bool VolatileThis);
3403
3404 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3405 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3406 TypoRecoveryCallback;
3407
3408private:
3409 bool CppLookupName(LookupResult &R, Scope *S);
3410
3411 struct TypoExprState {
3412 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3413 TypoDiagnosticGenerator DiagHandler;
3414 TypoRecoveryCallback RecoveryHandler;
3415 TypoExprState();
3416 TypoExprState(TypoExprState &&other) noexcept;
3417 TypoExprState &operator=(TypoExprState &&other) noexcept;
3418 };
3419
3420 /// The set of unhandled TypoExprs and their associated state.
3421 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3422
3423 /// Creates a new TypoExpr AST node.
3424 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3425 TypoDiagnosticGenerator TDG,
3426 TypoRecoveryCallback TRC);
3427
3428 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3429 //
3430 // The boolean value will be true to indicate that the namespace was loaded
3431 // from an AST/PCH file, or false otherwise.
3432 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3433
3434 /// Whether we have already loaded known namespaces from an extenal
3435 /// source.
3436 bool LoadedExternalKnownNamespaces;
3437
3438 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3439 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3440 /// should be skipped entirely.
3441 std::unique_ptr<TypoCorrectionConsumer>
3442 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3443 Sema::LookupNameKind LookupKind, Scope *S,
3444 CXXScopeSpec *SS,
3445 CorrectionCandidateCallback &CCC,
3446 DeclContext *MemberContext, bool EnteringContext,
3447 const ObjCObjectPointerType *OPT,
3448 bool ErrorRecovery);
3449
3450public:
3451 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3452
3453 /// Clears the state of the given TypoExpr.
3454 void clearDelayedTypo(TypoExpr *TE);
3455
3456 /// Look up a name, looking for a single declaration. Return
3457 /// null if the results were absent, ambiguous, or overloaded.
3458 ///
3459 /// It is preferable to use the elaborated form and explicitly handle
3460 /// ambiguity and overloaded.
3461 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3462 SourceLocation Loc,
3463 LookupNameKind NameKind,
3464 RedeclarationKind Redecl
3465 = NotForRedeclaration);
3466 bool LookupBuiltin(LookupResult &R);
3467 bool LookupName(LookupResult &R, Scope *S,
3468 bool AllowBuiltinCreation = false);
3469 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3470 bool InUnqualifiedLookup = false);
3471 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3472 CXXScopeSpec &SS);
3473 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3474 bool AllowBuiltinCreation = false,
3475 bool EnteringContext = false);
3476 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3477 RedeclarationKind Redecl
3478 = NotForRedeclaration);
3479 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3480
3481 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3482 QualType T1, QualType T2,
3483 UnresolvedSetImpl &Functions);
3484
3485 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3486 SourceLocation GnuLabelLoc = SourceLocation());
3487
3488 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3489 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3490 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3491 unsigned Quals);
3492 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3493 bool RValueThis, unsigned ThisQuals);
3494 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3495 unsigned Quals);
3496 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3497 bool RValueThis, unsigned ThisQuals);
3498 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3499
3500 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3501 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3502 ArrayRef<QualType> ArgTys,
3503 bool AllowRaw,
3504 bool AllowTemplate,
3505 bool AllowStringTemplate,
3506 bool DiagnoseMissing);
3507 bool isKnownName(StringRef name);
3508
3509 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3510 enum class FunctionEmissionStatus {
3511 Emitted,
3512 CUDADiscarded, // Discarded due to CUDA/HIP hostness
3513 OMPDiscarded, // Discarded due to OpenMP hostness
3514 TemplateDiscarded, // Discarded due to uninstantiated templates
3515 Unknown,
3516 };
3517 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
3518
3519 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3520 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3521
3522 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3523 ArrayRef<Expr *> Args, ADLResult &Functions);
3524
3525 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3526 VisibleDeclConsumer &Consumer,
3527 bool IncludeGlobalScope = true,
3528 bool LoadExternal = true);
3529 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3530 VisibleDeclConsumer &Consumer,
3531 bool IncludeGlobalScope = true,
3532 bool IncludeDependentBases = false,
3533 bool LoadExternal = true);
3534
3535 enum CorrectTypoKind {
3536 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3537 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3538 };
3539
3540 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3541 Sema::LookupNameKind LookupKind,
3542 Scope *S, CXXScopeSpec *SS,
3543 CorrectionCandidateCallback &CCC,
3544 CorrectTypoKind Mode,
3545 DeclContext *MemberContext = nullptr,
3546 bool EnteringContext = false,
3547 const ObjCObjectPointerType *OPT = nullptr,
3548 bool RecordFailure = true);
3549
3550 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3551 Sema::LookupNameKind LookupKind, Scope *S,
3552 CXXScopeSpec *SS,
3553 CorrectionCandidateCallback &CCC,
3554 TypoDiagnosticGenerator TDG,
3555 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3556 DeclContext *MemberContext = nullptr,
3557 bool EnteringContext = false,
3558 const ObjCObjectPointerType *OPT = nullptr);
3559
3560 /// Process any TypoExprs in the given Expr and its children,
3561 /// generating diagnostics as appropriate and returning a new Expr if there
3562 /// were typos that were all successfully corrected and ExprError if one or
3563 /// more typos could not be corrected.
3564 ///
3565 /// \param E The Expr to check for TypoExprs.
3566 ///
3567 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3568 /// initializer.
3569 ///
3570 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3571 /// it is an acceptable/usable result from a single combination of typo
3572 /// corrections. As long as the filter returns ExprError, different
3573 /// combinations of corrections will be tried until all are exhausted.
3574 ExprResult
3575 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3576 llvm::function_ref<ExprResult(Expr *)> Filter =
3577 [](Expr *E) -> ExprResult { return E; });
3578
3579 ExprResult
3580 CorrectDelayedTyposInExpr(Expr *E,
3581 llvm::function_ref<ExprResult(Expr *)> Filter) {
3582 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3583 }
3584
3585 ExprResult
3586 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3587 llvm::function_ref<ExprResult(Expr *)> Filter =
3588 [](Expr *E) -> ExprResult { return E; }) {
3589 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3590 }
3591
3592 ExprResult
3593 CorrectDelayedTyposInExpr(ExprResult ER,
3594 llvm::function_ref<ExprResult(Expr *)> Filter) {
3595 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3596 }
3597
3598 void diagnoseTypo(const TypoCorrection &Correction,
3599 const PartialDiagnostic &TypoDiag,
3600 bool ErrorRecovery = true);
3601
3602 void diagnoseTypo(const TypoCorrection &Correction,
3603 const PartialDiagnostic &TypoDiag,
3604 const PartialDiagnostic &PrevNote,
3605 bool ErrorRecovery = true);
3606
3607 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3608
3609 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3610 ArrayRef<Expr *> Args,
3611 AssociatedNamespaceSet &AssociatedNamespaces,
3612 AssociatedClassSet &AssociatedClasses);
3613
3614 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3615 bool ConsiderLinkage, bool AllowInlineNamespace);
3616
3617 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3618
3619 void DiagnoseAmbiguousLookup(LookupResult &Result);
3620 //@}
3621
3622 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3623 SourceLocation IdLoc,
3624 bool TypoCorrection = false);
3625 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3626 Scope *S, bool ForRedeclaration,
3627 SourceLocation Loc);
3628 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3629 Scope *S);
3630 void AddKnownFunctionAttributes(FunctionDecl *FD);
3631
3632 // More parsing and symbol table subroutines.
3633
3634 void ProcessPragmaWeak(Scope *S, Decl *D);
3635 // Decl attributes - this routine is the top level dispatcher.
3636 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3637 // Helper for delayed processing of attributes.
3638 void ProcessDeclAttributeDelayed(Decl *D,
3639 const ParsedAttributesView &AttrList);
3640 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3641 bool IncludeCXX11Attributes = true);
3642 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3643 const ParsedAttributesView &AttrList);
3644
3645 void checkUnusedDeclAttributes(Declarator &D);
3646
3647 /// Determine if type T is a valid subject for a nonnull and similar
3648 /// attributes. By default, we look through references (the behavior used by
3649 /// nonnull), but if the second parameter is true, then we treat a reference
3650 /// type as valid.
3651 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3652
3653 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3654 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3655 const FunctionDecl *FD = nullptr);
3656 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3657 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3658 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3659 StringRef &Str,
3660 SourceLocation *ArgLocation = nullptr);
3661 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3662 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3663 bool checkMSInheritanceAttrOnDefinition(
3664 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3665 MSInheritanceAttr::Spelling SemanticSpelling);
3666
3667 void CheckAlignasUnderalignment(Decl *D);
3668
3669 /// Adjust the calling convention of a method to be the ABI default if it
3670 /// wasn't specified explicitly. This handles method types formed from
3671 /// function type typedefs and typename template arguments.
3672 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3673 SourceLocation Loc);
3674
3675 // Check if there is an explicit attribute, but only look through parens.
3676 // The intent is to look for an attribute on the current declarator, but not
3677 // one that came from a typedef.
3678 bool hasExplicitCallingConv(QualType T);
3679
3680 /// Get the outermost AttributedType node that sets a calling convention.
3681 /// Valid types should not have multiple attributes with different CCs.
3682 const AttributedType *getCallingConvAttributedType(QualType T) const;
3683
3684 /// Stmt attributes - this routine is the top level dispatcher.
3685 StmtResult ProcessStmtAttributes(Stmt *Stmt,
3686 const ParsedAttributesView &Attrs,
3687 SourceRange Range);
3688
3689 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3690 ObjCMethodDecl *MethodDecl,
3691 bool IsProtocolMethodDecl);
3692
3693 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3694 ObjCMethodDecl *Overridden,
3695 bool IsProtocolMethodDecl);
3696
3697 /// WarnExactTypedMethods - This routine issues a warning if method
3698 /// implementation declaration matches exactly that of its declaration.
3699 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3700 ObjCMethodDecl *MethodDecl,
3701 bool IsProtocolMethodDecl);
3702
3703 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3704
3705 /// CheckImplementationIvars - This routine checks if the instance variables
3706 /// listed in the implelementation match those listed in the interface.
3707 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3708 ObjCIvarDecl **Fields, unsigned nIvars,
3709 SourceLocation Loc);
3710
3711 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3712 /// remains unimplemented in the class or category \@implementation.
3713 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3714 ObjCContainerDecl* IDecl,
3715 bool IncompleteImpl = false);
3716
3717 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3718 /// which must be implemented by this implementation.
3719 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3720 ObjCContainerDecl *CDecl,
3721 bool SynthesizeProperties);
3722
3723 /// Diagnose any null-resettable synthesized setters.
3724 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3725
3726 /// DefaultSynthesizeProperties - This routine default synthesizes all
3727 /// properties which must be synthesized in the class's \@implementation.
3728 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3729 ObjCInterfaceDecl *IDecl,
3730 SourceLocation AtEnd);
3731 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3732
3733 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3734 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3735 /// declared in class 'IFace'.
3736 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3737 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3738
3739 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3740 /// backs the property is not used in the property's accessor.
3741 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3742 const ObjCImplementationDecl *ImplD);
3743
3744 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3745 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3746 /// It also returns ivar's property on success.
3747 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3748 const ObjCPropertyDecl *&PDecl) const;
3749
3750 /// Called by ActOnProperty to handle \@property declarations in
3751 /// class extensions.
3752 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3753 SourceLocation AtLoc,
3754 SourceLocation LParenLoc,
3755 FieldDeclarator &FD,
3756 Selector GetterSel,
3757 SourceLocation GetterNameLoc,
3758 Selector SetterSel,
3759 SourceLocation SetterNameLoc,
3760 const bool isReadWrite,
3761 unsigned &Attributes,
3762 const unsigned AttributesAsWritten,
3763 QualType T,
3764 TypeSourceInfo *TSI,
3765 tok::ObjCKeywordKind MethodImplKind);
3766
3767 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3768 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3769 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3770 ObjCContainerDecl *CDecl,
3771 SourceLocation AtLoc,
3772 SourceLocation LParenLoc,
3773 FieldDeclarator &FD,
3774 Selector GetterSel,
3775 SourceLocation GetterNameLoc,
3776 Selector SetterSel,
3777 SourceLocation SetterNameLoc,
3778 const bool isReadWrite,
3779 const unsigned Attributes,
3780 const unsigned AttributesAsWritten,
3781 QualType T,
3782 TypeSourceInfo *TSI,
3783 tok::ObjCKeywordKind MethodImplKind,
3784 DeclContext *lexicalDC = nullptr);
3785
3786 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3787 /// warning) when atomic property has one but not the other user-declared
3788 /// setter or getter.
3789 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3790 ObjCInterfaceDecl* IDecl);
3791
3792 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3793
3794 void DiagnoseMissingDesignatedInitOverrides(
3795 const ObjCImplementationDecl *ImplD,
3796 const ObjCInterfaceDecl *IFD);
3797
3798 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3799
3800 enum MethodMatchStrategy {
3801 MMS_loose,
3802 MMS_strict
3803 };
3804
3805 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3806 /// true, or false, accordingly.
3807 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3808 const ObjCMethodDecl *PrevMethod,
3809 MethodMatchStrategy strategy = MMS_strict);
3810
3811 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3812 /// or protocol against those declared in their implementations.
3813 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3814 const SelectorSet &ClsMap,
3815 SelectorSet &InsMapSeen,
3816 SelectorSet &ClsMapSeen,
3817 ObjCImplDecl* IMPDecl,
3818 ObjCContainerDecl* IDecl,
3819 bool &IncompleteImpl,
3820 bool ImmediateClass,
3821 bool WarnCategoryMethodImpl=false);
3822
3823 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3824 /// category matches with those implemented in its primary class and
3825 /// warns each time an exact match is found.
3826 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3827
3828 /// Add the given method to the list of globally-known methods.
3829 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3830
3831private:
3832 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3833 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3834 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3835
3836 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3837 /// optionally warns if there are multiple signatures.
3838 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3839 bool receiverIdOrClass,
3840 bool instance);
3841
3842public:
3843 /// - Returns instance or factory methods in global method pool for
3844 /// given selector. It checks the desired kind first, if none is found, and
3845 /// parameter checkTheOther is set, it then checks the other kind. If no such
3846 /// method or only one method is found, function returns false; otherwise, it
3847 /// returns true.
3848 bool
3849 CollectMultipleMethodsInGlobalPool(Selector Sel,
3850 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3851 bool InstanceFirst, bool CheckTheOther,
3852 const ObjCObjectType *TypeBound = nullptr);
3853
3854 bool
3855 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3856 SourceRange R, bool receiverIdOrClass,
3857 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3858
3859 void
3860 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3861 Selector Sel, SourceRange R,
3862 bool receiverIdOrClass);
3863
3864private:
3865 /// - Returns a selector which best matches given argument list or
3866 /// nullptr if none could be found
3867 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3868 bool IsInstance,
3869 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3870
3871
3872 /// Record the typo correction failure and return an empty correction.
3873 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3874 bool RecordFailure = true) {
3875 if (RecordFailure)
3876 TypoCorrectionFailures[Typo].insert(TypoLoc);
3877 return TypoCorrection();
3878 }
3879
3880public:
3881 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3882 /// unit are added to a global pool. This allows us to efficiently associate
3883 /// a selector with a method declaraation for purposes of typechecking
3884 /// messages sent to "id" (where the class of the object is unknown).
3885 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3886 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3887 }
3888
3889 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3890 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3891 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3892 }
3893
3894 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3895 /// pool.
3896 void AddAnyMethodToGlobalPool(Decl *D);
3897
3898 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3899 /// there are multiple signatures.
3900 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3901 bool receiverIdOrClass=false) {
3902 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3903 /*instance*/true);
3904 }
3905
3906 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3907 /// there are multiple signatures.
3908 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3909 bool receiverIdOrClass=false) {
3910 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3911 /*instance*/false);
3912 }
3913
3914 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3915 QualType ObjectType=QualType());
3916 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3917 /// implementation.
3918 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3919
3920 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3921 /// initialization.
3922 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3923 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3924
3925 //===--------------------------------------------------------------------===//
3926 // Statement Parsing Callbacks: SemaStmt.cpp.
3927public:
3928 class FullExprArg {
3929 public:
3930 FullExprArg() : E(nullptr) { }
3931 FullExprArg(Sema &actions) : E(nullptr) { }
3932
3933 ExprResult release() {
3934 return E;
3935 }
3936
3937 Expr *get() const { return E; }
3938
3939 Expr *operator->() {
3940 return E;
3941 }
3942
3943 private:
3944 // FIXME: No need to make the entire Sema class a friend when it's just
3945 // Sema::MakeFullExpr that needs access to the constructor below.
3946 friend class Sema;
3947
3948 explicit FullExprArg(Expr *expr) : E(expr) {}
3949
3950 Expr *E;
3951 };
3952
3953 FullExprArg MakeFullExpr(Expr *Arg) {
3954 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3955 }
3956 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3957 return FullExprArg(
3958 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
3959 }
3960 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3961 ExprResult FE =
3962 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3963 /*DiscardedValue*/ true);
3964 return FullExprArg(FE.get());
3965 }
3966
3967 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
3968 StmtResult ActOnExprStmtError();
3969
3970 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3971 bool HasLeadingEmptyMacro = false);
3972
3973 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3974 void ActOnFinishOfCompoundStmt();
3975 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3976 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3977
3978 /// A RAII object to enter scope of a compound statement.
3979 class CompoundScopeRAII {
3980 public:
3981 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3982 S.ActOnStartOfCompoundStmt(IsStmtExpr);
3983 }
3984
3985 ~CompoundScopeRAII() {
3986 S.ActOnFinishOfCompoundStmt();
3987 }
3988
3989 private:
3990 Sema &S;
3991 };
3992
3993 /// An RAII helper that pops function a function scope on exit.
3994 struct FunctionScopeRAII {
3995 Sema &S;
3996 bool Active;
3997 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3998 ~FunctionScopeRAII() {
3999 if (Active)
4000 S.PopFunctionScopeInfo();
4001 }
4002 void disable() { Active = false; }
4003 };
4004
4005 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4006 SourceLocation StartLoc,
4007 SourceLocation EndLoc);
4008 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4009 StmtResult ActOnForEachLValueExpr(Expr *E);
4010 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4011 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4012 SourceLocation DotDotDotLoc, ExprResult RHS,
4013 SourceLocation ColonLoc);
4014 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4015
4016 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4017 SourceLocation ColonLoc,
4018 Stmt *SubStmt, Scope *CurScope);
4019 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4020 SourceLocation ColonLoc, Stmt *SubStmt);
4021
4022 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4023 ArrayRef<const Attr*> Attrs,
4024 Stmt *SubStmt);
4025
4026 class ConditionResult;
4027 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4028 Stmt *InitStmt,
4029 ConditionResult Cond, Stmt *ThenVal,
4030 SourceLocation ElseLoc, Stmt *ElseVal);
4031 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4032 Stmt *InitStmt,
4033 ConditionResult Cond, Stmt *ThenVal,
4034 SourceLocation ElseLoc, Stmt *ElseVal);
4035 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4036 Stmt *InitStmt,
4037 ConditionResult Cond);
4038 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4039 Stmt *Switch, Stmt *Body);
4040 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
4041 Stmt *Body);
4042 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4043 SourceLocation WhileLoc, SourceLocation CondLParen,
4044 Expr *Cond, SourceLocation CondRParen);
4045
4046 StmtResult ActOnForStmt(SourceLocation ForLoc,
4047 SourceLocation LParenLoc,
4048 Stmt *First,
4049 ConditionResult Second,
4050 FullExprArg Third,
4051 SourceLocation RParenLoc,
4052 Stmt *Body);
4053 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4054 Expr *collection);
4055 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4056 Stmt *First, Expr *collection,
4057 SourceLocation RParenLoc);
4058 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4059
4060 enum BuildForRangeKind {
4061 /// Initial building of a for-range statement.
4062 BFRK_Build,
4063 /// Instantiation or recovery rebuild of a for-range statement. Don't
4064 /// attempt any typo-correction.
4065 BFRK_Rebuild,
4066 /// Determining whether a for-range statement could be built. Avoid any
4067 /// unnecessary or irreversible actions.
4068 BFRK_Check
4069 };
4070
4071 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4072 SourceLocation CoawaitLoc,
4073 Stmt *InitStmt,
4074 Stmt *LoopVar,
4075 SourceLocation ColonLoc, Expr *Collection,
4076 SourceLocation RParenLoc,
4077 BuildForRangeKind Kind);
4078 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4079 SourceLocation CoawaitLoc,
4080 Stmt *InitStmt,
4081 SourceLocation ColonLoc,
4082 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4083 Expr *Cond, Expr *Inc,
4084 Stmt *LoopVarDecl,
4085 SourceLocation RParenLoc,
4086 BuildForRangeKind Kind);
4087 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4088
4089 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4090 SourceLocation LabelLoc,
4091 LabelDecl *TheDecl);
4092 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4093 SourceLocation StarLoc,
4094 Expr *DestExp);
4095 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4096 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4097
4098 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4099 CapturedRegionKind Kind, unsigned NumParams);
4100 typedef std::pair<StringRef, QualType> CapturedParamNameType;
4101 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4102 CapturedRegionKind Kind,
4103 ArrayRef<CapturedParamNameType> Params,
4104 unsigned OpenMPCaptureLevel = 0);
4105 StmtResult ActOnCapturedRegionEnd(Stmt *S);
4106 void ActOnCapturedRegionError();
4107 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4108 SourceLocation Loc,
4109 unsigned NumParams);
4110
4111 enum CopyElisionSemanticsKind {
4112 CES_Strict = 0,
4113 CES_AllowParameters = 1,
4114 CES_AllowDifferentTypes = 2,
4115 CES_AllowExceptionVariables = 4,
4116 CES_FormerDefault = (CES_AllowParameters),
4117 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4118 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4119 CES_AllowExceptionVariables),
4120 };
4121
4122 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4123 CopyElisionSemanticsKind CESK);
4124 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4125 CopyElisionSemanticsKind CESK);
4126
4127 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4128 Scope *CurScope);
4129 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4130 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4131
4132 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4133 bool IsVolatile, unsigned NumOutputs,
4134 unsigned NumInputs, IdentifierInfo **Names,
4135 MultiExprArg Constraints, MultiExprArg Exprs,
4136 Expr *AsmString, MultiExprArg Clobbers,
4137 unsigned NumLabels,
4138 SourceLocation RParenLoc);
4139
4140 void FillInlineAsmIdentifierInfo(Expr *Res,
4141 llvm::InlineAsmIdentifierInfo &Info);
4142 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4143 SourceLocation TemplateKWLoc,
4144 UnqualifiedId &Id,
4145 bool IsUnevaluatedContext);
4146 bool LookupInlineAsmField(StringRef Base, StringRef Member,
4147 unsigned &Offset, SourceLocation AsmLoc);
4148 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4149 SourceLocation AsmLoc);
4150 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4151 ArrayRef<Token> AsmToks,
4152 StringRef AsmString,
4153 unsigned NumOutputs, unsigned NumInputs,
4154 ArrayRef<StringRef> Constraints,
4155 ArrayRef<StringRef> Clobbers,
4156 ArrayRef<Expr*> Exprs,
4157 SourceLocation EndLoc);
4158 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4159 SourceLocation Location,
4160 bool AlwaysCreate);
4161
4162 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4163 SourceLocation StartLoc,
4164 SourceLocation IdLoc, IdentifierInfo *Id,
4165 bool Invalid = false);
4166
4167 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4168
4169 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4170 Decl *Parm, Stmt *Body);
4171
4172 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4173
4174 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4175 MultiStmtArg Catch, Stmt *Finally);
4176
4177 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4178 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4179 Scope *CurScope);
4180 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4181 Expr *operand);
4182 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4183 Expr *SynchExpr,
4184 Stmt *SynchBody);
4185
4186 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4187
4188 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4189 SourceLocation StartLoc,
4190 SourceLocation IdLoc,
4191 IdentifierInfo *Id);
4192
4193 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4194
4195 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4196 Decl *ExDecl, Stmt *HandlerBlock);
4197 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4198 ArrayRef<Stmt *> Handlers);
4199
4200 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4201 SourceLocation TryLoc, Stmt *TryBlock,
4202 Stmt *Handler);
4203 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4204 Expr *FilterExpr,
4205 Stmt *Block);
4206 void ActOnStartSEHFinallyBlock();
4207 void ActOnAbortSEHFinallyBlock();
4208 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4209 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4210
4211 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4212
4213 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4214
4215 /// If it's a file scoped decl that must warn if not used, keep track
4216 /// of it.
4217 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4218
4219 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4220 /// whose result is unused, warn.
4221 void DiagnoseUnusedExprResult(const Stmt *S);
4222 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4223 void DiagnoseUnusedDecl(const NamedDecl *ND);
4224
4225 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4226 /// statement as a \p Body, and it is located on the same line.
4227 ///
4228 /// This helps prevent bugs due to typos, such as:
4229 /// if (condition);
4230 /// do_stuff();
4231 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4232 const Stmt *Body,
4233 unsigned DiagID);
4234
4235 /// Warn if a for/while loop statement \p S, which is followed by
4236 /// \p PossibleBody, has a suspicious null statement as a body.
4237 void DiagnoseEmptyLoopBody(const Stmt *S,
4238 const Stmt *PossibleBody);
4239
4240 /// Warn if a value is moved to itself.
4241 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4242 SourceLocation OpLoc);
4243
4244 /// Warn if we're implicitly casting from a _Nullable pointer type to a
4245 /// _Nonnull one.
4246 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4247 SourceLocation Loc);
4248
4249 /// Warn when implicitly casting 0 to nullptr.
4250 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4251
4252 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4253 return DelayedDiagnostics.push(pool);
4254 }
4255 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4256
4257 typedef ProcessingContextState ParsingClassState;
4258 ParsingClassState PushParsingClass() {
4259 return DelayedDiagnostics.pushUndelayed();
4260 }
4261 void PopParsingClass(ParsingClassState state) {
4262 DelayedDiagnostics.popUndelayed(state);
4263 }
4264
4265 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4266
4267 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4268 const ObjCInterfaceDecl *UnknownObjCClass,
4269 bool ObjCPropertyAccess,
4270 bool AvoidPartialAvailabilityChecks = false,
4271 ObjCInterfaceDecl *ClassReceiver = nullptr);
4272
4273 bool makeUnavailableInSystemHeader(SourceLocation loc,
4274 UnavailableAttr::ImplicitReason reason);
4275
4276 /// Issue any -Wunguarded-availability warnings in \c FD
4277 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4278
4279 //===--------------------------------------------------------------------===//
4280 // Expression Parsing Callbacks: SemaExpr.cpp.
4281
4282 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4283 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4284 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4285 bool ObjCPropertyAccess = false,
4286 bool AvoidPartialAvailabilityChecks = false,
4287 ObjCInterfaceDecl *ClassReciever = nullptr);
4288 void NoteDeletedFunction(FunctionDecl *FD);
4289 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4290 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4291 ObjCMethodDecl *Getter,
4292 SourceLocation Loc);
4293 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4294 ArrayRef<Expr *> Args);
4295
4296 void PushExpressionEvaluationContext(
4297 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4298 ExpressionEvaluationContextRecord::ExpressionKind Type =
4299 ExpressionEvaluationContextRecord::EK_Other);
4300 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4301 void PushExpressionEvaluationContext(
4302 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4303 ExpressionEvaluationContextRecord::ExpressionKind Type =
4304 ExpressionEvaluationContextRecord::EK_Other);
4305 void PopExpressionEvaluationContext();
4306
4307 void DiscardCleanupsInEvaluationContext();
4308
4309 ExprResult TransformToPotentiallyEvaluated(Expr *E);
4310 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4311
4312 ExprResult CheckUnevaluatedOperand(Expr *E);
4313 void CheckUnusedVolatileAssignment(Expr *E);
4314
4315 ExprResult ActOnConstantExpression(ExprResult Res);
4316
4317 // Functions for marking a declaration referenced. These functions also
4318 // contain the relevant logic for marking if a reference to a function or
4319 // variable is an odr-use (in the C++11 sense). There are separate variants
4320 // for expressions referring to a decl; these exist because odr-use marking
4321 // needs to be delayed for some constant variables when we build one of the
4322 // named expressions.
4323 //
4324 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4325 // should usually be true. This only needs to be set to false if the lack of
4326 // odr-use cannot be determined from the current context (for instance,
4327 // because the name denotes a virtual function and was written without an
4328 // explicit nested-name-specifier).
4329 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4330 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4331 bool MightBeOdrUse = true);
4332 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4333 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4334 void MarkMemberReferenced(MemberExpr *E);
4335 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4336 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4337 unsigned CapturingScopeIndex);
4338
4339 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4340 void CleanupVarDeclMarking();
4341
4342 enum TryCaptureKind {
4343 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4344 };
4345
4346 /// Try to capture the given variable.
4347 ///
4348 /// \param Var The variable to capture.
4349 ///
4350 /// \param Loc The location at which the capture occurs.
4351 ///
4352 /// \param Kind The kind of capture, which may be implicit (for either a
4353 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4354 ///
4355 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4356 /// an explicit lambda capture.
4357 ///
4358 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4359 /// captures or diagnose errors. If false, this routine merely check whether
4360 /// the capture can occur without performing the capture itself or complaining
4361 /// if the variable cannot be captured.
4362 ///
4363 /// \param CaptureType Will be set to the type of the field used to capture
4364 /// this variable in the innermost block or lambda. Only valid when the
4365 /// variable can be captured.
4366 ///
4367 /// \param DeclRefType Will be set to the type of a reference to the capture
4368 /// from within the current scope. Only valid when the variable can be
4369 /// captured.
4370 ///
4371 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4372 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4373 /// This is useful when enclosing lambdas must speculatively capture
4374 /// variables that may or may not be used in certain specializations of
4375 /// a nested generic lambda.
4376 ///
4377 /// \returns true if an error occurred (i.e., the variable cannot be
4378 /// captured) and false if the capture succeeded.
4379 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4380 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4381 QualType &CaptureType,
4382 QualType &DeclRefType,
4383 const unsigned *const FunctionScopeIndexToStopAt);
4384
4385 /// Try to capture the given variable.
4386 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4387 TryCaptureKind Kind = TryCapture_Implicit,
4388 SourceLocation EllipsisLoc = SourceLocation());
4389
4390 /// Checks if the variable must be captured.
4391 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4392
4393 /// Given a variable, determine the type that a reference to that
4394 /// variable will have in the given scope.
4395 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4396
4397 /// Mark all of the declarations referenced within a particular AST node as
4398 /// referenced. Used when template instantiation instantiates a non-dependent
4399 /// type -- entities referenced by the type are now referenced.
4400 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4401 void MarkDeclarationsReferencedInExpr(Expr *E,
4402 bool SkipLocalVariables = false);
4403
4404 /// Try to recover by turning the given expression into a
4405 /// call. Returns true if recovery was attempted or an error was
4406 /// emitted; this may also leave the ExprResult invalid.
4407 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4408 bool ForceComplain = false,
4409 bool (*IsPlausibleResult)(QualType) = nullptr);
4410
4411 /// Figure out if an expression could be turned into a call.
4412 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4413 UnresolvedSetImpl &NonTemplateOverloads);
4414
4415 /// Conditionally issue a diagnostic based on the current
4416 /// evaluation context.
4417 ///
4418 /// \param Statement If Statement is non-null, delay reporting the
4419 /// diagnostic until the function body is parsed, and then do a basic
4420 /// reachability analysis to determine if the statement is reachable.
4421 /// If it is unreachable, the diagnostic will not be emitted.
4422 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4423 const PartialDiagnostic &PD);
4424 /// Similar, but diagnostic is only produced if all the specified statements
4425 /// are reachable.
4426 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4427 const PartialDiagnostic &PD);
4428
4429 // Primary Expressions.
4430 SourceRange getExprRange(Expr *E) const;
4431
4432 ExprResult ActOnIdExpression(
4433 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4434 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4435 CorrectionCandidateCallback *CCC = nullptr,
4436 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4437
4438 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4439 TemplateArgumentListInfo &Buffer,
4440 DeclarationNameInfo &NameInfo,
4441 const TemplateArgumentListInfo *&TemplateArgs);
4442
4443 bool
4444 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4445 CorrectionCandidateCallback &CCC,
4446 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4447 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4448
4449 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4450 IdentifierInfo *II);
4451 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4452
4453 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4454 IdentifierInfo *II,
4455 bool AllowBuiltinCreation=false);
4456
4457 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4458 SourceLocation TemplateKWLoc,
4459 const DeclarationNameInfo &NameInfo,
4460 bool isAddressOfOperand,
4461 const TemplateArgumentListInfo *TemplateArgs);
4462
4463 /// If \p D cannot be odr-used in the current expression evaluation context,
4464 /// return a reason explaining why. Otherwise, return NOUR_None.
4465 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4466
4467 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4468 SourceLocation Loc,
4469 const CXXScopeSpec *SS = nullptr);
4470 DeclRefExpr *
4471 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4472 const DeclarationNameInfo &NameInfo,
4473 const CXXScopeSpec *SS = nullptr,
4474 NamedDecl *FoundD = nullptr,
4475 SourceLocation TemplateKWLoc = SourceLocation(),
4476 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4477 DeclRefExpr *
4478 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4479 const DeclarationNameInfo &NameInfo,
4480 NestedNameSpecifierLoc NNS,
4481 NamedDecl *FoundD = nullptr,
4482 SourceLocation TemplateKWLoc = SourceLocation(),
4483 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4484
4485 ExprResult
4486 BuildAnonymousStructUnionMemberReference(
4487 const CXXScopeSpec &SS,
4488 SourceLocation nameLoc,
4489 IndirectFieldDecl *indirectField,
4490 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4491 Expr *baseObjectExpr = nullptr,
4492 SourceLocation opLoc = SourceLocation());
4493
4494 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4495 SourceLocation TemplateKWLoc,
4496 LookupResult &R,
4497 const TemplateArgumentListInfo *TemplateArgs,
4498 const Scope *S);
4499 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4500 SourceLocation TemplateKWLoc,
4501 LookupResult &R,
4502 const TemplateArgumentListInfo *TemplateArgs,
4503 bool IsDefiniteInstance,
4504 const Scope *S);
4505 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4506 const LookupResult &R,
4507 bool HasTrailingLParen);
4508
4509 ExprResult
4510 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4511 const DeclarationNameInfo &NameInfo,
4512 bool IsAddressOfOperand, const Scope *S,
4513 TypeSourceInfo **RecoveryTSI = nullptr);
4514
4515 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4516 SourceLocation TemplateKWLoc,
4517 const DeclarationNameInfo &NameInfo,
4518 const TemplateArgumentListInfo *TemplateArgs);
4519
4520 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4521 LookupResult &R,
4522 bool NeedsADL,
4523 bool AcceptInvalidDecl = false);
4524 ExprResult BuildDeclarationNameExpr(
4525 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4526 NamedDecl *FoundD = nullptr,
4527 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4528 bool AcceptInvalidDecl = false);
4529
4530 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4531 DeclarationNameInfo &SuffixInfo,
4532 ArrayRef<Expr *> Args,
4533 SourceLocation LitEndLoc,
4534 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4535
4536 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4537 PredefinedExpr::IdentKind IK);
4538 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4539 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4540
4541 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4542
4543 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4544 ExprResult ActOnCharacterConstant(const Token &Tok,
4545 Scope *UDLScope = nullptr);
4546 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4547 ExprResult ActOnParenListExpr(SourceLocation L,
4548 SourceLocation R,
4549 MultiExprArg Val);
4550
4551 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4552 /// fragments (e.g. "foo" "bar" L"baz").
4553 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4554 Scope *UDLScope = nullptr);
4555
4556 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4557 SourceLocation DefaultLoc,
4558 SourceLocation RParenLoc,
4559 Expr *ControllingExpr,
4560 ArrayRef<ParsedType> ArgTypes,
4561 ArrayRef<Expr *> ArgExprs);
4562 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4563 SourceLocation DefaultLoc,
4564 SourceLocation RParenLoc,
4565 Expr *ControllingExpr,
4566 ArrayRef<TypeSourceInfo *> Types,
4567 ArrayRef<Expr *> Exprs);
4568
4569 // Binary/Unary Operators. 'Tok' is the token for the operator.
4570 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4571 Expr *InputExpr);
4572 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4573 UnaryOperatorKind Opc, Expr *Input);
4574 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4575 tok::TokenKind Op, Expr *Input);
4576
4577 bool isQualifiedMemberAccess(Expr *E);
4578 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4579
4580 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4581 SourceLocation OpLoc,
4582 UnaryExprOrTypeTrait ExprKind,
4583 SourceRange R);
4584 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4585 UnaryExprOrTypeTrait ExprKind);
4586 ExprResult
4587 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4588 UnaryExprOrTypeTrait ExprKind,
4589 bool IsType, void *TyOrEx,
4590 SourceRange ArgRange);
4591
4592 ExprResult CheckPlaceholderExpr(Expr *E);
4593 bool CheckVecStepExpr(Expr *E);
4594
4595 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4596 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4597 SourceRange ExprRange,
4598 UnaryExprOrTypeTrait ExprKind);
4599 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4600 SourceLocation OpLoc,
4601 IdentifierInfo &Name,
4602 SourceLocation NameLoc,
4603 SourceLocation RParenLoc);
4604 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4605 tok::TokenKind Kind, Expr *Input);
4606
4607 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4608 Expr *Idx, SourceLocation RLoc);
4609 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4610 Expr *Idx, SourceLocation RLoc);
4611 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4612 Expr *LowerBound, SourceLocation ColonLoc,
4613 Expr *Length, SourceLocation RBLoc);
4614
4615 // This struct is for use by ActOnMemberAccess to allow
4616 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4617 // changing the access operator from a '.' to a '->' (to see if that is the
4618 // change needed to fix an error about an unknown member, e.g. when the class
4619 // defines a custom operator->).
4620 struct ActOnMemberAccessExtraArgs {
4621 Scope *S;
4622 UnqualifiedId &Id;
4623 Decl *ObjCImpDecl;
4624 };
4625
4626 ExprResult BuildMemberReferenceExpr(
4627 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4628 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4629 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4630 const TemplateArgumentListInfo *TemplateArgs,
4631 const Scope *S,
4632 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4633
4634 ExprResult
4635 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4636 bool IsArrow, const CXXScopeSpec &SS,
4637 SourceLocation TemplateKWLoc,
4638 NamedDecl *FirstQualifierInScope, LookupResult &R,
4639 const TemplateArgumentListInfo *TemplateArgs,
4640 const Scope *S,
4641 bool SuppressQualifierCheck = false,
4642 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4643
4644 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4645 SourceLocation OpLoc,
4646 const CXXScopeSpec &SS, FieldDecl *Field,
4647 DeclAccessPair FoundDecl,
4648 const DeclarationNameInfo &MemberNameInfo);
4649
4650 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4651
4652 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4653 const CXXScopeSpec &SS,
4654 const LookupResult &R);
4655
4656 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4657 bool IsArrow, SourceLocation OpLoc,
4658 const CXXScopeSpec &SS,
4659 SourceLocation TemplateKWLoc,
4660 NamedDecl *FirstQualifierInScope,
4661 const DeclarationNameInfo &NameInfo,
4662 const TemplateArgumentListInfo *TemplateArgs);
4663
4664 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4665 SourceLocation OpLoc,
4666 tok::TokenKind OpKind,
4667 CXXScopeSpec &SS,
4668 SourceLocation TemplateKWLoc,
4669 UnqualifiedId &Member,
4670 Decl *ObjCImpDecl);
4671
4672 MemberExpr *
4673 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4674 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
4675 ValueDecl *Member, DeclAccessPair FoundDecl,
4676 bool HadMultipleCandidates,
4677 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4678 ExprValueKind VK, ExprObjectKind OK,
4679 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4680 MemberExpr *
4681 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4682 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
4683 ValueDecl *Member, DeclAccessPair FoundDecl,
4684 bool HadMultipleCandidates,
4685 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4686 ExprValueKind VK, ExprObjectKind OK,
4687 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4688
4689 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4690 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4691 FunctionDecl *FDecl,
4692 const FunctionProtoType *Proto,
4693 ArrayRef<Expr *> Args,
4694 SourceLocation RParenLoc,
4695 bool ExecConfig = false);
4696 void CheckStaticArrayArgument(SourceLocation CallLoc,
4697 ParmVarDecl *Param,
4698 const Expr *ArgExpr);
4699
4700 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4701 /// This provides the location of the left/right parens and a list of comma
4702 /// locations.
4703 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4704 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4705 Expr *ExecConfig = nullptr);
4706 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4707 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4708 Expr *ExecConfig = nullptr,
4709 bool IsExecConfig = false);
4710 enum class AtomicArgumentOrder { API, AST };
4711 ExprResult
4712 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4713 SourceLocation RParenLoc, MultiExprArg Args,
4714 AtomicExpr::AtomicOp Op,
4715 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
4716 ExprResult
4717 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4718 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4719 Expr *Config = nullptr, bool IsExecConfig = false,
4720 ADLCallKind UsesADL = ADLCallKind::NotADL);
4721
4722 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4723 MultiExprArg ExecConfig,
4724 SourceLocation GGGLoc);
4725
4726 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4727 Declarator &D, ParsedType &Ty,
4728 SourceLocation RParenLoc, Expr *CastExpr);
4729 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4730 TypeSourceInfo *Ty,
4731 SourceLocation RParenLoc,
4732 Expr *Op);
4733 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4734
4735 /// Build an altivec or OpenCL literal.
4736 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4737 SourceLocation RParenLoc, Expr *E,
4738 TypeSourceInfo *TInfo);
4739
4740 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4741
4742 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4743 ParsedType Ty,
4744 SourceLocation RParenLoc,
4745 Expr *InitExpr);
4746
4747 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4748 TypeSourceInfo *TInfo,
4749 SourceLocation RParenLoc,
4750 Expr *LiteralExpr);
4751
4752 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4753 MultiExprArg InitArgList,
4754 SourceLocation RBraceLoc);
4755
4756 ExprResult BuildInitList(SourceLocation LBraceLoc,
4757 MultiExprArg InitArgList,
4758 SourceLocation RBraceLoc);
4759
4760 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4761 SourceLocation EqualOrColonLoc,
4762 bool GNUSyntax,
4763 ExprResult Init);
4764
4765private:
4766 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4767
4768public:
4769 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4770 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4771 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4772 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4773 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4774 Expr *LHSExpr, Expr *RHSExpr);
4775
4776 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4777
4778 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4779 /// in the case of a the GNU conditional expr extension.
4780 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4781 SourceLocation ColonLoc,
4782 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4783
4784 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4785 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4786 LabelDecl *TheDecl);
4787
4788 void ActOnStartStmtExpr();
4789 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4790 SourceLocation RPLoc); // "({..})"
4791 // Handle the final expression in a statement expression.
4792 ExprResult ActOnStmtExprResult(ExprResult E);
4793 void ActOnStmtExprError();
4794
4795 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4796 struct OffsetOfComponent {
4797 SourceLocation LocStart, LocEnd;
4798 bool isBrackets; // true if [expr], false if .ident
4799 union {
4800 IdentifierInfo *IdentInfo;
4801 Expr *E;
4802 } U;
4803 };
4804
4805 /// __builtin_offsetof(type, a.b[123][456].c)
4806 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4807 TypeSourceInfo *TInfo,
4808 ArrayRef<OffsetOfComponent> Components,
4809 SourceLocation RParenLoc);
4810 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4811 SourceLocation BuiltinLoc,
4812 SourceLocation TypeLoc,
4813 ParsedType ParsedArgTy,
4814 ArrayRef<OffsetOfComponent> Components,
4815 SourceLocation RParenLoc);
4816
4817 // __builtin_choose_expr(constExpr, expr1, expr2)
4818 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4819 Expr *CondExpr, Expr *LHSExpr,
4820 Expr *RHSExpr, SourceLocation RPLoc);
4821
4822 // __builtin_va_arg(expr, type)
4823 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4824 SourceLocation RPLoc);
4825 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4826 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4827
4828 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
4829 // __builtin_COLUMN()
4830 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
4831 SourceLocation BuiltinLoc,
4832 SourceLocation RPLoc);
4833
4834 // Build a potentially resolved SourceLocExpr.
4835 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
4836 SourceLocation BuiltinLoc, SourceLocation RPLoc,
4837 DeclContext *ParentContext);
4838
4839 // __null
4840 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4841
4842 bool CheckCaseExpression(Expr *E);
4843
4844 /// Describes the result of an "if-exists" condition check.
4845 enum IfExistsResult {
4846 /// The symbol exists.
4847 IER_Exists,
4848
4849 /// The symbol does not exist.
4850 IER_DoesNotExist,
4851
4852 /// The name is a dependent name, so the results will differ
4853 /// from one instantiation to the next.
4854 IER_Dependent,
4855
4856 /// An error occurred.
4857 IER_Error
4858 };
4859
4860 IfExistsResult
4861 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4862 const DeclarationNameInfo &TargetNameInfo);
4863
4864 IfExistsResult
4865 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4866 bool IsIfExists, CXXScopeSpec &SS,
4867 UnqualifiedId &Name);
4868
4869 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4870 bool IsIfExists,
4871 NestedNameSpecifierLoc QualifierLoc,
4872 DeclarationNameInfo NameInfo,
4873 Stmt *Nested);
4874 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4875 bool IsIfExists,
4876 CXXScopeSpec &SS, UnqualifiedId &Name,
4877 Stmt *Nested);
4878
4879 //===------------------------- "Block" Extension ------------------------===//
4880
4881 /// ActOnBlockStart - This callback is invoked when a block literal is
4882 /// started.
4883 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4884
4885 /// ActOnBlockArguments - This callback allows processing of block arguments.
4886 /// If there are no arguments, this is still invoked.
4887 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4888 Scope *CurScope);
4889
4890 /// ActOnBlockError - If there is an error parsing a block, this callback
4891 /// is invoked to pop the information about the block from the action impl.
4892 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4893
4894 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4895 /// literal was successfully completed. ^(int x){...}
4896 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4897 Scope *CurScope);
4898
4899 //===---------------------------- Clang Extensions ----------------------===//
4900
4901 /// __builtin_convertvector(...)
4902 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4903 SourceLocation BuiltinLoc,
4904 SourceLocation RParenLoc);
4905
4906 //===---------------------------- OpenCL Features -----------------------===//
4907
4908 /// __builtin_astype(...)
4909 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4910 SourceLocation BuiltinLoc,
4911 SourceLocation RParenLoc);
4912
4913 //===---------------------------- C++ Features --------------------------===//
4914
4915 // Act on C++ namespaces
4916 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4917 SourceLocation NamespaceLoc,
4918 SourceLocation IdentLoc, IdentifierInfo *Ident,
4919 SourceLocation LBrace,
4920 const ParsedAttributesView &AttrList,
4921 UsingDirectiveDecl *&UsingDecl);
4922 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4923
4924 NamespaceDecl *getStdNamespace() const;
4925 NamespaceDecl *getOrCreateStdNamespace();
4926
4927 NamespaceDecl *lookupStdExperimentalNamespace();
4928
4929 CXXRecordDecl *getStdBadAlloc() const;
4930 EnumDecl *getStdAlignValT() const;
4931
4932private:
4933 // A cache representing if we've fully checked the various comparison category
4934 // types stored in ASTContext. The bit-index corresponds to the integer value
4935 // of a ComparisonCategoryType enumerator.
4936 llvm::SmallBitVector FullyCheckedComparisonCategories;
4937
4938 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4939 CXXScopeSpec &SS,
4940 ParsedType TemplateTypeTy,
4941 IdentifierInfo *MemberOrBase);
4942
4943public:
4944 /// Lookup the specified comparison category types in the standard
4945 /// library, an check the VarDecls possibly returned by the operator<=>
4946 /// builtins for that type.
4947 ///
4948 /// \return The type of the comparison category type corresponding to the
4949 /// specified Kind, or a null type if an error occurs
4950 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
4951 SourceLocation Loc);
4952
4953 /// Tests whether Ty is an instance of std::initializer_list and, if
4954 /// it is and Element is not NULL, assigns the element type to Element.
4955 bool isStdInitializerList(QualType Ty, QualType *Element);
4956
4957 /// Looks for the std::initializer_list template and instantiates it
4958 /// with Element, or emits an error if it's not found.
4959 ///
4960 /// \returns The instantiated template, or null on error.
4961 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4962
4963 /// Determine whether Ctor is an initializer-list constructor, as
4964 /// defined in [dcl.init.list]p2.
4965 bool isInitListConstructor(const FunctionDecl *Ctor);
4966
4967 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
4968 SourceLocation NamespcLoc, CXXScopeSpec &SS,
4969 SourceLocation IdentLoc,
4970 IdentifierInfo *NamespcName,
4971 const ParsedAttributesView &AttrList);
4972
4973 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4974
4975 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4976 SourceLocation NamespaceLoc,
4977 SourceLocation AliasLoc,
4978 IdentifierInfo *Alias,
4979 CXXScopeSpec &SS,
4980 SourceLocation IdentLoc,
4981 IdentifierInfo *Ident);
4982
4983 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4984 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4985 const LookupResult &PreviousDecls,
4986 UsingShadowDecl *&PrevShadow);
4987 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4988 NamedDecl *Target,
4989 UsingShadowDecl *PrevDecl);
4990
4991 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4992 bool HasTypenameKeyword,
4993 const CXXScopeSpec &SS,
4994 SourceLocation NameLoc,
4995 const LookupResult &Previous);
4996 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4997 bool HasTypename,
4998 const CXXScopeSpec &SS,
4999 const DeclarationNameInfo &NameInfo,
5000 SourceLocation NameLoc);
5001
5002 NamedDecl *BuildUsingDeclaration(
5003 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5004 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5005 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5006 const ParsedAttributesView &AttrList, bool IsInstantiation);
5007 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5008 ArrayRef<NamedDecl *> Expansions);
5009
5010 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5011
5012 /// Given a derived-class using shadow declaration for a constructor and the
5013 /// correspnding base class constructor, find or create the implicit
5014 /// synthesized derived class constructor to use for this initialization.
5015 CXXConstructorDecl *
5016 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5017 ConstructorUsingShadowDecl *DerivedShadow);
5018
5019 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5020 SourceLocation UsingLoc,
5021 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5022 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5023 const ParsedAttributesView &AttrList);
5024 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5025 MultiTemplateParamsArg TemplateParams,
5026 SourceLocation UsingLoc, UnqualifiedId &Name,
5027 const ParsedAttributesView &AttrList,
5028 TypeResult Type, Decl *DeclFromDeclSpec);
5029
5030 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5031 /// including handling of its default argument expressions.
5032 ///
5033 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5034 ExprResult
5035 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5036 NamedDecl *FoundDecl,
5037 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5038 bool HadMultipleCandidates, bool IsListInitialization,
5039 bool IsStdInitListInitialization,
5040 bool RequiresZeroInit, unsigned ConstructKind,
5041 SourceRange ParenRange);
5042
5043 /// Build a CXXConstructExpr whose constructor has already been resolved if
5044 /// it denotes an inherited constructor.
5045 ExprResult
5046 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5047 CXXConstructorDecl *Constructor, bool Elidable,
5048 MultiExprArg Exprs,
5049 bool HadMultipleCandidates, bool IsListInitialization,
5050 bool IsStdInitListInitialization,
5051 bool RequiresZeroInit, unsigned ConstructKind,
5052 SourceRange ParenRange);
5053
5054 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5055 // the constructor can be elidable?
5056 ExprResult
5057 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5058 NamedDecl *FoundDecl,
5059 CXXConstructorDecl *Constructor, bool Elidable,
5060 MultiExprArg Exprs, bool HadMultipleCandidates,
5061 bool IsListInitialization,
5062 bool IsStdInitListInitialization, bool RequiresZeroInit,
5063 unsigned ConstructKind, SourceRange ParenRange);
5064
5065 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5066
5067
5068 /// Instantiate or parse a C++ default argument expression as necessary.
5069 /// Return true on error.
5070 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5071 ParmVarDecl *Param);
5072
5073 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5074 /// the default expr if needed.
5075 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5076 FunctionDecl *FD,
5077 ParmVarDecl *Param);
5078
5079 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5080 /// constructed variable.
5081 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5082
5083 /// Helper class that collects exception specifications for
5084 /// implicitly-declared special member functions.
5085 class ImplicitExceptionSpecification {
5086 // Pointer to allow copying
5087 Sema *Self;
5088 // We order exception specifications thus:
5089 // noexcept is the most restrictive, but is only used in C++11.
5090 // throw() comes next.
5091 // Then a throw(collected exceptions)
5092 // Finally no specification, which is expressed as noexcept(false).
5093 // throw(...) is used instead if any called function uses it.
5094 ExceptionSpecificationType ComputedEST;
5095 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5096 SmallVector<QualType, 4> Exceptions;
5097
5098 void ClearExceptions() {
5099 ExceptionsSeen.clear();
5100 Exceptions.clear();
5101 }
5102
5103 public:
5104 explicit ImplicitExceptionSpecification(Sema &Self)
5105 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5106 if (!Self.getLangOpts().CPlusPlus11)
5107 ComputedEST = EST_DynamicNone;
5108 }
5109
5110 /// Get the computed exception specification type.
5111 ExceptionSpecificationType getExceptionSpecType() const {
5112 assert(!isComputedNoexcept(ComputedEST) &&((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 5113, __PRETTY_FUNCTION__))
5113 "noexcept(expr) should not be a possible result")((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 5113, __PRETTY_FUNCTION__))
;
5114 return ComputedEST;
5115 }
5116
5117 /// The number of exceptions in the exception specification.
5118 unsigned size() const { return Exceptions.size(); }
5119
5120 /// The set of exceptions in the exception specification.
5121 const QualType *data() const { return Exceptions.data(); }
5122
5123 /// Integrate another called method into the collected data.
5124 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5125
5126 /// Integrate an invoked expression into the collected data.
5127 void CalledExpr(Expr *E);
5128
5129 /// Overwrite an EPI's exception specification with this
5130 /// computed exception specification.
5131 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5132 FunctionProtoType::ExceptionSpecInfo ESI;
5133 ESI.Type = getExceptionSpecType();
5134 if (ESI.Type == EST_Dynamic) {
5135 ESI.Exceptions = Exceptions;
5136 } else if (ESI.Type == EST_None) {
5137 /// C++11 [except.spec]p14:
5138 /// The exception-specification is noexcept(false) if the set of
5139 /// potential exceptions of the special member function contains "any"
5140 ESI.Type = EST_NoexceptFalse;
5141 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5142 tok::kw_false).get();
5143 }
5144 return ESI;
5145 }
5146 };
5147
5148 /// Determine what sort of exception specification a defaulted
5149 /// copy constructor of a class will have.
5150 ImplicitExceptionSpecification
5151 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5152 CXXMethodDecl *MD);
5153
5154 /// Determine what sort of exception specification a defaulted
5155 /// default constructor of a class will have, and whether the parameter
5156 /// will be const.
5157 ImplicitExceptionSpecification
5158 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5159
5160 /// Determine what sort of exception specification a defaulted
5161 /// copy assignment operator of a class will have, and whether the
5162 /// parameter will be const.
5163 ImplicitExceptionSpecification
5164 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5165
5166 /// Determine what sort of exception specification a defaulted move
5167 /// constructor of a class will have.
5168 ImplicitExceptionSpecification
5169 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5170
5171 /// Determine what sort of exception specification a defaulted move
5172 /// assignment operator of a class will have.
5173 ImplicitExceptionSpecification
5174 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5175
5176 /// Determine what sort of exception specification a defaulted
5177 /// destructor of a class will have.
5178 ImplicitExceptionSpecification
5179 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5180
5181 /// Determine what sort of exception specification an inheriting
5182 /// constructor of a class will have.
5183 ImplicitExceptionSpecification
5184 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5185 CXXConstructorDecl *CD);
5186
5187 /// Evaluate the implicit exception specification for a defaulted
5188 /// special member function.
5189 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
5190
5191 /// Check the given noexcept-specifier, convert its expression, and compute
5192 /// the appropriate ExceptionSpecificationType.
5193 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5194 ExceptionSpecificationType &EST);
5195
5196 /// Check the given exception-specification and update the
5197 /// exception specification information with the results.
5198 void checkExceptionSpecification(bool IsTopLevel,
5199 ExceptionSpecificationType EST,
5200 ArrayRef<ParsedType> DynamicExceptions,
5201 ArrayRef<SourceRange> DynamicExceptionRanges,
5202 Expr *NoexceptExpr,
5203 SmallVectorImpl<QualType> &Exceptions,
5204 FunctionProtoType::ExceptionSpecInfo &ESI);
5205
5206 /// Determine if we're in a case where we need to (incorrectly) eagerly
5207 /// parse an exception specification to work around a libstdc++ bug.
5208 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5209
5210 /// Add an exception-specification to the given member function
5211 /// (or member function template). The exception-specification was parsed
5212 /// after the method itself was declared.
5213 void actOnDelayedExceptionSpecification(Decl *Method,
5214 ExceptionSpecificationType EST,
5215 SourceRange SpecificationRange,
5216 ArrayRef<ParsedType> DynamicExceptions,
5217 ArrayRef<SourceRange> DynamicExceptionRanges,
5218 Expr *NoexceptExpr);
5219
5220 class InheritedConstructorInfo;
5221
5222 /// Determine if a special member function should have a deleted
5223 /// definition when it is defaulted.
5224 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5225 InheritedConstructorInfo *ICI = nullptr,
5226 bool Diagnose = false);
5227
5228 /// Declare the implicit default constructor for the given class.
5229 ///
5230 /// \param ClassDecl The class declaration into which the implicit
5231 /// default constructor will be added.
5232 ///
5233 /// \returns The implicitly-declared default constructor.
5234 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5235 CXXRecordDecl *ClassDecl);
5236
5237 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5238 /// defining this constructor as the default constructor.
5239 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5240 CXXConstructorDecl *Constructor);
5241
5242 /// Declare the implicit destructor for the given class.
5243 ///
5244 /// \param ClassDecl The class declaration into which the implicit
5245 /// destructor will be added.
5246 ///
5247 /// \returns The implicitly-declared destructor.
5248 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5249
5250 /// DefineImplicitDestructor - Checks for feasibility of
5251 /// defining this destructor as the default destructor.
5252 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5253 CXXDestructorDecl *Destructor);
5254
5255 /// Build an exception spec for destructors that don't have one.
5256 ///
5257 /// C++11 says that user-defined destructors with no exception spec get one
5258 /// that looks as if the destructor was implicitly declared.
5259 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5260
5261 /// Define the specified inheriting constructor.
5262 void DefineInheritingConstructor(SourceLocation UseLoc,
5263 CXXConstructorDecl *Constructor);
5264
5265 /// Declare the implicit copy constructor for the given class.
5266 ///
5267 /// \param ClassDecl The class declaration into which the implicit
5268 /// copy constructor will be added.
5269 ///
5270 /// \returns The implicitly-declared copy constructor.
5271 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5272
5273 /// DefineImplicitCopyConstructor - Checks for feasibility of
5274 /// defining this constructor as the copy constructor.
5275 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5276 CXXConstructorDecl *Constructor);
5277
5278 /// Declare the implicit move constructor for the given class.
5279 ///
5280 /// \param ClassDecl The Class declaration into which the implicit
5281 /// move constructor will be added.
5282 ///
5283 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5284 /// declared.
5285 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5286
5287 /// DefineImplicitMoveConstructor - Checks for feasibility of
5288 /// defining this constructor as the move constructor.
5289 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5290 CXXConstructorDecl *Constructor);
5291
5292 /// Declare the implicit copy assignment operator for the given class.
5293 ///
5294 /// \param ClassDecl The class declaration into which the implicit
5295 /// copy assignment operator will be added.
5296 ///
5297 /// \returns The implicitly-declared copy assignment operator.
5298 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5299
5300 /// Defines an implicitly-declared copy assignment operator.
5301 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5302 CXXMethodDecl *MethodDecl);
5303
5304 /// Declare the implicit move assignment operator for the given class.
5305 ///
5306 /// \param ClassDecl The Class declaration into which the implicit
5307 /// move assignment operator will be added.
5308 ///
5309 /// \returns The implicitly-declared move assignment operator, or NULL if it
5310 /// wasn't declared.
5311 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5312
5313 /// Defines an implicitly-declared move assignment operator.
5314 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5315 CXXMethodDecl *MethodDecl);
5316
5317 /// Force the declaration of any implicitly-declared members of this
5318 /// class.
5319 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5320
5321 /// Check a completed declaration of an implicit special member.
5322 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5323
5324 /// Determine whether the given function is an implicitly-deleted
5325 /// special member function.
5326 bool isImplicitlyDeleted(FunctionDecl *FD);
5327
5328 /// Check whether 'this' shows up in the type of a static member
5329 /// function after the (naturally empty) cv-qualifier-seq would be.
5330 ///
5331 /// \returns true if an error occurred.
5332 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5333
5334 /// Whether this' shows up in the exception specification of a static
5335 /// member function.
5336 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5337
5338 /// Check whether 'this' shows up in the attributes of the given
5339 /// static member function.
5340 ///
5341 /// \returns true if an error occurred.
5342 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5343
5344 /// MaybeBindToTemporary - If the passed in expression has a record type with
5345 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5346 /// it simply returns the passed in expression.
5347 ExprResult MaybeBindToTemporary(Expr *E);
5348
5349 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5350 MultiExprArg ArgsPtr,
5351 SourceLocation Loc,
5352 SmallVectorImpl<Expr*> &ConvertedArgs,
5353 bool AllowExplicit = false,
5354 bool IsListInitialization = false);
5355
5356 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5357 SourceLocation NameLoc,
5358 IdentifierInfo &Name);
5359
5360 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5361 Scope *S, CXXScopeSpec &SS,
5362 bool EnteringContext);
5363 ParsedType getDestructorName(SourceLocation TildeLoc,
5364 IdentifierInfo &II, SourceLocation NameLoc,
5365 Scope *S, CXXScopeSpec &SS,
5366 ParsedType ObjectType,
5367 bool EnteringContext);
5368
5369 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5370 ParsedType ObjectType);
5371
5372 // Checks that reinterpret casts don't have undefined behavior.
5373 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5374 bool IsDereference, SourceRange Range);
5375
5376 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
5377 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5378 tok::TokenKind Kind,
5379 SourceLocation LAngleBracketLoc,
5380 Declarator &D,
5381 SourceLocation RAngleBracketLoc,
5382 SourceLocation LParenLoc,
5383 Expr *E,
5384 SourceLocation RParenLoc);
5385
5386 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5387 tok::TokenKind Kind,
5388 TypeSourceInfo *Ty,
5389 Expr *E,
5390 SourceRange AngleBrackets,
5391 SourceRange Parens);
5392
5393 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
5394 ExprResult Operand,
5395 SourceLocation RParenLoc);
5396
5397 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
5398 Expr *Operand, SourceLocation RParenLoc);
5399
5400 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5401 SourceLocation TypeidLoc,
5402 TypeSourceInfo *Operand,
5403 SourceLocation RParenLoc);
5404 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5405 SourceLocation TypeidLoc,
5406 Expr *Operand,
5407 SourceLocation RParenLoc);
5408
5409 /// ActOnCXXTypeid - Parse typeid( something ).
5410 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5411 SourceLocation LParenLoc, bool isType,
5412 void *TyOrExpr,
5413 SourceLocation RParenLoc);
5414
5415 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5416 SourceLocation TypeidLoc,
5417 TypeSourceInfo *Operand,
5418 SourceLocation RParenLoc);
5419 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5420 SourceLocation TypeidLoc,
5421 Expr *Operand,
5422 SourceLocation RParenLoc);
5423
5424 /// ActOnCXXUuidof - Parse __uuidof( something ).
5425 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5426 SourceLocation LParenLoc, bool isType,
5427 void *TyOrExpr,
5428 SourceLocation RParenLoc);
5429
5430 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
5431 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5432 tok::TokenKind Operator,
5433 SourceLocation EllipsisLoc, Expr *RHS,
5434 SourceLocation RParenLoc);
5435 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5436 BinaryOperatorKind Operator,
5437 SourceLocation EllipsisLoc, Expr *RHS,
5438 SourceLocation RParenLoc,
5439 Optional<unsigned> NumExpansions);
5440 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5441 BinaryOperatorKind Operator);
5442
5443 //// ActOnCXXThis - Parse 'this' pointer.
5444 ExprResult ActOnCXXThis(SourceLocation loc);
5445
5446 /// Build a CXXThisExpr and mark it referenced in the current context.
5447 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
5448 void MarkThisReferenced(CXXThisExpr *This);
5449
5450 /// Try to retrieve the type of the 'this' pointer.
5451 ///
5452 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5453 QualType getCurrentThisType();
5454
5455 /// When non-NULL, the C++ 'this' expression is allowed despite the
5456 /// current context not being a non-static member function. In such cases,
5457 /// this provides the type used for 'this'.
5458 QualType CXXThisTypeOverride;
5459
5460 /// RAII object used to temporarily allow the C++ 'this' expression
5461 /// to be used, with the given qualifiers on the current class type.
5462 class CXXThisScopeRAII {
5463 Sema &S;
5464 QualType OldCXXThisTypeOverride;
5465 bool Enabled;
5466
5467 public:
5468 /// Introduce a new scope where 'this' may be allowed (when enabled),
5469 /// using the given declaration (which is either a class template or a
5470 /// class) along with the given qualifiers.
5471 /// along with the qualifiers placed on '*this'.
5472 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
5473 bool Enabled = true);
5474
5475 ~CXXThisScopeRAII();
5476 };
5477
5478 /// Make sure the value of 'this' is actually available in the current
5479 /// context, if it is a potentially evaluated context.
5480 ///
5481 /// \param Loc The location at which the capture of 'this' occurs.
5482 ///
5483 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5484 /// capture list.
5485 ///
5486 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5487 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5488 /// This is useful when enclosing lambdas must speculatively capture
5489 /// 'this' that may or may not be used in certain specializations of
5490 /// a nested generic lambda (depending on whether the name resolves to
5491 /// a non-static member function or a static function).
5492 /// \return returns 'true' if failed, 'false' if success.
5493 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5494 bool BuildAndDiagnose = true,
5495 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5496 bool ByCopy = false);
5497
5498 /// Determine whether the given type is the type of *this that is used
5499 /// outside of the body of a member function for a type that is currently
5500 /// being defined.
5501 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5502
5503 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5504 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5505
5506
5507 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5508 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5509
5510 ExprResult
5511 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5512 SourceLocation AtLoc, SourceLocation RParen);
5513
5514 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5515 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5516
5517 //// ActOnCXXThrow - Parse throw expressions.
5518 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5519 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5520 bool IsThrownVarInScope);
5521 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5522
5523 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5524 /// Can be interpreted either as function-style casting ("int(x)")
5525 /// or class type construction ("ClassType(x,y,z)")
5526 /// or creation of a value-initialized type ("int()").
5527 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5528 SourceLocation LParenOrBraceLoc,
5529 MultiExprArg Exprs,
5530 SourceLocation RParenOrBraceLoc,
5531 bool ListInitialization);
5532
5533 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5534 SourceLocation LParenLoc,
5535 MultiExprArg Exprs,
5536 SourceLocation RParenLoc,
5537 bool ListInitialization);
5538
5539 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5540 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5541 SourceLocation PlacementLParen,
5542 MultiExprArg PlacementArgs,
5543 SourceLocation PlacementRParen,
5544 SourceRange TypeIdParens, Declarator &D,
5545 Expr *Initializer);
5546 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5547 SourceLocation PlacementLParen,
5548 MultiExprArg PlacementArgs,
5549 SourceLocation PlacementRParen,
5550 SourceRange TypeIdParens,
5551 QualType AllocType,
5552 TypeSourceInfo *AllocTypeInfo,
5553 Optional<Expr *> ArraySize,
5554 SourceRange DirectInitRange,
5555 Expr *Initializer);
5556
5557 /// Determine whether \p FD is an aligned allocation or deallocation
5558 /// function that is unavailable.
5559 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
5560
5561 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
5562 /// function that is unavailable.
5563 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
5564 SourceLocation Loc);
5565
5566 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5567 SourceRange R);
5568
5569 /// The scope in which to find allocation functions.
5570 enum AllocationFunctionScope {
5571 /// Only look for allocation functions in the global scope.
5572 AFS_Global,
5573 /// Only look for allocation functions in the scope of the
5574 /// allocated class.
5575 AFS_Class,
5576 /// Look for allocation functions in both the global scope
5577 /// and in the scope of the allocated class.
5578 AFS_Both
5579 };
5580
5581 /// Finds the overloads of operator new and delete that are appropriate
5582 /// for the allocation.
5583 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5584 AllocationFunctionScope NewScope,
5585 AllocationFunctionScope DeleteScope,
5586 QualType AllocType, bool IsArray,
5587 bool &PassAlignment, MultiExprArg PlaceArgs,
5588 FunctionDecl *&OperatorNew,
5589 FunctionDecl *&OperatorDelete,
5590 bool Diagnose = true);
5591 void DeclareGlobalNewDelete();
5592 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5593 ArrayRef<QualType> Params);
5594
5595 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5596 DeclarationName Name, FunctionDecl* &Operator,
5597 bool Diagnose = true);
5598 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5599 bool CanProvideSize,
5600 bool Overaligned,
5601 DeclarationName Name);
5602 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5603 CXXRecordDecl *RD);
5604
5605 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5606 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5607 bool UseGlobal, bool ArrayForm,
5608 Expr *Operand);
5609 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5610 bool IsDelete, bool CallCanBeVirtual,
5611 bool WarnOnNonAbstractTypes,
5612 SourceLocation DtorLoc);
5613
5614 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5615 Expr *Operand, SourceLocation RParen);
5616 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5617 SourceLocation RParen);
5618
5619 /// Parsed one of the type trait support pseudo-functions.
5620 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5621 ArrayRef<ParsedType> Args,
5622 SourceLocation RParenLoc);
5623 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5624 ArrayRef<TypeSourceInfo *> Args,
5625 SourceLocation RParenLoc);
5626
5627 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5628 /// pseudo-functions.
5629 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5630 SourceLocation KWLoc,
5631 ParsedType LhsTy,
5632 Expr *DimExpr,
5633 SourceLocation RParen);
5634
5635 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5636 SourceLocation KWLoc,
5637 TypeSourceInfo *TSInfo,
5638 Expr *DimExpr,
5639 SourceLocation RParen);
5640
5641 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5642 /// pseudo-functions.
5643 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5644 SourceLocation KWLoc,
5645 Expr *Queried,
5646 SourceLocation RParen);
5647
5648 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5649 SourceLocation KWLoc,
5650 Expr *Queried,
5651 SourceLocation RParen);
5652
5653 ExprResult ActOnStartCXXMemberReference(Scope *S,
5654 Expr *Base,
5655 SourceLocation OpLoc,
5656 tok::TokenKind OpKind,
5657 ParsedType &ObjectType,
5658 bool &MayBePseudoDestructor);
5659
5660 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5661 SourceLocation OpLoc,
5662 tok::TokenKind OpKind,
5663 const CXXScopeSpec &SS,
5664 TypeSourceInfo *ScopeType,
5665 SourceLocation CCLoc,
5666 SourceLocation TildeLoc,
5667 PseudoDestructorTypeStorage DestroyedType);
5668
5669 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5670 SourceLocation OpLoc,
5671 tok::TokenKind OpKind,
5672 CXXScopeSpec &SS,
5673 UnqualifiedId &FirstTypeName,
5674 SourceLocation CCLoc,
5675 SourceLocation TildeLoc,
5676 UnqualifiedId &SecondTypeName);
5677
5678 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5679 SourceLocation OpLoc,
5680 tok::TokenKind OpKind,
5681 SourceLocation TildeLoc,
5682 const DeclSpec& DS);
5683
5684 /// MaybeCreateExprWithCleanups - If the current full-expression
5685 /// requires any cleanups, surround it with a ExprWithCleanups node.
5686 /// Otherwise, just returns the passed-in expression.
5687 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5688 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5689 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5690
5691 MaterializeTemporaryExpr *
5692 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5693 bool BoundToLvalueReference);
5694
5695 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
5696 return ActOnFinishFullExpr(
5697 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
5698 }
5699 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5700 bool DiscardedValue, bool IsConstexpr = false);
5701 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5702
5703 // Marks SS invalid if it represents an incomplete type.
5704 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5705
5706 DeclContext *computeDeclContext(QualType T);
5707 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5708 bool EnteringContext = false);
5709 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5710 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5711
5712 /// The parser has parsed a global nested-name-specifier '::'.
5713 ///
5714 /// \param CCLoc The location of the '::'.
5715 ///
5716 /// \param SS The nested-name-specifier, which will be updated in-place
5717 /// to reflect the parsed nested-name-specifier.
5718 ///
5719 /// \returns true if an error occurred, false otherwise.
5720 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5721
5722 /// The parser has parsed a '__super' nested-name-specifier.
5723 ///
5724 /// \param SuperLoc The location of the '__super' keyword.
5725 ///
5726 /// \param ColonColonLoc The location of the '::'.
5727 ///
5728 /// \param SS The nested-name-specifier, which will be updated in-place
5729 /// to reflect the parsed nested-name-specifier.
5730 ///
5731 /// \returns true if an error occurred, false otherwise.
5732 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5733 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5734
5735 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5736 bool *CanCorrect = nullptr);
5737 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5738
5739 /// Keeps information about an identifier in a nested-name-spec.
5740 ///
5741 struct NestedNameSpecInfo {
5742 /// The type of the object, if we're parsing nested-name-specifier in
5743 /// a member access expression.
5744 ParsedType ObjectType;
5745
5746 /// The identifier preceding the '::'.
5747 IdentifierInfo *Identifier;
5748
5749 /// The location of the identifier.
5750 SourceLocation IdentifierLoc;
5751
5752 /// The location of the '::'.
5753 SourceLocation CCLoc;
5754
5755 /// Creates info object for the most typical case.
5756 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5757 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5758 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5759 CCLoc(ColonColonLoc) {
5760 }
5761
5762 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5763 SourceLocation ColonColonLoc, QualType ObjectType)
5764 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5765 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5766 }
5767 };
5768
5769 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5770 NestedNameSpecInfo &IdInfo);
5771
5772 bool BuildCXXNestedNameSpecifier(Scope *S,
5773 NestedNameSpecInfo &IdInfo,
5774 bool EnteringContext,
5775 CXXScopeSpec &SS,
5776 NamedDecl *ScopeLookupResult,
5777 bool ErrorRecoveryLookup,
5778 bool *IsCorrectedToColon = nullptr,
5779 bool OnlyNamespace = false);
5780
5781 /// The parser has parsed a nested-name-specifier 'identifier::'.
5782 ///
5783 /// \param S The scope in which this nested-name-specifier occurs.
5784 ///
5785 /// \param IdInfo Parser information about an identifier in the
5786 /// nested-name-spec.
5787 ///
5788 /// \param EnteringContext Whether we're entering the context nominated by
5789 /// this nested-name-specifier.
5790 ///
5791 /// \param SS The nested-name-specifier, which is both an input
5792 /// parameter (the nested-name-specifier before this type) and an
5793 /// output parameter (containing the full nested-name-specifier,
5794 /// including this new type).
5795 ///
5796 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5797 /// error recovery. In this case do not emit error message.
5798 ///
5799 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5800 /// are allowed. The bool value pointed by this parameter is set to 'true'
5801 /// if the identifier is treated as if it was followed by ':', not '::'.
5802 ///
5803 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5804 ///
5805 /// \returns true if an error occurred, false otherwise.
5806 bool ActOnCXXNestedNameSpecifier(Scope *S,
5807 NestedNameSpecInfo &IdInfo,
5808 bool EnteringContext,
5809 CXXScopeSpec &SS,
5810 bool ErrorRecoveryLookup = false,
5811 bool *IsCorrectedToColon = nullptr,
5812 bool OnlyNamespace = false);
5813
5814 ExprResult ActOnDecltypeExpression(Expr *E);
5815
5816 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5817 const DeclSpec &DS,
5818 SourceLocation ColonColonLoc);
5819
5820 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5821 NestedNameSpecInfo &IdInfo,
5822 bool EnteringContext);
5823
5824 /// The parser has parsed a nested-name-specifier
5825 /// 'template[opt] template-name < template-args >::'.
5826 ///
5827 /// \param S The scope in which this nested-name-specifier occurs.
5828 ///
5829 /// \param SS The nested-name-specifier, which is both an input
5830 /// parameter (the nested-name-specifier before this type) and an
5831 /// output parameter (containing the full nested-name-specifier,
5832 /// including this new type).
5833 ///
5834 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5835 /// \param TemplateName the template name.
5836 /// \param TemplateNameLoc The location of the template name.
5837 /// \param LAngleLoc The location of the opening angle bracket ('<').
5838 /// \param TemplateArgs The template arguments.
5839 /// \param RAngleLoc The location of the closing angle bracket ('>').
5840 /// \param CCLoc The location of the '::'.
5841 ///
5842 /// \param EnteringContext Whether we're entering the context of the
5843 /// nested-name-specifier.
5844 ///
5845 ///
5846 /// \returns true if an error occurred, false otherwise.
5847 bool ActOnCXXNestedNameSpecifier(Scope *S,
5848 CXXScopeSpec &SS,
5849 SourceLocation TemplateKWLoc,
5850 TemplateTy TemplateName,
5851 SourceLocation TemplateNameLoc,
5852 SourceLocation LAngleLoc,
5853 ASTTemplateArgsPtr TemplateArgs,
5854 SourceLocation RAngleLoc,
5855 SourceLocation CCLoc,
5856 bool EnteringContext);
5857
5858 /// Given a C++ nested-name-specifier, produce an annotation value
5859 /// that the parser can use later to reconstruct the given
5860 /// nested-name-specifier.
5861 ///
5862 /// \param SS A nested-name-specifier.
5863 ///
5864 /// \returns A pointer containing all of the information in the
5865 /// nested-name-specifier \p SS.
5866 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5867
5868 /// Given an annotation pointer for a nested-name-specifier, restore
5869 /// the nested-name-specifier structure.
5870 ///
5871 /// \param Annotation The annotation pointer, produced by
5872 /// \c SaveNestedNameSpecifierAnnotation().
5873 ///
5874 /// \param AnnotationRange The source range corresponding to the annotation.
5875 ///
5876 /// \param SS The nested-name-specifier that will be updated with the contents
5877 /// of the annotation pointer.
5878 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5879 SourceRange AnnotationRange,
5880 CXXScopeSpec &SS);
5881
5882 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5883
5884 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5885 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5886 /// After this method is called, according to [C++ 3.4.3p3], names should be
5887 /// looked up in the declarator-id's scope, until the declarator is parsed and
5888 /// ActOnCXXExitDeclaratorScope is called.
5889 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5890 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5891
5892 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5893 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5894 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5895 /// Used to indicate that names should revert to being looked up in the
5896 /// defining scope.
5897 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5898
5899 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5900 /// initializer for the declaration 'Dcl'.
5901 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5902 /// static data member of class X, names should be looked up in the scope of
5903 /// class X.
5904 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5905
5906 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5907 /// initializer for the declaration 'Dcl'.
5908 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5909
5910 /// Create a new lambda closure type.
5911 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5912 TypeSourceInfo *Info,
5913 bool KnownDependent,
5914 LambdaCaptureDefault CaptureDefault);
5915
5916 /// Start the definition of a lambda expression.
5917 CXXMethodDecl *
5918 startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange,
5919 TypeSourceInfo *MethodType, SourceLocation EndLoc,
5920 ArrayRef<ParmVarDecl *> Params,
5921 ConstexprSpecKind ConstexprKind,
5922 Optional<std::pair<unsigned, Decl *>> Mangling = None);
5923
5924 /// Endow the lambda scope info with the relevant properties.
5925 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5926 CXXMethodDecl *CallOperator,
5927 SourceRange IntroducerRange,
5928 LambdaCaptureDefault CaptureDefault,
5929 SourceLocation CaptureDefaultLoc,
5930 bool ExplicitParams,
5931 bool ExplicitResultType,
5932 bool Mutable);
5933
5934 /// Perform initialization analysis of the init-capture and perform
5935 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5936 /// not being used to initialize a reference.
5937 ParsedType actOnLambdaInitCaptureInitialization(
5938 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
5939 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
5940 return ParsedType::make(buildLambdaInitCaptureInitialization(
5941 Loc, ByRef, EllipsisLoc, None, Id,
5942 InitKind != LambdaCaptureInitKind::CopyInit, Init));
5943 }
5944 QualType buildLambdaInitCaptureInitialization(
5945 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
5946 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
5947 Expr *&Init);
5948
5949 /// Create a dummy variable within the declcontext of the lambda's
5950 /// call operator, for name lookup purposes for a lambda init capture.
5951 ///
5952 /// CodeGen handles emission of lambda captures, ignoring these dummy
5953 /// variables appropriately.
5954 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5955 QualType InitCaptureType,
5956 SourceLocation EllipsisLoc,
5957 IdentifierInfo *Id,
5958 unsigned InitStyle, Expr *Init);
5959
5960 /// Add an init-capture to a lambda scope.
5961 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5962
5963 /// Note that we have finished the explicit captures for the
5964 /// given lambda.
5965 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5966
5967 /// \brief This is called after parsing the explicit template parameter list
5968 /// on a lambda (if it exists) in C++2a.
5969 void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
5970 ArrayRef<NamedDecl *> TParams,
5971 SourceLocation RAngleLoc);
5972
5973 /// Introduce the lambda parameters into scope.
5974 void addLambdaParameters(
5975 ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
5976 CXXMethodDecl *CallOperator, Scope *CurScope);
5977
5978 /// Deduce a block or lambda's return type based on the return
5979 /// statements present in the body.
5980 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5981
5982 /// ActOnStartOfLambdaDefinition - This is called just before we start
5983 /// parsing the body of a lambda; it analyzes the explicit captures and
5984 /// arguments, and sets up various data-structures for the body of the
5985 /// lambda.
5986 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5987 Declarator &ParamInfo, Scope *CurScope);
5988
5989 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5990 /// is invoked to pop the information about the lambda.
5991 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5992 bool IsInstantiation = false);
5993
5994 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5995 /// was successfully completed.
5996 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5997 Scope *CurScope);
5998
5999 /// Does copying/destroying the captured variable have side effects?
6000 bool CaptureHasSideEffects(const sema::Capture &From);
6001
6002 /// Diagnose if an explicit lambda capture is unused. Returns true if a
6003 /// diagnostic is emitted.
6004 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6005 const sema::Capture &From);
6006
6007 /// Build a FieldDecl suitable to hold the given capture.
6008 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6009
6010 /// Initialize the given capture with a suitable expression.
6011 ExprResult BuildCaptureInit(const sema::Capture &Capture,
6012 SourceLocation ImplicitCaptureLoc,
6013 bool IsOpenMPMapping = false);
6014
6015 /// Complete a lambda-expression having processed and attached the
6016 /// lambda body.
6017 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6018 sema::LambdaScopeInfo *LSI);
6019
6020 /// Get the return type to use for a lambda's conversion function(s) to
6021 /// function pointer type, given the type of the call operator.
6022 QualType
6023 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
6024
6025 /// Define the "body" of the conversion from a lambda object to a
6026 /// function pointer.
6027 ///
6028 /// This routine doesn't actually define a sensible body; rather, it fills
6029 /// in the initialization expression needed to copy the lambda object into
6030 /// the block, and IR generation actually generates the real body of the
6031 /// block pointer conversion.
6032 void DefineImplicitLambdaToFunctionPointerConversion(
6033 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6034
6035 /// Define the "body" of the conversion from a lambda object to a
6036 /// block pointer.
6037 ///
6038 /// This routine doesn't actually define a sensible body; rather, it fills
6039 /// in the initialization expression needed to copy the lambda object into
6040 /// the block, and IR generation actually generates the real body of the
6041 /// block pointer conversion.
6042 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6043 CXXConversionDecl *Conv);
6044
6045 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6046 SourceLocation ConvLocation,
6047 CXXConversionDecl *Conv,
6048 Expr *Src);
6049
6050 // ParseObjCStringLiteral - Parse Objective-C string literals.
6051 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6052 ArrayRef<Expr *> Strings);
6053
6054 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6055
6056 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6057 /// numeric literal expression. Type of the expression will be "NSNumber *"
6058 /// or "id" if NSNumber is unavailable.
6059 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6060 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6061 bool Value);
6062 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6063
6064 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6065 /// '@' prefixed parenthesized expression. The type of the expression will
6066 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6067 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6068 /// "const char *" or C structure with attribute 'objc_boxable'.
6069 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6070
6071 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6072 Expr *IndexExpr,
6073 ObjCMethodDecl *getterMethod,
6074 ObjCMethodDecl *setterMethod);
6075
6076 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6077 MutableArrayRef<ObjCDictionaryElement> Elements);
6078
6079 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6080 TypeSourceInfo *EncodedTypeInfo,
6081 SourceLocation RParenLoc);
6082 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6083 CXXConversionDecl *Method,
6084 bool HadMultipleCandidates);
6085
6086 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6087 SourceLocation EncodeLoc,
6088 SourceLocation LParenLoc,
6089 ParsedType Ty,
6090 SourceLocation RParenLoc);
6091
6092 /// ParseObjCSelectorExpression - Build selector expression for \@selector
6093 ExprResult ParseObjCSelectorExpression(Selector Sel,
6094 SourceLocation AtLoc,
6095 SourceLocation SelLoc,
6096 SourceLocation LParenLoc,
6097 SourceLocation RParenLoc,
6098 bool WarnMultipleSelectors);
6099
6100 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6101 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6102 SourceLocation AtLoc,
6103 SourceLocation ProtoLoc,
6104 SourceLocation LParenLoc,
6105 SourceLocation ProtoIdLoc,
6106 SourceLocation RParenLoc);
6107
6108 //===--------------------------------------------------------------------===//
6109 // C++ Declarations
6110 //
6111 Decl *ActOnStartLinkageSpecification(Scope *S,
6112 SourceLocation ExternLoc,
6113 Expr *LangStr,
6114 SourceLocation LBraceLoc);
6115 Decl *ActOnFinishLinkageSpecification(Scope *S,
6116 Decl *LinkageSpec,
6117 SourceLocation RBraceLoc);
6118
6119
6120 //===--------------------------------------------------------------------===//
6121 // C++ Classes
6122 //
6123 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6124 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6125 const CXXScopeSpec *SS = nullptr);
6126 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6127
6128 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6129 SourceLocation ColonLoc,
6130 const ParsedAttributesView &Attrs);
6131
6132 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6133 Declarator &D,
6134 MultiTemplateParamsArg TemplateParameterLists,
6135 Expr *BitfieldWidth, const VirtSpecifiers &VS,
6136 InClassInitStyle InitStyle);
6137
6138 void ActOnStartCXXInClassMemberInitializer();
6139 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6140 SourceLocation EqualLoc,
6141 Expr *Init);
6142
6143 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6144 Scope *S,
6145 CXXScopeSpec &SS,
6146 IdentifierInfo *MemberOrBase,
6147 ParsedType TemplateTypeTy,
6148 const DeclSpec &DS,
6149 SourceLocation IdLoc,
6150 SourceLocation LParenLoc,
6151 ArrayRef<Expr *> Args,
6152 SourceLocation RParenLoc,
6153 SourceLocation EllipsisLoc);
6154
6155 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6156 Scope *S,
6157 CXXScopeSpec &SS,
6158 IdentifierInfo *MemberOrBase,
6159 ParsedType TemplateTypeTy,
6160 const DeclSpec &DS,
6161 SourceLocation IdLoc,
6162 Expr *InitList,
6163 SourceLocation EllipsisLoc);
6164
6165 MemInitResult BuildMemInitializer(Decl *ConstructorD,
6166 Scope *S,
6167 CXXScopeSpec &SS,
6168 IdentifierInfo *MemberOrBase,
6169 ParsedType TemplateTypeTy,
6170 const DeclSpec &DS,
6171 SourceLocation IdLoc,
6172 Expr *Init,
6173 SourceLocation EllipsisLoc);
6174
6175 MemInitResult BuildMemberInitializer(ValueDecl *Member,
6176 Expr *Init,
6177 SourceLocation IdLoc);
6178
6179 MemInitResult BuildBaseInitializer(QualType BaseType,
6180 TypeSourceInfo *BaseTInfo,
6181 Expr *Init,
6182 CXXRecordDecl *ClassDecl,
6183 SourceLocation EllipsisLoc);
6184
6185 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
6186 Expr *Init,
6187 CXXRecordDecl *ClassDecl);
6188
6189 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6190 CXXCtorInitializer *Initializer);
6191
6192 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6193 ArrayRef<CXXCtorInitializer *> Initializers = None);
6194
6195 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
6196
6197
6198 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6199 /// mark all the non-trivial destructors of its members and bases as
6200 /// referenced.
6201 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6202 CXXRecordDecl *Record);
6203
6204 /// The list of classes whose vtables have been used within
6205 /// this translation unit, and the source locations at which the
6206 /// first use occurred.
6207 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
6208
6209 /// The list of vtables that are required but have not yet been
6210 /// materialized.
6211 SmallVector<VTableUse, 16> VTableUses;
6212
6213 /// The set of classes whose vtables have been used within
6214 /// this translation unit, and a bit that will be true if the vtable is
6215 /// required to be emitted (otherwise, it should be emitted only if needed
6216 /// by code generation).
6217 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6218
6219 /// Load any externally-stored vtable uses.
6220 void LoadExternalVTableUses();
6221
6222 /// Note that the vtable for the given class was used at the
6223 /// given location.
6224 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6225 bool DefinitionRequired = false);
6226
6227 /// Mark the exception specifications of all virtual member functions
6228 /// in the given class as needed.
6229 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6230 const CXXRecordDecl *RD);
6231
6232 /// MarkVirtualMembersReferenced - Will mark all members of the given
6233 /// CXXRecordDecl referenced.
6234 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6235 bool ConstexprOnly = false);
6236
6237 /// Define all of the vtables that have been used in this
6238 /// translation unit and reference any virtual members used by those
6239 /// vtables.
6240 ///
6241 /// \returns true if any work was done, false otherwise.
6242 bool DefineUsedVTables();
6243
6244 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6245
6246 void ActOnMemInitializers(Decl *ConstructorDecl,
6247 SourceLocation ColonLoc,
6248 ArrayRef<CXXCtorInitializer*> MemInits,
6249 bool AnyErrors);
6250
6251 /// Check class-level dllimport/dllexport attribute. The caller must
6252 /// ensure that referenceDLLExportedClassMethods is called some point later
6253 /// when all outer classes of Class are complete.
6254 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6255 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6256
6257 void referenceDLLExportedClassMethods();
6258
6259 void propagateDLLAttrToBaseClassTemplate(
6260 CXXRecordDecl *Class, Attr *ClassAttr,
6261 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6262 SourceLocation BaseLoc);
6263
6264 /// Add gsl::Pointer attribute to std::container::iterator
6265 /// \param ND The declaration that introduces the name
6266 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
6267 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
6268
6269 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
6270 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
6271
6272 /// Add [[gsl::Pointer]] attributes for std:: types.
6273 void inferGslPointerAttribute(TypedefNameDecl *TD);
6274
6275 void CheckCompletedCXXClass(CXXRecordDecl *Record);
6276
6277 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6278 /// conditions that are needed for the attribute to have an effect.
6279 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6280
6281 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6282 Decl *TagDecl, SourceLocation LBrac,
6283 SourceLocation RBrac,
6284 const ParsedAttributesView &AttrList);
6285 void ActOnFinishCXXMemberDecls();
6286 void ActOnFinishCXXNonNestedClass(Decl *D);
6287
6288 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6289 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
6290 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6291 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6292 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6293 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6294 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6295 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6296 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
6297 CachedTokens &Toks);
6298 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
6299 bool IsInsideALocalClassWithinATemplateFunction();
6300
6301 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6302 Expr *AssertExpr,
6303 Expr *AssertMessageExpr,
6304 SourceLocation RParenLoc);
6305 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6306 Expr *AssertExpr,
6307 StringLiteral *AssertMessageExpr,
6308 SourceLocation RParenLoc,
6309 bool Failed);
6310
6311 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
6312 SourceLocation FriendLoc,
6313 TypeSourceInfo *TSInfo);
6314 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6315 MultiTemplateParamsArg TemplateParams);
6316 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6317 MultiTemplateParamsArg TemplateParams);
6318
6319 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6320 StorageClass& SC);
6321 void CheckConstructor(CXXConstructorDecl *Constructor);
6322 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6323 StorageClass& SC);
6324 bool CheckDestructor(CXXDestructorDecl *Destructor);
6325 void CheckConversionDeclarator(Declarator &D, QualType &R,
6326 StorageClass& SC);
6327 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6328 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6329 StorageClass &SC);
6330 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
6331
6332 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
6333 void CheckDelayedMemberExceptionSpecs();
6334
6335 //===--------------------------------------------------------------------===//
6336 // C++ Derived Classes
6337 //
6338
6339 /// ActOnBaseSpecifier - Parsed a base specifier
6340 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6341 SourceRange SpecifierRange,
6342 bool Virtual, AccessSpecifier Access,
6343 TypeSourceInfo *TInfo,
6344 SourceLocation EllipsisLoc);
6345
6346 BaseResult ActOnBaseSpecifier(Decl *classdecl,
6347 SourceRange SpecifierRange,
6348 ParsedAttributes &Attrs,
6349 bool Virtual, AccessSpecifier Access,
6350 ParsedType basetype,
6351 SourceLocation BaseLoc,
6352 SourceLocation EllipsisLoc);
6353
6354 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6355 MutableArrayRef<CXXBaseSpecifier *> Bases);
6356 void ActOnBaseSpecifiers(Decl *ClassDecl,
6357 MutableArrayRef<CXXBaseSpecifier *> Bases);
6358
6359 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6360 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6361 CXXBasePaths &Paths);
6362
6363 // FIXME: I don't like this name.
6364 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6365
6366 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6367 SourceLocation Loc, SourceRange Range,
6368 CXXCastPath *BasePath = nullptr,
6369 bool IgnoreAccess = false);
6370 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6371 unsigned InaccessibleBaseID,
6372 unsigned AmbigiousBaseConvID,
6373 SourceLocation Loc, SourceRange Range,
6374 DeclarationName Name,
6375 CXXCastPath *BasePath,
6376 bool IgnoreAccess = false);
6377
6378 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6379
6380 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6381 const CXXMethodDecl *Old);
6382
6383 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6384 /// covariant, according to C++ [class.virtual]p5.
6385 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6386 const CXXMethodDecl *Old);
6387
6388 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6389 /// spec is a subset of base spec.
6390 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6391 const CXXMethodDecl *Old);
6392
6393 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6394
6395 /// CheckOverrideControl - Check C++11 override control semantics.
6396 void CheckOverrideControl(NamedDecl *D);
6397
6398 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6399 /// not used in the declaration of an overriding method.
6400 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
6401
6402 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
6403 /// overrides a virtual member function marked 'final', according to
6404 /// C++11 [class.virtual]p4.
6405 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6406 const CXXMethodDecl *Old);
6407
6408
6409 //===--------------------------------------------------------------------===//
6410 // C++ Access Control
6411 //
6412
6413 enum AccessResult {
6414 AR_accessible,
6415 AR_inaccessible,
6416 AR_dependent,
6417 AR_delayed
6418 };
6419
6420 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
6421 NamedDecl *PrevMemberDecl,
6422 AccessSpecifier LexicalAS);
6423
6424 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
6425 DeclAccessPair FoundDecl);
6426 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
6427 DeclAccessPair FoundDecl);
6428 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
6429 SourceRange PlacementRange,
6430 CXXRecordDecl *NamingClass,
6431 DeclAccessPair FoundDecl,
6432 bool Diagnose = true);
6433 AccessResult CheckConstructorAccess(SourceLocation Loc,
6434 CXXConstructorDecl *D,
6435 DeclAccessPair FoundDecl,
6436 const InitializedEntity &Entity,
6437 bool IsCopyBindingRefToTemp = false);
6438 AccessResult CheckConstructorAccess(SourceLocation Loc,
6439 CXXConstructorDecl *D,
6440 DeclAccessPair FoundDecl,
6441 const InitializedEntity &Entity,
6442 const PartialDiagnostic &PDiag);
6443 AccessResult CheckDestructorAccess(SourceLocation Loc,
6444 CXXDestructorDecl *Dtor,
6445 const PartialDiagnostic &PDiag,
6446 QualType objectType = QualType());
6447 AccessResult CheckFriendAccess(NamedDecl *D);
6448 AccessResult CheckMemberAccess(SourceLocation UseLoc,
6449 CXXRecordDecl *NamingClass,
6450 DeclAccessPair Found);
6451 AccessResult
6452 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
6453 CXXRecordDecl *DecomposedClass,
6454 DeclAccessPair Field);
6455 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
6456 Expr *ObjectExpr,
6457 Expr *ArgExpr,
6458 DeclAccessPair FoundDecl);
6459 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
6460 DeclAccessPair FoundDecl);
6461 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
6462 QualType Base, QualType Derived,
6463 const CXXBasePath &Path,
6464 unsigned DiagID,
6465 bool ForceCheck = false,
6466 bool ForceUnprivileged = false);
6467 void CheckLookupAccess(const LookupResult &R);
6468 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
6469 QualType BaseType);
6470 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
6471 AccessSpecifier access,
6472 QualType objectType);
6473
6474 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6475 const MultiLevelTemplateArgumentList &TemplateArgs);
6476 void PerformDependentDiagnostics(const DeclContext *Pattern,
6477 const MultiLevelTemplateArgumentList &TemplateArgs);
6478
6479 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6480
6481 /// When true, access checking violations are treated as SFINAE
6482 /// failures rather than hard errors.
6483 bool AccessCheckingSFINAE;
6484
6485 enum AbstractDiagSelID {
6486 AbstractNone = -1,
6487 AbstractReturnType,
6488 AbstractParamType,
6489 AbstractVariableType,
6490 AbstractFieldType,
6491 AbstractIvarType,
6492 AbstractSynthesizedIvarType,
6493 AbstractArrayType
6494 };
6495
6496 bool isAbstractType(SourceLocation Loc, QualType T);
6497 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6498 TypeDiagnoser &Diagnoser);
6499 template <typename... Ts>
6500 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6501 const Ts &...Args) {
6502 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6503 return RequireNonAbstractType(Loc, T, Diagnoser);
6504 }
6505
6506 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6507
6508 //===--------------------------------------------------------------------===//
6509 // C++ Overloaded Operators [C++ 13.5]
6510 //
6511
6512 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6513
6514 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6515
6516 //===--------------------------------------------------------------------===//
6517 // C++ Templates [C++ 14]
6518 //
6519 void FilterAcceptableTemplateNames(LookupResult &R,
6520 bool AllowFunctionTemplates = true,
6521 bool AllowDependent = true);
6522 bool hasAnyAcceptableTemplateNames(LookupResult &R,
6523 bool AllowFunctionTemplates = true,
6524 bool AllowDependent = true,
6525 bool AllowNonTemplateFunctions = false);
6526 /// Try to interpret the lookup result D as a template-name.
6527 ///
6528 /// \param D A declaration found by name lookup.
6529 /// \param AllowFunctionTemplates Whether function templates should be
6530 /// considered valid results.
6531 /// \param AllowDependent Whether unresolved using declarations (that might
6532 /// name templates) should be considered valid results.
6533 NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
6534 bool AllowFunctionTemplates = true,
6535 bool AllowDependent = true);
6536
6537 enum class AssumedTemplateKind {
6538 /// This is not assumed to be a template name.
6539 None,
6540 /// This is assumed to be a template name because lookup found nothing.
6541 FoundNothing,
6542 /// This is assumed to be a template name because lookup found one or more
6543 /// functions (but no function templates).
6544 FoundFunctions,
6545 };
6546 bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6547 QualType ObjectType, bool EnteringContext,
6548 bool &MemberOfUnknownSpecialization,
6549 SourceLocation TemplateKWLoc = SourceLocation(),
6550 AssumedTemplateKind *ATK = nullptr);
6551
6552 TemplateNameKind isTemplateName(Scope *S,
6553 CXXScopeSpec &SS,
6554 bool hasTemplateKeyword,
6555 const UnqualifiedId &Name,
6556 ParsedType ObjectType,
6557 bool EnteringContext,
6558 TemplateTy &Template,
6559 bool &MemberOfUnknownSpecialization);
6560
6561 /// Try to resolve an undeclared template name as a type template.
6562 ///
6563 /// Sets II to the identifier corresponding to the template name, and updates
6564 /// Name to a corresponding (typo-corrected) type template name and TNK to
6565 /// the corresponding kind, if possible.
6566 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
6567 TemplateNameKind &TNK,
6568 SourceLocation NameLoc,
6569 IdentifierInfo *&II);
6570
6571 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
6572 SourceLocation NameLoc,
6573 bool Diagnose = true);
6574
6575 /// Determine whether a particular identifier might be the name in a C++1z
6576 /// deduction-guide declaration.
6577 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6578 SourceLocation NameLoc,
6579 ParsedTemplateTy *Template = nullptr);
6580
6581 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6582 SourceLocation IILoc,
6583 Scope *S,
6584 const CXXScopeSpec *SS,
6585 TemplateTy &SuggestedTemplate,
6586 TemplateNameKind &SuggestedKind);
6587
6588 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6589 NamedDecl *Instantiation,
6590 bool InstantiatedFromMember,
6591 const NamedDecl *Pattern,
6592 const NamedDecl *PatternDef,
6593 TemplateSpecializationKind TSK,
6594 bool Complain = true);
6595
6596 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6597 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6598
6599 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6600 SourceLocation EllipsisLoc,
6601 SourceLocation KeyLoc,
6602 IdentifierInfo *ParamName,
6603 SourceLocation ParamNameLoc,
6604 unsigned Depth, unsigned Position,
6605 SourceLocation EqualLoc,
6606 ParsedType DefaultArg);
6607
6608 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6609 SourceLocation Loc);
6610 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6611
6612 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6613 unsigned Depth,
6614 unsigned Position,
6615 SourceLocation EqualLoc,
6616 Expr *DefaultArg);
6617 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6618 SourceLocation TmpLoc,
6619 TemplateParameterList *Params,
6620 SourceLocation EllipsisLoc,
6621 IdentifierInfo *ParamName,
6622 SourceLocation ParamNameLoc,
6623 unsigned Depth,
6624 unsigned Position,
6625 SourceLocation EqualLoc,
6626 ParsedTemplateArgument DefaultArg);
6627
6628 TemplateParameterList *
6629 ActOnTemplateParameterList(unsigned Depth,
6630 SourceLocation ExportLoc,
6631 SourceLocation TemplateLoc,
6632 SourceLocation LAngleLoc,
6633 ArrayRef<NamedDecl *> Params,
6634 SourceLocation RAngleLoc,
6635 Expr *RequiresClause);
6636
6637 /// The context in which we are checking a template parameter list.
6638 enum TemplateParamListContext {
6639 TPC_ClassTemplate,
6640 TPC_VarTemplate,
6641 TPC_FunctionTemplate,
6642 TPC_ClassTemplateMember,
6643 TPC_FriendClassTemplate,
6644 TPC_FriendFunctionTemplate,
6645 TPC_FriendFunctionTemplateDefinition,
6646 TPC_TypeAliasTemplate
6647 };
6648
6649 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6650 TemplateParameterList *OldParams,
6651 TemplateParamListContext TPC,
6652 SkipBodyInfo *SkipBody = nullptr);
6653 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6654 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6655 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6656 ArrayRef<TemplateParameterList *> ParamLists,
6657 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6658
6659 DeclResult CheckClassTemplate(
6660 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
6661 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
6662 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
6663 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
6664 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
6665 TemplateParameterList **OuterTemplateParamLists,
6666 SkipBodyInfo *SkipBody = nullptr);
6667
6668 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6669 QualType NTTPType,
6670 SourceLocation Loc);
6671
6672 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6673 TemplateArgumentListInfo &Out);
6674
6675 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
6676
6677 void NoteAllFoundTemplates(TemplateName Name);
6678
6679 QualType CheckTemplateIdType(TemplateName Template,
6680 SourceLocation TemplateLoc,
6681 TemplateArgumentListInfo &TemplateArgs);
6682
6683 TypeResult
6684 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6685 TemplateTy Template, IdentifierInfo *TemplateII,
6686 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
6687 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
6688 bool IsCtorOrDtorName = false, bool IsClassName = false);
6689
6690 /// Parsed an elaborated-type-specifier that refers to a template-id,
6691 /// such as \c class T::template apply<U>.
6692 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6693 TypeSpecifierType TagSpec,
6694 SourceLocation TagLoc,
6695 CXXScopeSpec &SS,
6696 SourceLocation TemplateKWLoc,
6697 TemplateTy TemplateD,
6698 SourceLocation TemplateLoc,
6699 SourceLocation LAngleLoc,
6700 ASTTemplateArgsPtr TemplateArgsIn,
6701 SourceLocation RAngleLoc);
6702
6703 DeclResult ActOnVarTemplateSpecialization(
6704 Scope *S, Declarator &D, TypeSourceInfo *DI,
6705 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6706 StorageClass SC, bool IsPartialSpecialization);
6707
6708 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6709 SourceLocation TemplateLoc,
6710 SourceLocation TemplateNameLoc,
6711 const TemplateArgumentListInfo &TemplateArgs);
6712
6713 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6714 const DeclarationNameInfo &NameInfo,
6715 VarTemplateDecl *Template,
6716 SourceLocation TemplateLoc,
6717 const TemplateArgumentListInfo *TemplateArgs);
6718
6719 ExprResult
6720 CheckConceptTemplateId(const CXXScopeSpec &SS,
6721 const DeclarationNameInfo &NameInfo,
6722 ConceptDecl *Template,
6723 SourceLocation TemplateLoc,
6724 const TemplateArgumentListInfo *TemplateArgs);
6725
6726 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
6727
6728 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6729 SourceLocation TemplateKWLoc,
6730 LookupResult &R,
6731 bool RequiresADL,
6732 const TemplateArgumentListInfo *TemplateArgs);
6733
6734 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6735 SourceLocation TemplateKWLoc,
6736 const DeclarationNameInfo &NameInfo,
6737 const TemplateArgumentListInfo *TemplateArgs);
6738
6739 TemplateNameKind ActOnDependentTemplateName(
6740 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6741 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6742 TemplateTy &Template, bool AllowInjectedClassName = false);
6743
6744 DeclResult ActOnClassTemplateSpecialization(
6745 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
6746 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
6747 const ParsedAttributesView &Attr,
6748 MultiTemplateParamsArg TemplateParameterLists,
6749 SkipBodyInfo *SkipBody = nullptr);
6750
6751 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6752 TemplateDecl *PrimaryTemplate,
6753 unsigned NumExplicitArgs,
6754 ArrayRef<TemplateArgument> Args);
6755 void CheckTemplatePartialSpecialization(
6756 ClassTemplatePartialSpecializationDecl *Partial);
6757 void CheckTemplatePartialSpecialization(
6758 VarTemplatePartialSpecializationDecl *Partial);
6759
6760 Decl *ActOnTemplateDeclarator(Scope *S,
6761 MultiTemplateParamsArg TemplateParameterLists,
6762 Declarator &D);
6763
6764 bool
6765 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6766 TemplateSpecializationKind NewTSK,
6767 NamedDecl *PrevDecl,
6768 TemplateSpecializationKind PrevTSK,
6769 SourceLocation PrevPtOfInstantiation,
6770 bool &SuppressNew);
6771
6772 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6773 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6774 LookupResult &Previous);
6775
6776 bool CheckFunctionTemplateSpecialization(
6777 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6778 LookupResult &Previous, bool QualifiedFriend = false);
6779 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6780 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6781
6782 DeclResult ActOnExplicitInstantiation(
6783 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
6784 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
6785 TemplateTy Template, SourceLocation TemplateNameLoc,
6786 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
6787 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
6788
6789 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
6790 SourceLocation TemplateLoc,
6791 unsigned TagSpec, SourceLocation KWLoc,
6792 CXXScopeSpec &SS, IdentifierInfo *Name,
6793 SourceLocation NameLoc,
6794 const ParsedAttributesView &Attr);
6795
6796 DeclResult ActOnExplicitInstantiation(Scope *S,
6797 SourceLocation ExternLoc,
6798 SourceLocation TemplateLoc,
6799 Declarator &D);
6800
6801 TemplateArgumentLoc
6802 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6803 SourceLocation TemplateLoc,
6804 SourceLocation RAngleLoc,
6805 Decl *Param,
6806 SmallVectorImpl<TemplateArgument>
6807 &Converted,
6808 bool &HasDefaultArg);
6809
6810 /// Specifies the context in which a particular template
6811 /// argument is being checked.
6812 enum CheckTemplateArgumentKind {
6813 /// The template argument was specified in the code or was
6814 /// instantiated with some deduced template arguments.
6815 CTAK_Specified,
6816
6817 /// The template argument was deduced via template argument
6818 /// deduction.
6819 CTAK_Deduced,
6820
6821 /// The template argument was deduced from an array bound
6822 /// via template argument deduction.
6823 CTAK_DeducedFromArrayBound
6824 };
6825
6826 bool CheckTemplateArgument(NamedDecl *Param,
6827 TemplateArgumentLoc &Arg,
6828 NamedDecl *Template,
6829 SourceLocation TemplateLoc,
6830 SourceLocation RAngleLoc,
6831 unsigned ArgumentPackIndex,
6832 SmallVectorImpl<TemplateArgument> &Converted,
6833 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6834
6835 /// Check that the given template arguments can be be provided to
6836 /// the given template, converting the arguments along the way.
6837 ///
6838 /// \param Template The template to which the template arguments are being
6839 /// provided.
6840 ///
6841 /// \param TemplateLoc The location of the template name in the source.
6842 ///
6843 /// \param TemplateArgs The list of template arguments. If the template is
6844 /// a template template parameter, this function may extend the set of
6845 /// template arguments to also include substituted, defaulted template
6846 /// arguments.
6847 ///
6848 /// \param PartialTemplateArgs True if the list of template arguments is
6849 /// intentionally partial, e.g., because we're checking just the initial
6850 /// set of template arguments.
6851 ///
6852 /// \param Converted Will receive the converted, canonicalized template
6853 /// arguments.
6854 ///
6855 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6856 /// contain the converted forms of the template arguments as written.
6857 /// Otherwise, \p TemplateArgs will not be modified.
6858 ///
6859 /// \returns true if an error occurred, false otherwise.
6860 bool CheckTemplateArgumentList(TemplateDecl *Template,
6861 SourceLocation TemplateLoc,
6862 TemplateArgumentListInfo &TemplateArgs,
6863 bool PartialTemplateArgs,
6864 SmallVectorImpl<TemplateArgument> &Converted,
6865 bool UpdateArgsWithConversions = true);
6866
6867 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6868 TemplateArgumentLoc &Arg,
6869 SmallVectorImpl<TemplateArgument> &Converted);
6870
6871 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6872 TypeSourceInfo *Arg);
6873 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6874 QualType InstantiatedParamType, Expr *Arg,
6875 TemplateArgument &Converted,
6876 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6877 bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
6878 TemplateArgumentLoc &Arg);
6879
6880 ExprResult
6881 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6882 QualType ParamType,
6883 SourceLocation Loc);
6884 ExprResult
6885 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6886 SourceLocation Loc);
6887
6888 /// Enumeration describing how template parameter lists are compared
6889 /// for equality.
6890 enum TemplateParameterListEqualKind {
6891 /// We are matching the template parameter lists of two templates
6892 /// that might be redeclarations.
6893 ///
6894 /// \code
6895 /// template<typename T> struct X;
6896 /// template<typename T> struct X;
6897 /// \endcode
6898 TPL_TemplateMatch,
6899
6900 /// We are matching the template parameter lists of two template
6901 /// template parameters as part of matching the template parameter lists
6902 /// of two templates that might be redeclarations.
6903 ///
6904 /// \code
6905 /// template<template<int I> class TT> struct X;
6906 /// template<template<int Value> class Other> struct X;
6907 /// \endcode
6908 TPL_TemplateTemplateParmMatch,
6909
6910 /// We are matching the template parameter lists of a template
6911 /// template argument against the template parameter lists of a template
6912 /// template parameter.
6913 ///
6914 /// \code
6915 /// template<template<int Value> class Metafun> struct X;
6916 /// template<int Value> struct integer_c;
6917 /// X<integer_c> xic;
6918 /// \endcode
6919 TPL_TemplateTemplateArgumentMatch
6920 };
6921
6922 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6923 TemplateParameterList *Old,
6924 bool Complain,
6925 TemplateParameterListEqualKind Kind,
6926 SourceLocation TemplateArgLoc
6927 = SourceLocation());
6928
6929 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6930
6931 /// Called when the parser has parsed a C++ typename
6932 /// specifier, e.g., "typename T::type".
6933 ///
6934 /// \param S The scope in which this typename type occurs.
6935 /// \param TypenameLoc the location of the 'typename' keyword
6936 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6937 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6938 /// \param IdLoc the location of the identifier.
6939 TypeResult
6940 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6941 const CXXScopeSpec &SS, const IdentifierInfo &II,
6942 SourceLocation IdLoc);
6943
6944 /// Called when the parser has parsed a C++ typename
6945 /// specifier that ends in a template-id, e.g.,
6946 /// "typename MetaFun::template apply<T1, T2>".
6947 ///
6948 /// \param S The scope in which this typename type occurs.
6949 /// \param TypenameLoc the location of the 'typename' keyword
6950 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6951 /// \param TemplateLoc the location of the 'template' keyword, if any.
6952 /// \param TemplateName The template name.
6953 /// \param TemplateII The identifier used to name the template.
6954 /// \param TemplateIILoc The location of the template name.
6955 /// \param LAngleLoc The location of the opening angle bracket ('<').
6956 /// \param TemplateArgs The template arguments.
6957 /// \param RAngleLoc The location of the closing angle bracket ('>').
6958 TypeResult
6959 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6960 const CXXScopeSpec &SS,
6961 SourceLocation TemplateLoc,
6962 TemplateTy TemplateName,
6963 IdentifierInfo *TemplateII,
6964 SourceLocation TemplateIILoc,
6965 SourceLocation LAngleLoc,
6966 ASTTemplateArgsPtr TemplateArgs,
6967 SourceLocation RAngleLoc);
6968
6969 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6970 SourceLocation KeywordLoc,
6971 NestedNameSpecifierLoc QualifierLoc,
6972 const IdentifierInfo &II,
6973 SourceLocation IILoc);
6974
6975 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6976 SourceLocation Loc,
6977 DeclarationName Name);
6978 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6979
6980 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6981 bool RebuildTemplateParamsInCurrentInstantiation(
6982 TemplateParameterList *Params);
6983
6984 std::string
6985 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6986 const TemplateArgumentList &Args);
6987
6988 std::string
6989 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6990 const TemplateArgument *Args,
6991 unsigned NumArgs);
6992
6993 // Concepts
6994 Decl *ActOnConceptDefinition(
6995 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
6996 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
6997
6998 //===--------------------------------------------------------------------===//
6999 // C++ Variadic Templates (C++0x [temp.variadic])
7000 //===--------------------------------------------------------------------===//
7001
7002 /// Determine whether an unexpanded parameter pack might be permitted in this
7003 /// location. Useful for error recovery.
7004 bool isUnexpandedParameterPackPermitted();
7005
7006 /// The context in which an unexpanded parameter pack is
7007 /// being diagnosed.
7008 ///
7009 /// Note that the values of this enumeration line up with the first
7010 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
7011 enum UnexpandedParameterPackContext {
7012 /// An arbitrary expression.
7013 UPPC_Expression = 0,
7014
7015 /// The base type of a class type.
7016 UPPC_BaseType,
7017
7018 /// The type of an arbitrary declaration.
7019 UPPC_DeclarationType,
7020
7021 /// The type of a data member.
7022 UPPC_DataMemberType,
7023
7024 /// The size of a bit-field.
7025 UPPC_BitFieldWidth,
7026
7027 /// The expression in a static assertion.
7028 UPPC_StaticAssertExpression,
7029
7030 /// The fixed underlying type of an enumeration.
7031 UPPC_FixedUnderlyingType,
7032
7033 /// The enumerator value.
7034 UPPC_EnumeratorValue,
7035
7036 /// A using declaration.
7037 UPPC_UsingDeclaration,
7038
7039 /// A friend declaration.
7040 UPPC_FriendDeclaration,
7041
7042 /// A declaration qualifier.
7043 UPPC_DeclarationQualifier,
7044
7045 /// An initializer.
7046 UPPC_Initializer,
7047
7048 /// A default argument.
7049 UPPC_DefaultArgument,
7050
7051 /// The type of a non-type template parameter.
7052 UPPC_NonTypeTemplateParameterType,
7053
7054 /// The type of an exception.
7055 UPPC_ExceptionType,
7056
7057 /// Partial specialization.
7058 UPPC_PartialSpecialization,
7059
7060 /// Microsoft __if_exists.
7061 UPPC_IfExists,
7062
7063 /// Microsoft __if_not_exists.
7064 UPPC_IfNotExists,
7065
7066 /// Lambda expression.
7067 UPPC_Lambda,
7068
7069 /// Block expression,
7070 UPPC_Block
7071 };
7072
7073 /// Diagnose unexpanded parameter packs.
7074 ///
7075 /// \param Loc The location at which we should emit the diagnostic.
7076 ///
7077 /// \param UPPC The context in which we are diagnosing unexpanded
7078 /// parameter packs.
7079 ///
7080 /// \param Unexpanded the set of unexpanded parameter packs.
7081 ///
7082 /// \returns true if an error occurred, false otherwise.
7083 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
7084 UnexpandedParameterPackContext UPPC,
7085 ArrayRef<UnexpandedParameterPack> Unexpanded);
7086
7087 /// If the given type contains an unexpanded parameter pack,
7088 /// diagnose the error.
7089 ///
7090 /// \param Loc The source location where a diagnostc should be emitted.
7091 ///
7092 /// \param T The type that is being checked for unexpanded parameter
7093 /// packs.
7094 ///
7095 /// \returns true if an error occurred, false otherwise.
7096 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
7097 UnexpandedParameterPackContext UPPC);
7098
7099 /// If the given expression contains an unexpanded parameter
7100 /// pack, diagnose the error.
7101 ///
7102 /// \param E The expression that is being checked for unexpanded
7103 /// parameter packs.
7104 ///
7105 /// \returns true if an error occurred, false otherwise.
7106 bool DiagnoseUnexpandedParameterPack(Expr *E,
7107 UnexpandedParameterPackContext UPPC = UPPC_Expression);
7108
7109 /// If the given nested-name-specifier contains an unexpanded
7110 /// parameter pack, diagnose the error.
7111 ///
7112 /// \param SS The nested-name-specifier that is being checked for
7113 /// unexpanded parameter packs.
7114 ///
7115 /// \returns true if an error occurred, false otherwise.
7116 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
7117 UnexpandedParameterPackContext UPPC);
7118
7119 /// If the given name contains an unexpanded parameter pack,
7120 /// diagnose the error.
7121 ///
7122 /// \param NameInfo The name (with source location information) that
7123 /// is being checked for unexpanded parameter packs.
7124 ///
7125 /// \returns true if an error occurred, false otherwise.
7126 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
7127 UnexpandedParameterPackContext UPPC);
7128
7129 /// If the given template name contains an unexpanded parameter pack,
7130 /// diagnose the error.
7131 ///
7132 /// \param Loc The location of the template name.
7133 ///
7134 /// \param Template The template name that is being checked for unexpanded
7135 /// parameter packs.
7136 ///
7137 /// \returns true if an error occurred, false otherwise.
7138 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
7139 TemplateName Template,
7140 UnexpandedParameterPackContext UPPC);
7141
7142 /// If the given template argument contains an unexpanded parameter
7143 /// pack, diagnose the error.
7144 ///
7145 /// \param Arg The template argument that is being checked for unexpanded
7146 /// parameter packs.
7147 ///
7148 /// \returns true if an error occurred, false otherwise.
7149 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
7150 UnexpandedParameterPackContext UPPC);
7151
7152 /// Collect the set of unexpanded parameter packs within the given
7153 /// template argument.
7154 ///
7155 /// \param Arg The template argument that will be traversed to find
7156 /// unexpanded parameter packs.
7157 void collectUnexpandedParameterPacks(TemplateArgument Arg,
7158 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7159
7160 /// Collect the set of unexpanded parameter packs within the given
7161 /// template argument.
7162 ///
7163 /// \param Arg The template argument that will be traversed to find
7164 /// unexpanded parameter packs.
7165 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
7166 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7167
7168 /// Collect the set of unexpanded parameter packs within the given
7169 /// type.
7170 ///
7171 /// \param T The type that will be traversed to find
7172 /// unexpanded parameter packs.
7173 void collectUnexpandedParameterPacks(QualType T,
7174 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7175
7176 /// Collect the set of unexpanded parameter packs within the given
7177 /// type.
7178 ///
7179 /// \param TL The type that will be traversed to find
7180 /// unexpanded parameter packs.
7181 void collectUnexpandedParameterPacks(TypeLoc TL,
7182 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7183
7184 /// Collect the set of unexpanded parameter packs within the given
7185 /// nested-name-specifier.
7186 ///
7187 /// \param NNS The nested-name-specifier that will be traversed to find
7188 /// unexpanded parameter packs.
7189 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
7190 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7191
7192 /// Collect the set of unexpanded parameter packs within the given
7193 /// name.
7194 ///
7195 /// \param NameInfo The name that will be traversed to find
7196 /// unexpanded parameter packs.
7197 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
7198 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7199
7200 /// Invoked when parsing a template argument followed by an
7201 /// ellipsis, which creates a pack expansion.
7202 ///
7203 /// \param Arg The template argument preceding the ellipsis, which
7204 /// may already be invalid.
7205 ///
7206 /// \param EllipsisLoc The location of the ellipsis.
7207 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
7208 SourceLocation EllipsisLoc);
7209
7210 /// Invoked when parsing a type followed by an ellipsis, which
7211 /// creates a pack expansion.
7212 ///
7213 /// \param Type The type preceding the ellipsis, which will become
7214 /// the pattern of the pack expansion.
7215 ///
7216 /// \param EllipsisLoc The location of the ellipsis.
7217 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
7218
7219 /// Construct a pack expansion type from the pattern of the pack
7220 /// expansion.
7221 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
7222 SourceLocation EllipsisLoc,
7223 Optional<unsigned> NumExpansions);
7224
7225 /// Construct a pack expansion type from the pattern of the pack
7226 /// expansion.
7227 QualType CheckPackExpansion(QualType Pattern,
7228 SourceRange PatternRange,
7229 SourceLocation EllipsisLoc,
7230 Optional<unsigned> NumExpansions);
7231
7232 /// Invoked when parsing an expression followed by an ellipsis, which
7233 /// creates a pack expansion.
7234 ///
7235 /// \param Pattern The expression preceding the ellipsis, which will become
7236 /// the pattern of the pack expansion.
7237 ///
7238 /// \param EllipsisLoc The location of the ellipsis.
7239 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
7240
7241 /// Invoked when parsing an expression followed by an ellipsis, which
7242 /// creates a pack expansion.
7243 ///
7244 /// \param Pattern The expression preceding the ellipsis, which will become
7245 /// the pattern of the pack expansion.
7246 ///
7247 /// \param EllipsisLoc The location of the ellipsis.
7248 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
7249 Optional<unsigned> NumExpansions);
7250
7251 /// Determine whether we could expand a pack expansion with the
7252 /// given set of parameter packs into separate arguments by repeatedly
7253 /// transforming the pattern.
7254 ///
7255 /// \param EllipsisLoc The location of the ellipsis that identifies the
7256 /// pack expansion.
7257 ///
7258 /// \param PatternRange The source range that covers the entire pattern of
7259 /// the pack expansion.
7260 ///
7261 /// \param Unexpanded The set of unexpanded parameter packs within the
7262 /// pattern.
7263 ///
7264 /// \param ShouldExpand Will be set to \c true if the transformer should
7265 /// expand the corresponding pack expansions into separate arguments. When
7266 /// set, \c NumExpansions must also be set.
7267 ///
7268 /// \param RetainExpansion Whether the caller should add an unexpanded
7269 /// pack expansion after all of the expanded arguments. This is used
7270 /// when extending explicitly-specified template argument packs per
7271 /// C++0x [temp.arg.explicit]p9.
7272 ///
7273 /// \param NumExpansions The number of separate arguments that will be in
7274 /// the expanded form of the corresponding pack expansion. This is both an
7275 /// input and an output parameter, which can be set by the caller if the
7276 /// number of expansions is known a priori (e.g., due to a prior substitution)
7277 /// and will be set by the callee when the number of expansions is known.
7278 /// The callee must set this value when \c ShouldExpand is \c true; it may
7279 /// set this value in other cases.
7280 ///
7281 /// \returns true if an error occurred (e.g., because the parameter packs
7282 /// are to be instantiated with arguments of different lengths), false
7283 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
7284 /// must be set.
7285 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
7286 SourceRange PatternRange,
7287 ArrayRef<UnexpandedParameterPack> Unexpanded,
7288 const MultiLevelTemplateArgumentList &TemplateArgs,
7289 bool &ShouldExpand,
7290 bool &RetainExpansion,
7291 Optional<unsigned> &NumExpansions);
7292
7293 /// Determine the number of arguments in the given pack expansion
7294 /// type.
7295 ///
7296 /// This routine assumes that the number of arguments in the expansion is
7297 /// consistent across all of the unexpanded parameter packs in its pattern.
7298 ///
7299 /// Returns an empty Optional if the type can't be expanded.
7300 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
7301 const MultiLevelTemplateArgumentList &TemplateArgs);
7302
7303 /// Determine whether the given declarator contains any unexpanded
7304 /// parameter packs.
7305 ///
7306 /// This routine is used by the parser to disambiguate function declarators
7307 /// with an ellipsis prior to the ')', e.g.,
7308 ///
7309 /// \code
7310 /// void f(T...);
7311 /// \endcode
7312 ///
7313 /// To determine whether we have an (unnamed) function parameter pack or
7314 /// a variadic function.
7315 ///
7316 /// \returns true if the declarator contains any unexpanded parameter packs,
7317 /// false otherwise.
7318 bool containsUnexpandedParameterPacks(Declarator &D);
7319
7320 /// Returns the pattern of the pack expansion for a template argument.
7321 ///
7322 /// \param OrigLoc The template argument to expand.
7323 ///
7324 /// \param Ellipsis Will be set to the location of the ellipsis.
7325 ///
7326 /// \param NumExpansions Will be set to the number of expansions that will
7327 /// be generated from this pack expansion, if known a priori.
7328 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
7329 TemplateArgumentLoc OrigLoc,
7330 SourceLocation &Ellipsis,
7331 Optional<unsigned> &NumExpansions) const;
7332
7333 /// Given a template argument that contains an unexpanded parameter pack, but
7334 /// which has already been substituted, attempt to determine the number of
7335 /// elements that will be produced once this argument is fully-expanded.
7336 ///
7337 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
7338 /// avoid actually expanding the pack where possible.
7339 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
7340
7341 //===--------------------------------------------------------------------===//
7342 // C++ Template Argument Deduction (C++ [temp.deduct])
7343 //===--------------------------------------------------------------------===//
7344
7345 /// Adjust the type \p ArgFunctionType to match the calling convention,
7346 /// noreturn, and optionally the exception specification of \p FunctionType.
7347 /// Deduction often wants to ignore these properties when matching function
7348 /// types.
7349 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
7350 bool AdjustExceptionSpec = false);
7351
7352 /// Describes the result of template argument deduction.
7353 ///
7354 /// The TemplateDeductionResult enumeration describes the result of
7355 /// template argument deduction, as returned from
7356 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
7357 /// structure provides additional information about the results of
7358 /// template argument deduction, e.g., the deduced template argument
7359 /// list (if successful) or the specific template parameters or
7360 /// deduced arguments that were involved in the failure.
7361 enum TemplateDeductionResult {
7362 /// Template argument deduction was successful.
7363 TDK_Success = 0,
7364 /// The declaration was invalid; do nothing.
7365 TDK_Invalid,
7366 /// Template argument deduction exceeded the maximum template
7367 /// instantiation depth (which has already been diagnosed).
7368 TDK_InstantiationDepth,
7369 /// Template argument deduction did not deduce a value
7370 /// for every template parameter.
7371 TDK_Incomplete,
7372 /// Template argument deduction did not deduce a value for every
7373 /// expansion of an expanded template parameter pack.
7374 TDK_IncompletePack,
7375 /// Template argument deduction produced inconsistent
7376 /// deduced values for the given template parameter.
7377 TDK_Inconsistent,
7378 /// Template argument deduction failed due to inconsistent
7379 /// cv-qualifiers on a template parameter type that would
7380 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
7381 /// but were given a non-const "X".
7382 TDK_Underqualified,
7383 /// Substitution of the deduced template argument values
7384 /// resulted in an error.
7385 TDK_SubstitutionFailure,
7386 /// After substituting deduced template arguments, a dependent
7387 /// parameter type did not match the corresponding argument.
7388 TDK_DeducedMismatch,
7389 /// After substituting deduced template arguments, an element of
7390 /// a dependent parameter type did not match the corresponding element
7391 /// of the corresponding argument (when deducing from an initializer list).
7392 TDK_DeducedMismatchNested,
7393 /// A non-depnedent component of the parameter did not match the
7394 /// corresponding component of the argument.
7395 TDK_NonDeducedMismatch,
7396 /// When performing template argument deduction for a function
7397 /// template, there were too many call arguments.
7398 TDK_TooManyArguments,
7399 /// When performing template argument deduction for a function
7400 /// template, there were too few call arguments.
7401 TDK_TooFewArguments,
7402 /// The explicitly-specified template arguments were not valid
7403 /// template arguments for the given template.
7404 TDK_InvalidExplicitArguments,
7405 /// Checking non-dependent argument conversions failed.
7406 TDK_NonDependentConversionFailure,
7407 /// Deduction failed; that's all we know.
7408 TDK_MiscellaneousDeductionFailure,
7409 /// CUDA Target attributes do not match.
7410 TDK_CUDATargetMismatch
7411 };
7412
7413 TemplateDeductionResult
7414 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
7415 const TemplateArgumentList &TemplateArgs,
7416 sema::TemplateDeductionInfo &Info);
7417
7418 TemplateDeductionResult
7419 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
7420 const TemplateArgumentList &TemplateArgs,
7421 sema::TemplateDeductionInfo &Info);
7422
7423 TemplateDeductionResult SubstituteExplicitTemplateArguments(
7424 FunctionTemplateDecl *FunctionTemplate,
7425 TemplateArgumentListInfo &ExplicitTemplateArgs,
7426 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7427 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
7428 sema::TemplateDeductionInfo &Info);
7429
7430 /// brief A function argument from which we performed template argument
7431 // deduction for a call.
7432 struct OriginalCallArg {
7433 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
7434 unsigned ArgIdx, QualType OriginalArgType)
7435 : OriginalParamType(OriginalParamType),
7436 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
7437 OriginalArgType(OriginalArgType) {}
7438
7439 QualType OriginalParamType;
7440 bool DecomposedParam;
7441 unsigned ArgIdx;
7442 QualType OriginalArgType;
7443 };
7444
7445 TemplateDeductionResult FinishTemplateArgumentDeduction(
7446 FunctionTemplateDecl *FunctionTemplate,
7447 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7448 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
7449 sema::TemplateDeductionInfo &Info,
7450 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
7451 bool PartialOverloading = false,
7452 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
7453
7454 TemplateDeductionResult DeduceTemplateArguments(
7455 FunctionTemplateDecl *FunctionTemplate,
7456 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7457 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
7458 bool PartialOverloading,
7459 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
7460
7461 TemplateDeductionResult
7462 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7463 TemplateArgumentListInfo *ExplicitTemplateArgs,
7464 QualType ArgFunctionType,
7465 FunctionDecl *&Specialization,
7466 sema::TemplateDeductionInfo &Info,
7467 bool IsAddressOfFunction = false);
7468
7469 TemplateDeductionResult
7470 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7471 QualType ToType,
7472 CXXConversionDecl *&Specialization,
7473 sema::TemplateDeductionInfo &Info);
7474
7475 TemplateDeductionResult
7476 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7477 TemplateArgumentListInfo *ExplicitTemplateArgs,
7478 FunctionDecl *&Specialization,
7479 sema::TemplateDeductionInfo &Info,
7480 bool IsAddressOfFunction = false);
7481
7482 /// Substitute Replacement for \p auto in \p TypeWithAuto
7483 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
7484 /// Substitute Replacement for auto in TypeWithAuto
7485 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
7486 QualType Replacement);
7487 /// Completely replace the \c auto in \p TypeWithAuto by
7488 /// \p Replacement. This does not retain any \c auto type sugar.
7489 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
7490
7491 /// Result type of DeduceAutoType.
7492 enum DeduceAutoResult {
7493 DAR_Succeeded,
7494 DAR_Failed,
7495 DAR_FailedAlreadyDiagnosed
7496 };
7497
7498 DeduceAutoResult
7499 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
7500 Optional<unsigned> DependentDeductionDepth = None);
7501 DeduceAutoResult
7502 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
7503 Optional<unsigned> DependentDeductionDepth = None);
7504 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7505 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7506 bool Diagnose = true);
7507
7508 /// Declare implicit deduction guides for a class template if we've
7509 /// not already done so.
7510 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7511 SourceLocation Loc);
7512
7513 QualType DeduceTemplateSpecializationFromInitializer(
7514 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7515 const InitializationKind &Kind, MultiExprArg Init);
7516
7517 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7518 QualType Type, TypeSourceInfo *TSI,
7519 SourceRange Range, bool DirectInit,
7520 Expr *Init);
7521
7522 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7523
7524 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7525 SourceLocation ReturnLoc,
7526 Expr *&RetExpr, AutoType *AT);
7527
7528 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7529 FunctionTemplateDecl *FT2,
7530 SourceLocation Loc,
7531 TemplatePartialOrderingContext TPOC,
7532 unsigned NumCallArguments1,
7533 unsigned NumCallArguments2);
7534 UnresolvedSetIterator
7535 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7536 TemplateSpecCandidateSet &FailedCandidates,
7537 SourceLocation Loc,
7538 const PartialDiagnostic &NoneDiag,
7539 const PartialDiagnostic &AmbigDiag,
7540 const PartialDiagnostic &CandidateDiag,
7541 bool Complain = true, QualType TargetType = QualType());
7542
7543 ClassTemplatePartialSpecializationDecl *
7544 getMoreSpecializedPartialSpecialization(
7545 ClassTemplatePartialSpecializationDecl *PS1,
7546 ClassTemplatePartialSpecializationDecl *PS2,
7547 SourceLocation Loc);
7548
7549 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7550 sema::TemplateDeductionInfo &Info);
7551
7552 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7553 VarTemplatePartialSpecializationDecl *PS1,
7554 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7555
7556 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7557 sema::TemplateDeductionInfo &Info);
7558
7559 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7560 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
7561
7562 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7563 bool OnlyDeduced,
7564 unsigned Depth,
7565 llvm::SmallBitVector &Used);
7566 void MarkDeducedTemplateParameters(
7567 const FunctionTemplateDecl *FunctionTemplate,
7568 llvm::SmallBitVector &Deduced) {
7569 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7570 }
7571 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
7572 const FunctionTemplateDecl *FunctionTemplate,
7573 llvm::SmallBitVector &Deduced);
7574
7575 //===--------------------------------------------------------------------===//
7576 // C++ Template Instantiation
7577 //
7578
7579 MultiLevelTemplateArgumentList
7580 getTemplateInstantiationArgs(NamedDecl *D,
7581 const TemplateArgumentList *Innermost = nullptr,
7582 bool RelativeToPrimary = false,
7583 const FunctionDecl *Pattern = nullptr);
7584
7585 /// A context in which code is being synthesized (where a source location
7586 /// alone is not sufficient to identify the context). This covers template
7587 /// instantiation and various forms of implicitly-generated functions.
7588 struct CodeSynthesisContext {
7589 /// The kind of template instantiation we are performing
7590 enum SynthesisKind {
7591 /// We are instantiating a template declaration. The entity is
7592 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7593 TemplateInstantiation,
7594
7595 /// We are instantiating a default argument for a template
7596 /// parameter. The Entity is the template parameter whose argument is
7597 /// being instantiated, the Template is the template, and the
7598 /// TemplateArgs/NumTemplateArguments provide the template arguments as
7599 /// specified.
7600 DefaultTemplateArgumentInstantiation,
7601
7602 /// We are instantiating a default argument for a function.
7603 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7604 /// provides the template arguments as specified.
7605 DefaultFunctionArgumentInstantiation,
7606
7607 /// We are substituting explicit template arguments provided for
7608 /// a function template. The entity is a FunctionTemplateDecl.
7609 ExplicitTemplateArgumentSubstitution,
7610
7611 /// We are substituting template argument determined as part of
7612 /// template argument deduction for either a class template
7613 /// partial specialization or a function template. The
7614 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7615 /// a TemplateDecl.
7616 DeducedTemplateArgumentSubstitution,
7617
7618 /// We are substituting prior template arguments into a new
7619 /// template parameter. The template parameter itself is either a
7620 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7621 PriorTemplateArgumentSubstitution,
7622
7623 /// We are checking the validity of a default template argument that
7624 /// has been used when naming a template-id.
7625 DefaultTemplateArgumentChecking,
7626
7627 /// We are computing the exception specification for a defaulted special
7628 /// member function.
7629 ExceptionSpecEvaluation,
7630
7631 /// We are instantiating the exception specification for a function
7632 /// template which was deferred until it was needed.
7633 ExceptionSpecInstantiation,
7634
7635 /// We are declaring an implicit special member function.
7636 DeclaringSpecialMember,
7637
7638 /// We are defining a synthesized function (such as a defaulted special
7639 /// member).
7640 DefiningSynthesizedFunction,
7641
7642 /// Added for Template instantiation observation.
7643 /// Memoization means we are _not_ instantiating a template because
7644 /// it is already instantiated (but we entered a context where we
7645 /// would have had to if it was not already instantiated).
7646 Memoization
7647 } Kind;
7648
7649 /// Was the enclosing context a non-instantiation SFINAE context?
7650 bool SavedInNonInstantiationSFINAEContext;
7651
7652 /// The point of instantiation or synthesis within the source code.
7653 SourceLocation PointOfInstantiation;
7654
7655 /// The entity that is being synthesized.
7656 Decl *Entity;
7657
7658 /// The template (or partial specialization) in which we are
7659 /// performing the instantiation, for substitutions of prior template
7660 /// arguments.
7661 NamedDecl *Template;
7662
7663 /// The list of template arguments we are substituting, if they
7664 /// are not part of the entity.
7665 const TemplateArgument *TemplateArgs;
7666
7667 // FIXME: Wrap this union around more members, or perhaps store the
7668 // kind-specific members in the RAII object owning the context.
7669 union {
7670 /// The number of template arguments in TemplateArgs.
7671 unsigned NumTemplateArgs;
7672
7673 /// The special member being declared or defined.
7674 CXXSpecialMember SpecialMember;
7675 };
7676
7677 ArrayRef<TemplateArgument> template_arguments() const {
7678 assert(Kind != DeclaringSpecialMember)((Kind != DeclaringSpecialMember) ? static_cast<void> (
0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 7678, __PRETTY_FUNCTION__))
;
7679 return {TemplateArgs, NumTemplateArgs};
7680 }
7681
7682 /// The template deduction info object associated with the
7683 /// substitution or checking of explicit or deduced template arguments.
7684 sema::TemplateDeductionInfo *DeductionInfo;
7685
7686 /// The source range that covers the construct that cause
7687 /// the instantiation, e.g., the template-id that causes a class
7688 /// template instantiation.
7689 SourceRange InstantiationRange;
7690
7691 CodeSynthesisContext()
7692 : Kind(TemplateInstantiation),
7693 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
7694 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
7695 DeductionInfo(nullptr) {}
7696
7697 /// Determines whether this template is an actual instantiation
7698 /// that should be counted toward the maximum instantiation depth.
7699 bool isInstantiationRecord() const;
7700 };
7701
7702 /// List of active code synthesis contexts.
7703 ///
7704 /// This vector is treated as a stack. As synthesis of one entity requires
7705 /// synthesis of another, additional contexts are pushed onto the stack.
7706 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7707
7708 /// Specializations whose definitions are currently being instantiated.
7709 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7710
7711 /// Non-dependent types used in templates that have already been instantiated
7712 /// by some template instantiation.
7713 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7714
7715 /// Extra modules inspected when performing a lookup during a template
7716 /// instantiation. Computed lazily.
7717 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7718
7719 /// Cache of additional modules that should be used for name lookup
7720 /// within the current template instantiation. Computed lazily; use
7721 /// getLookupModules() to get a complete set.
7722 llvm::DenseSet<Module*> LookupModulesCache;
7723
7724 /// Get the set of additional modules that should be checked during
7725 /// name lookup. A module and its imports become visible when instanting a
7726 /// template defined within it.
7727 llvm::DenseSet<Module*> &getLookupModules();
7728
7729 /// Map from the most recent declaration of a namespace to the most
7730 /// recent visible declaration of that namespace.
7731 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7732
7733 /// Whether we are in a SFINAE context that is not associated with
7734 /// template instantiation.
7735 ///
7736 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7737 /// of a template instantiation or template argument deduction.
7738 bool InNonInstantiationSFINAEContext;
7739
7740 /// The number of \p CodeSynthesisContexts that are not template
7741 /// instantiations and, therefore, should not be counted as part of the
7742 /// instantiation depth.
7743 ///
7744 /// When the instantiation depth reaches the user-configurable limit
7745 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7746 // FIXME: Should we have a similar limit for other forms of synthesis?
7747 unsigned NonInstantiationEntries;
7748
7749 /// The depth of the context stack at the point when the most recent
7750 /// error or warning was produced.
7751 ///
7752 /// This value is used to suppress printing of redundant context stacks
7753 /// when there are multiple errors or warnings in the same instantiation.
7754 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7755 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7756
7757 /// The template instantiation callbacks to trace or track
7758 /// instantiations (objects can be chained).
7759 ///
7760 /// This callbacks is used to print, trace or track template
7761 /// instantiations as they are being constructed.
7762 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
7763 TemplateInstCallbacks;
7764
7765 /// The current index into pack expansion arguments that will be
7766 /// used for substitution of parameter packs.
7767 ///
7768 /// The pack expansion index will be -1 to indicate that parameter packs
7769 /// should be instantiated as themselves. Otherwise, the index specifies
7770 /// which argument within the parameter pack will be used for substitution.
7771 int ArgumentPackSubstitutionIndex;
7772
7773 /// RAII object used to change the argument pack substitution index
7774 /// within a \c Sema object.
7775 ///
7776 /// See \c ArgumentPackSubstitutionIndex for more information.
7777 class ArgumentPackSubstitutionIndexRAII {
7778 Sema &Self;
7779 int OldSubstitutionIndex;
7780
7781 public:
7782 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7783 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7784 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7785 }
7786
7787 ~ArgumentPackSubstitutionIndexRAII() {
7788 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7789 }
7790 };
7791
7792 friend class ArgumentPackSubstitutionRAII;
7793
7794 /// For each declaration that involved template argument deduction, the
7795 /// set of diagnostics that were suppressed during that template argument
7796 /// deduction.
7797 ///
7798 /// FIXME: Serialize this structure to the AST file.
7799 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7800 SuppressedDiagnosticsMap;
7801 SuppressedDiagnosticsMap SuppressedDiagnostics;
7802
7803 /// A stack object to be created when performing template
7804 /// instantiation.
7805 ///
7806 /// Construction of an object of type \c InstantiatingTemplate
7807 /// pushes the current instantiation onto the stack of active
7808 /// instantiations. If the size of this stack exceeds the maximum
7809 /// number of recursive template instantiations, construction
7810 /// produces an error and evaluates true.
7811 ///
7812 /// Destruction of this object will pop the named instantiation off
7813 /// the stack.
7814 struct InstantiatingTemplate {
7815 /// Note that we are instantiating a class template,
7816 /// function template, variable template, alias template,
7817 /// or a member thereof.
7818 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7819 Decl *Entity,
7820 SourceRange InstantiationRange = SourceRange());
7821
7822 struct ExceptionSpecification {};
7823 /// Note that we are instantiating an exception specification
7824 /// of a function template.
7825 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7826 FunctionDecl *Entity, ExceptionSpecification,
7827 SourceRange InstantiationRange = SourceRange());
7828
7829 /// Note that we are instantiating a default argument in a
7830 /// template-id.
7831 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7832 TemplateParameter Param, TemplateDecl *Template,
7833 ArrayRef<TemplateArgument> TemplateArgs,
7834 SourceRange InstantiationRange = SourceRange());
7835
7836 /// Note that we are substituting either explicitly-specified or
7837 /// deduced template arguments during function template argument deduction.
7838 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7839 FunctionTemplateDecl *FunctionTemplate,
7840 ArrayRef<TemplateArgument> TemplateArgs,
7841 CodeSynthesisContext::SynthesisKind Kind,
7842 sema::TemplateDeductionInfo &DeductionInfo,
7843 SourceRange InstantiationRange = SourceRange());
7844
7845 /// Note that we are instantiating as part of template
7846 /// argument deduction for a class template declaration.
7847 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7848 TemplateDecl *Template,
7849 ArrayRef<TemplateArgument> TemplateArgs,
7850 sema::TemplateDeductionInfo &DeductionInfo,
7851 SourceRange InstantiationRange = SourceRange());
7852
7853 /// Note that we are instantiating as part of template
7854 /// argument deduction for a class template partial
7855 /// specialization.
7856 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7857 ClassTemplatePartialSpecializationDecl *PartialSpec,
7858 ArrayRef<TemplateArgument> TemplateArgs,
7859 sema::TemplateDeductionInfo &DeductionInfo,
7860 SourceRange InstantiationRange = SourceRange());
7861
7862 /// Note that we are instantiating as part of template
7863 /// argument deduction for a variable template partial
7864 /// specialization.
7865 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7866 VarTemplatePartialSpecializationDecl *PartialSpec,
7867 ArrayRef<TemplateArgument> TemplateArgs,
7868 sema::TemplateDeductionInfo &DeductionInfo,
7869 SourceRange InstantiationRange = SourceRange());
7870
7871 /// Note that we are instantiating a default argument for a function
7872 /// parameter.
7873 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7874 ParmVarDecl *Param,
7875 ArrayRef<TemplateArgument> TemplateArgs,
7876 SourceRange InstantiationRange = SourceRange());
7877
7878 /// Note that we are substituting prior template arguments into a
7879 /// non-type parameter.
7880 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7881 NamedDecl *Template,
7882 NonTypeTemplateParmDecl *Param,
7883 ArrayRef<TemplateArgument> TemplateArgs,
7884 SourceRange InstantiationRange);
7885
7886 /// Note that we are substituting prior template arguments into a
7887 /// template template parameter.
7888 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7889 NamedDecl *Template,
7890 TemplateTemplateParmDecl *Param,
7891 ArrayRef<TemplateArgument> TemplateArgs,
7892 SourceRange InstantiationRange);
7893
7894 /// Note that we are checking the default template argument
7895 /// against the template parameter for a given template-id.
7896 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7897 TemplateDecl *Template,
7898 NamedDecl *Param,
7899 ArrayRef<TemplateArgument> TemplateArgs,
7900 SourceRange InstantiationRange);
7901
7902
7903 /// Note that we have finished instantiating this template.
7904 void Clear();
7905
7906 ~InstantiatingTemplate() { Clear(); }
7907
7908 /// Determines whether we have exceeded the maximum
7909 /// recursive template instantiations.
7910 bool isInvalid() const { return Invalid; }
7911
7912 /// Determine whether we are already instantiating this
7913 /// specialization in some surrounding active instantiation.
7914 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7915
7916 private:
7917 Sema &SemaRef;
7918 bool Invalid;
7919 bool AlreadyInstantiating;
7920 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7921 SourceRange InstantiationRange);
7922
7923 InstantiatingTemplate(
7924 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7925 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7926 Decl *Entity, NamedDecl *Template = nullptr,
7927 ArrayRef<TemplateArgument> TemplateArgs = None,
7928 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7929
7930 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7931
7932 InstantiatingTemplate&
7933 operator=(const InstantiatingTemplate&) = delete;
7934 };
7935
7936 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7937 void popCodeSynthesisContext();
7938
7939 /// Determine whether we are currently performing template instantiation.
7940 bool inTemplateInstantiation() const {
7941 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7942 }
7943
7944 void PrintContextStack() {
7945 if (!CodeSynthesisContexts.empty() &&
7946 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7947 PrintInstantiationStack();
7948 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7949 }
7950 if (PragmaAttributeCurrentTargetDecl)
7951 PrintPragmaAttributeInstantiationPoint();
7952 }
7953 void PrintInstantiationStack();
7954
7955 void PrintPragmaAttributeInstantiationPoint();
7956
7957 /// Determines whether we are currently in a context where
7958 /// template argument substitution failures are not considered
7959 /// errors.
7960 ///
7961 /// \returns An empty \c Optional if we're not in a SFINAE context.
7962 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7963 /// template-deduction context object, which can be used to capture
7964 /// diagnostics that will be suppressed.
7965 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7966
7967 /// Determines whether we are currently in a context that
7968 /// is not evaluated as per C++ [expr] p5.
7969 bool isUnevaluatedContext() const {
7970 assert(!ExprEvalContexts.empty() &&((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 7971, __PRETTY_FUNCTION__))
7971 "Must be in an expression evaluation context")((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 7971, __PRETTY_FUNCTION__))
;
7972 return ExprEvalContexts.back().isUnevaluated();
7973 }
7974
7975 /// RAII class used to determine whether SFINAE has
7976 /// trapped any errors that occur during template argument
7977 /// deduction.
7978 class SFINAETrap {
7979 Sema &SemaRef;
7980 unsigned PrevSFINAEErrors;
7981 bool PrevInNonInstantiationSFINAEContext;
7982 bool PrevAccessCheckingSFINAE;
7983 bool PrevLastDiagnosticIgnored;
7984
7985 public:
7986 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7987 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7988 PrevInNonInstantiationSFINAEContext(
7989 SemaRef.InNonInstantiationSFINAEContext),
7990 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
7991 PrevLastDiagnosticIgnored(
7992 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
7993 {
7994 if (!SemaRef.isSFINAEContext())
7995 SemaRef.InNonInstantiationSFINAEContext = true;
7996 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7997 }
7998
7999 ~SFINAETrap() {
8000 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
8001 SemaRef.InNonInstantiationSFINAEContext
8002 = PrevInNonInstantiationSFINAEContext;
8003 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
8004 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
8005 PrevLastDiagnosticIgnored);
8006 }
8007
8008 /// Determine whether any SFINAE errors have been trapped.
8009 bool hasErrorOccurred() const {
8010 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
8011 }
8012 };
8013
8014 /// RAII class used to indicate that we are performing provisional
8015 /// semantic analysis to determine the validity of a construct, so
8016 /// typo-correction and diagnostics in the immediate context (not within
8017 /// implicitly-instantiated templates) should be suppressed.
8018 class TentativeAnalysisScope {
8019 Sema &SemaRef;
8020 // FIXME: Using a SFINAETrap for this is a hack.
8021 SFINAETrap Trap;
8022 bool PrevDisableTypoCorrection;
8023 public:
8024 explicit TentativeAnalysisScope(Sema &SemaRef)
8025 : SemaRef(SemaRef), Trap(SemaRef, true),
8026 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
8027 SemaRef.DisableTypoCorrection = true;
8028 }
8029 ~TentativeAnalysisScope() {
8030 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
8031 }
8032 };
8033
8034 /// The current instantiation scope used to store local
8035 /// variables.
8036 LocalInstantiationScope *CurrentInstantiationScope;
8037
8038 /// Tracks whether we are in a context where typo correction is
8039 /// disabled.
8040 bool DisableTypoCorrection;
8041
8042 /// The number of typos corrected by CorrectTypo.
8043 unsigned TyposCorrected;
8044
8045 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
8046 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
8047
8048 /// A cache containing identifiers for which typo correction failed and
8049 /// their locations, so that repeated attempts to correct an identifier in a
8050 /// given location are ignored if typo correction already failed for it.
8051 IdentifierSourceLocations TypoCorrectionFailures;
8052
8053 /// Worker object for performing CFG-based warnings.
8054 sema::AnalysisBasedWarnings AnalysisWarnings;
8055 threadSafety::BeforeSet *ThreadSafetyDeclCache;
8056
8057 /// An entity for which implicit template instantiation is required.
8058 ///
8059 /// The source location associated with the declaration is the first place in
8060 /// the source code where the declaration was "used". It is not necessarily
8061 /// the point of instantiation (which will be either before or after the
8062 /// namespace-scope declaration that triggered this implicit instantiation),
8063 /// However, it is the location that diagnostics should generally refer to,
8064 /// because users will need to know what code triggered the instantiation.
8065 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
8066
8067 /// The queue of implicit template instantiations that are required
8068 /// but have not yet been performed.
8069 std::deque<PendingImplicitInstantiation> PendingInstantiations;
8070
8071 /// Queue of implicit template instantiations that cannot be performed
8072 /// eagerly.
8073 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
8074
8075 class GlobalEagerInstantiationScope {
8076 public:
8077 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
8078 : S(S), Enabled(Enabled) {
8079 if (!Enabled) return;
8080
8081 SavedPendingInstantiations.swap(S.PendingInstantiations);
8082 SavedVTableUses.swap(S.VTableUses);
8083 }
8084
8085 void perform() {
8086 if (Enabled) {
8087 S.DefineUsedVTables();
8088 S.PerformPendingInstantiations();
8089 }
8090 }
8091
8092 ~GlobalEagerInstantiationScope() {
8093 if (!Enabled) return;
8094
8095 // Restore the set of pending vtables.
8096 assert(S.VTableUses.empty() &&((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 8097, __PRETTY_FUNCTION__))
8097 "VTableUses should be empty before it is discarded.")((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 8097, __PRETTY_FUNCTION__))
;
8098 S.VTableUses.swap(SavedVTableUses);
8099
8100 // Restore the set of pending implicit instantiations.
8101 assert(S.PendingInstantiations.empty() &&((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 8102, __PRETTY_FUNCTION__))
8102 "PendingInstantiations should be empty before it is discarded.")((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 8102, __PRETTY_FUNCTION__))
;
8103 S.PendingInstantiations.swap(SavedPendingInstantiations);
8104 }
8105
8106 private:
8107 Sema &S;
8108 SmallVector<VTableUse, 16> SavedVTableUses;
8109 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
8110 bool Enabled;
8111 };
8112
8113 /// The queue of implicit template instantiations that are required
8114 /// and must be performed within the current local scope.
8115 ///
8116 /// This queue is only used for member functions of local classes in
8117 /// templates, which must be instantiated in the same scope as their
8118 /// enclosing function, so that they can reference function-local
8119 /// types, static variables, enumerators, etc.
8120 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
8121
8122 class LocalEagerInstantiationScope {
8123 public:
8124 LocalEagerInstantiationScope(Sema &S) : S(S) {
8125 SavedPendingLocalImplicitInstantiations.swap(
8126 S.PendingLocalImplicitInstantiations);
8127 }
8128
8129 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
8130
8131 ~LocalEagerInstantiationScope() {
8132 assert(S.PendingLocalImplicitInstantiations.empty() &&((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 8133, __PRETTY_FUNCTION__))
8133 "there shouldn't be any pending local implicit instantiations")((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 8133, __PRETTY_FUNCTION__))
;
8134 SavedPendingLocalImplicitInstantiations.swap(
8135 S.PendingLocalImplicitInstantiations);
8136 }
8137
8138 private:
8139 Sema &S;
8140 std::deque<PendingImplicitInstantiation>
8141 SavedPendingLocalImplicitInstantiations;
8142 };
8143
8144 /// A helper class for building up ExtParameterInfos.
8145 class ExtParameterInfoBuilder {
8146 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
8147 bool HasInteresting = false;
8148
8149 public:
8150 /// Set the ExtParameterInfo for the parameter at the given index,
8151 ///
8152 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
8153 assert(Infos.size() <= index)((Infos.size() <= index) ? static_cast<void> (0) : __assert_fail
("Infos.size() <= index", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 8153, __PRETTY_FUNCTION__))
;
8154 Infos.resize(index);
8155 Infos.push_back(info);
8156
8157 if (!HasInteresting)
8158 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
8159 }
8160
8161 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
8162 /// ExtParameterInfo array we've built up.
8163 const FunctionProtoType::ExtParameterInfo *
8164 getPointerOrNull(unsigned numParams) {
8165 if (!HasInteresting) return nullptr;
8166 Infos.resize(numParams);
8167 return Infos.data();
8168 }
8169 };
8170
8171 void PerformPendingInstantiations(bool LocalOnly = false);
8172
8173 TypeSourceInfo *SubstType(TypeSourceInfo *T,
8174 const MultiLevelTemplateArgumentList &TemplateArgs,
8175 SourceLocation Loc, DeclarationName Entity,
8176 bool AllowDeducedTST = false);
8177
8178 QualType SubstType(QualType T,
8179 const MultiLevelTemplateArgumentList &TemplateArgs,
8180 SourceLocation Loc, DeclarationName Entity);
8181
8182 TypeSourceInfo *SubstType(TypeLoc TL,
8183 const MultiLevelTemplateArgumentList &TemplateArgs,
8184 SourceLocation Loc, DeclarationName Entity);
8185
8186 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
8187 const MultiLevelTemplateArgumentList &TemplateArgs,
8188 SourceLocation Loc,
8189 DeclarationName Entity,
8190 CXXRecordDecl *ThisContext,
8191 Qualifiers ThisTypeQuals);
8192 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
8193 const MultiLevelTemplateArgumentList &Args);
8194 bool SubstExceptionSpec(SourceLocation Loc,
8195 FunctionProtoType::ExceptionSpecInfo &ESI,
8196 SmallVectorImpl<QualType> &ExceptionStorage,
8197 const MultiLevelTemplateArgumentList &Args);
8198 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
8199 const MultiLevelTemplateArgumentList &TemplateArgs,
8200 int indexAdjustment,
8201 Optional<unsigned> NumExpansions,
8202 bool ExpectParameterPack);
8203 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
8204 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
8205 const MultiLevelTemplateArgumentList &TemplateArgs,
8206 SmallVectorImpl<QualType> &ParamTypes,
8207 SmallVectorImpl<ParmVarDecl *> *OutParams,
8208 ExtParameterInfoBuilder &ParamInfos);
8209 ExprResult SubstExpr(Expr *E,
8210 const MultiLevelTemplateArgumentList &TemplateArgs);
8211
8212 /// Substitute the given template arguments into a list of
8213 /// expressions, expanding pack expansions if required.
8214 ///
8215 /// \param Exprs The list of expressions to substitute into.
8216 ///
8217 /// \param IsCall Whether this is some form of call, in which case
8218 /// default arguments will be dropped.
8219 ///
8220 /// \param TemplateArgs The set of template arguments to substitute.
8221 ///
8222 /// \param Outputs Will receive all of the substituted arguments.
8223 ///
8224 /// \returns true if an error occurred, false otherwise.
8225 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
8226 const MultiLevelTemplateArgumentList &TemplateArgs,
8227 SmallVectorImpl<Expr *> &Outputs);
8228
8229 StmtResult SubstStmt(Stmt *S,
8230 const MultiLevelTemplateArgumentList &TemplateArgs);
8231
8232 TemplateParameterList *
8233 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
8234 const MultiLevelTemplateArgumentList &TemplateArgs);
8235
8236 Decl *SubstDecl(Decl *D, DeclContext *Owner,
8237 const MultiLevelTemplateArgumentList &TemplateArgs);
8238
8239 ExprResult SubstInitializer(Expr *E,
8240 const MultiLevelTemplateArgumentList &TemplateArgs,
8241 bool CXXDirectInit);
8242
8243 bool
8244 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
8245 CXXRecordDecl *Pattern,
8246 const MultiLevelTemplateArgumentList &TemplateArgs);
8247
8248 bool
8249 InstantiateClass(SourceLocation PointOfInstantiation,
8250 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
8251 const MultiLevelTemplateArgumentList &TemplateArgs,
8252 TemplateSpecializationKind TSK,
8253 bool Complain = true);
8254
8255 bool InstantiateEnum(SourceLocation PointOfInstantiation,
8256 EnumDecl *Instantiation, EnumDecl *Pattern,
8257 const MultiLevelTemplateArgumentList &TemplateArgs,
8258 TemplateSpecializationKind TSK);
8259
8260 bool InstantiateInClassInitializer(
8261 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
8262 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
8263
8264 struct LateInstantiatedAttribute {
8265 const Attr *TmplAttr;
8266 LocalInstantiationScope *Scope;
8267 Decl *NewDecl;
8268
8269 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
8270 Decl *D)
8271 : TmplAttr(A), Scope(S), NewDecl(D)
8272 { }
8273 };
8274 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
8275
8276 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
8277 const Decl *Pattern, Decl *Inst,
8278 LateInstantiatedAttrVec *LateAttrs = nullptr,
8279 LocalInstantiationScope *OuterMostScope = nullptr);
8280
8281 void
8282 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
8283 const Decl *Pattern, Decl *Inst,
8284 LateInstantiatedAttrVec *LateAttrs = nullptr,
8285 LocalInstantiationScope *OuterMostScope = nullptr);
8286
8287 bool usesPartialOrExplicitSpecialization(
8288 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
8289
8290 bool
8291 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
8292 ClassTemplateSpecializationDecl *ClassTemplateSpec,
8293 TemplateSpecializationKind TSK,
8294 bool Complain = true);
8295
8296 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
8297 CXXRecordDecl *Instantiation,
8298 const MultiLevelTemplateArgumentList &TemplateArgs,
8299 TemplateSpecializationKind TSK);
8300
8301 void InstantiateClassTemplateSpecializationMembers(
8302 SourceLocation PointOfInstantiation,
8303 ClassTemplateSpecializationDecl *ClassTemplateSpec,
8304 TemplateSpecializationKind TSK);
8305
8306 NestedNameSpecifierLoc
8307 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
8308 const MultiLevelTemplateArgumentList &TemplateArgs);
8309
8310 DeclarationNameInfo
8311 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
8312 const MultiLevelTemplateArgumentList &TemplateArgs);
8313 TemplateName
8314 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
8315 SourceLocation Loc,
8316 const MultiLevelTemplateArgumentList &TemplateArgs);
8317 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
8318 TemplateArgumentListInfo &Result,
8319 const MultiLevelTemplateArgumentList &TemplateArgs);
8320
8321 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
8322 FunctionDecl *Function);
8323 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
8324 const TemplateArgumentList *Args,
8325 SourceLocation Loc);
8326 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
8327 FunctionDecl *Function,
8328 bool Recursive = false,
8329 bool DefinitionRequired = false,
8330 bool AtEndOfTU = false);
8331 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
8332 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
8333 const TemplateArgumentList &TemplateArgList,
8334 const TemplateArgumentListInfo &TemplateArgsInfo,
8335 SmallVectorImpl<TemplateArgument> &Converted,
8336 SourceLocation PointOfInstantiation, void *InsertPos,
8337 LateInstantiatedAttrVec *LateAttrs = nullptr,
8338 LocalInstantiationScope *StartingScope = nullptr);
8339 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
8340 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
8341 const MultiLevelTemplateArgumentList &TemplateArgs);
8342 void
8343 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
8344 const MultiLevelTemplateArgumentList &TemplateArgs,
8345 LateInstantiatedAttrVec *LateAttrs,
8346 DeclContext *Owner,
8347 LocalInstantiationScope *StartingScope,
8348 bool InstantiatingVarTemplate = false,
8349 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
8350
8351 VarDecl *getVarTemplateSpecialization(
8352 VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
8353 const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
8354
8355 void InstantiateVariableInitializer(
8356 VarDecl *Var, VarDecl *OldVar,
8357 const MultiLevelTemplateArgumentList &TemplateArgs);
8358 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
8359 VarDecl *Var, bool Recursive = false,
8360 bool DefinitionRequired = false,
8361 bool AtEndOfTU = false);
8362
8363 void InstantiateMemInitializers(CXXConstructorDecl *New,
8364 const CXXConstructorDecl *Tmpl,
8365 const MultiLevelTemplateArgumentList &TemplateArgs);
8366
8367 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
8368 const MultiLevelTemplateArgumentList &TemplateArgs,
8369 bool FindingInstantiatedContext = false);
8370 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
8371 const MultiLevelTemplateArgumentList &TemplateArgs);
8372
8373 // Objective-C declarations.
8374 enum ObjCContainerKind {
8375 OCK_None = -1,
8376 OCK_Interface = 0,
8377 OCK_Protocol,
8378 OCK_Category,
8379 OCK_ClassExtension,
8380 OCK_Implementation,
8381 OCK_CategoryImplementation
8382 };
8383 ObjCContainerKind getObjCContainerKind() const;
8384
8385 DeclResult actOnObjCTypeParam(Scope *S,
8386 ObjCTypeParamVariance variance,
8387 SourceLocation varianceLoc,
8388 unsigned index,
8389 IdentifierInfo *paramName,
8390 SourceLocation paramLoc,
8391 SourceLocation colonLoc,
8392 ParsedType typeBound);
8393
8394 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
8395 ArrayRef<Decl *> typeParams,
8396 SourceLocation rAngleLoc);
8397 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
8398
8399 Decl *ActOnStartClassInterface(
8400 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8401 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8402 IdentifierInfo *SuperName, SourceLocation SuperLoc,
8403 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
8404 Decl *const *ProtoRefs, unsigned NumProtoRefs,
8405 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8406 const ParsedAttributesView &AttrList);
8407
8408 void ActOnSuperClassOfClassInterface(Scope *S,
8409 SourceLocation AtInterfaceLoc,
8410 ObjCInterfaceDecl *IDecl,
8411 IdentifierInfo *ClassName,
8412 SourceLocation ClassLoc,
8413 IdentifierInfo *SuperName,
8414 SourceLocation SuperLoc,
8415 ArrayRef<ParsedType> SuperTypeArgs,
8416 SourceRange SuperTypeArgsRange);
8417
8418 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
8419 SmallVectorImpl<SourceLocation> &ProtocolLocs,
8420 IdentifierInfo *SuperName,
8421 SourceLocation SuperLoc);
8422
8423 Decl *ActOnCompatibilityAlias(
8424 SourceLocation AtCompatibilityAliasLoc,
8425 IdentifierInfo *AliasName, SourceLocation AliasLocation,
8426 IdentifierInfo *ClassName, SourceLocation ClassLocation);
8427
8428 bool CheckForwardProtocolDeclarationForCircularDependency(
8429 IdentifierInfo *PName,
8430 SourceLocation &PLoc, SourceLocation PrevLoc,
8431 const ObjCList<ObjCProtocolDecl> &PList);
8432
8433 Decl *ActOnStartProtocolInterface(
8434 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
8435 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
8436 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
8437 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
8438
8439 Decl *ActOnStartCategoryInterface(
8440 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8441 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8442 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
8443 Decl *const *ProtoRefs, unsigned NumProtoRefs,
8444 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8445 const ParsedAttributesView &AttrList);
8446
8447 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
8448 IdentifierInfo *ClassName,
8449 SourceLocation ClassLoc,
8450 IdentifierInfo *SuperClassname,
8451 SourceLocation SuperClassLoc,
8452 const ParsedAttributesView &AttrList);
8453
8454 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
8455 IdentifierInfo *ClassName,
8456 SourceLocation ClassLoc,
8457 IdentifierInfo *CatName,
8458 SourceLocation CatLoc,
8459 const ParsedAttributesView &AttrList);
8460
8461 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
8462 ArrayRef<Decl *> Decls);
8463
8464 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
8465 IdentifierInfo **IdentList,
8466 SourceLocation *IdentLocs,
8467 ArrayRef<ObjCTypeParamList *> TypeParamLists,
8468 unsigned NumElts);
8469
8470 DeclGroupPtrTy
8471 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
8472 ArrayRef<IdentifierLocPair> IdentList,
8473 const ParsedAttributesView &attrList);
8474
8475 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
8476 ArrayRef<IdentifierLocPair> ProtocolId,
8477 SmallVectorImpl<Decl *> &Protocols);
8478
8479 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
8480 SourceLocation ProtocolLoc,
8481 IdentifierInfo *TypeArgId,
8482 SourceLocation TypeArgLoc,
8483 bool SelectProtocolFirst = false);
8484
8485 /// Given a list of identifiers (and their locations), resolve the
8486 /// names to either Objective-C protocol qualifiers or type
8487 /// arguments, as appropriate.
8488 void actOnObjCTypeArgsOrProtocolQualifiers(
8489 Scope *S,
8490 ParsedType baseType,
8491 SourceLocation lAngleLoc,
8492 ArrayRef<IdentifierInfo *> identifiers,
8493 ArrayRef<SourceLocation> identifierLocs,
8494 SourceLocation rAngleLoc,
8495 SourceLocation &typeArgsLAngleLoc,
8496 SmallVectorImpl<ParsedType> &typeArgs,
8497 SourceLocation &typeArgsRAngleLoc,
8498 SourceLocation &protocolLAngleLoc,
8499 SmallVectorImpl<Decl *> &protocols,
8500 SourceLocation &protocolRAngleLoc,
8501 bool warnOnIncompleteProtocols);
8502
8503 /// Build a an Objective-C protocol-qualified 'id' type where no
8504 /// base type was specified.
8505 TypeResult actOnObjCProtocolQualifierType(
8506 SourceLocation lAngleLoc,
8507 ArrayRef<Decl *> protocols,
8508 ArrayRef<SourceLocation> protocolLocs,
8509 SourceLocation rAngleLoc);
8510
8511 /// Build a specialized and/or protocol-qualified Objective-C type.
8512 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
8513 Scope *S,
8514 SourceLocation Loc,
8515 ParsedType BaseType,
8516 SourceLocation TypeArgsLAngleLoc,
8517 ArrayRef<ParsedType> TypeArgs,
8518 SourceLocation TypeArgsRAngleLoc,
8519 SourceLocation ProtocolLAngleLoc,
8520 ArrayRef<Decl *> Protocols,
8521 ArrayRef<SourceLocation> ProtocolLocs,
8522 SourceLocation ProtocolRAngleLoc);
8523
8524 /// Build an Objective-C type parameter type.
8525 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
8526 SourceLocation ProtocolLAngleLoc,
8527 ArrayRef<ObjCProtocolDecl *> Protocols,
8528 ArrayRef<SourceLocation> ProtocolLocs,
8529 SourceLocation ProtocolRAngleLoc,
8530 bool FailOnError = false);
8531
8532 /// Build an Objective-C object pointer type.
8533 QualType BuildObjCObjectType(QualType BaseType,
8534 SourceLocation Loc,
8535 SourceLocation TypeArgsLAngleLoc,
8536 ArrayRef<TypeSourceInfo *> TypeArgs,
8537 SourceLocation TypeArgsRAngleLoc,
8538 SourceLocation ProtocolLAngleLoc,
8539 ArrayRef<ObjCProtocolDecl *> Protocols,
8540 ArrayRef<SourceLocation> ProtocolLocs,
8541 SourceLocation ProtocolRAngleLoc,
8542 bool FailOnError = false);
8543
8544 /// Ensure attributes are consistent with type.
8545 /// \param [in, out] Attributes The attributes to check; they will
8546 /// be modified to be consistent with \p PropertyTy.
8547 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
8548 SourceLocation Loc,
8549 unsigned &Attributes,
8550 bool propertyInPrimaryClass);
8551
8552 /// Process the specified property declaration and create decls for the
8553 /// setters and getters as needed.
8554 /// \param property The property declaration being processed
8555 void ProcessPropertyDecl(ObjCPropertyDecl *property);
8556
8557
8558 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
8559 ObjCPropertyDecl *SuperProperty,
8560 const IdentifierInfo *Name,
8561 bool OverridingProtocolProperty);
8562
8563 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
8564 ObjCInterfaceDecl *ID);
8565
8566 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
8567 ArrayRef<Decl *> allMethods = None,
8568 ArrayRef<DeclGroupPtrTy> allTUVars = None);
8569
8570 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
8571 SourceLocation LParenLoc,
8572 FieldDeclarator &FD, ObjCDeclSpec &ODS,
8573 Selector GetterSel, Selector SetterSel,
8574 tok::ObjCKeywordKind MethodImplKind,
8575 DeclContext *lexicalDC = nullptr);
8576
8577 Decl *ActOnPropertyImplDecl(Scope *S,
8578 SourceLocation AtLoc,
8579 SourceLocation PropertyLoc,
8580 bool ImplKind,
8581 IdentifierInfo *PropertyId,
8582 IdentifierInfo *PropertyIvar,
8583 SourceLocation PropertyIvarLoc,
8584 ObjCPropertyQueryKind QueryKind);
8585
8586 enum ObjCSpecialMethodKind {
8587 OSMK_None,
8588 OSMK_Alloc,
8589 OSMK_New,
8590 OSMK_Copy,
8591 OSMK_RetainingInit,
8592 OSMK_NonRetainingInit
8593 };
8594
8595 struct ObjCArgInfo {
8596 IdentifierInfo *Name;
8597 SourceLocation NameLoc;
8598 // The Type is null if no type was specified, and the DeclSpec is invalid
8599 // in this case.
8600 ParsedType Type;
8601 ObjCDeclSpec DeclSpec;
8602
8603 /// ArgAttrs - Attribute list for this argument.
8604 ParsedAttributesView ArgAttrs;
8605 };
8606
8607 Decl *ActOnMethodDeclaration(
8608 Scope *S,
8609 SourceLocation BeginLoc, // location of the + or -.
8610 SourceLocation EndLoc, // location of the ; or {.
8611 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8612 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8613 // optional arguments. The number of types/arguments is obtained
8614 // from the Sel.getNumArgs().
8615 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
8616 unsigned CNumArgs, // c-style args
8617 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
8618 bool isVariadic, bool MethodDefinition);
8619
8620 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8621 const ObjCObjectPointerType *OPT,
8622 bool IsInstance);
8623 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8624 bool IsInstance);
8625
8626 bool CheckARCMethodDecl(ObjCMethodDecl *method);
8627 bool inferObjCARCLifetime(ValueDecl *decl);
8628
8629 ExprResult
8630 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8631 Expr *BaseExpr,
8632 SourceLocation OpLoc,
8633 DeclarationName MemberName,
8634 SourceLocation MemberLoc,
8635 SourceLocation SuperLoc, QualType SuperType,
8636 bool Super);
8637
8638 ExprResult
8639 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8640 IdentifierInfo &propertyName,
8641 SourceLocation receiverNameLoc,
8642 SourceLocation propertyNameLoc);
8643
8644 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8645
8646 /// Describes the kind of message expression indicated by a message
8647 /// send that starts with an identifier.
8648 enum ObjCMessageKind {
8649 /// The message is sent to 'super'.
8650 ObjCSuperMessage,
8651 /// The message is an instance message.
8652 ObjCInstanceMessage,
8653 /// The message is a class message, and the identifier is a type
8654 /// name.
8655 ObjCClassMessage
8656 };
8657
8658 ObjCMessageKind getObjCMessageKind(Scope *S,
8659 IdentifierInfo *Name,
8660 SourceLocation NameLoc,
8661 bool IsSuper,
8662 bool HasTrailingDot,
8663 ParsedType &ReceiverType);
8664
8665 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8666 Selector Sel,
8667 SourceLocation LBracLoc,
8668 ArrayRef<SourceLocation> SelectorLocs,
8669 SourceLocation RBracLoc,
8670 MultiExprArg Args);
8671
8672 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8673 QualType ReceiverType,
8674 SourceLocation SuperLoc,
8675 Selector Sel,
8676 ObjCMethodDecl *Method,
8677 SourceLocation LBracLoc,
8678 ArrayRef<SourceLocation> SelectorLocs,
8679 SourceLocation RBracLoc,
8680 MultiExprArg Args,
8681 bool isImplicit = false);
8682
8683 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8684 bool isSuperReceiver,
8685 SourceLocation Loc,
8686 Selector Sel,
8687 ObjCMethodDecl *Method,
8688 MultiExprArg Args);
8689
8690 ExprResult ActOnClassMessage(Scope *S,
8691 ParsedType Receiver,
8692 Selector Sel,
8693 SourceLocation LBracLoc,
8694 ArrayRef<SourceLocation> SelectorLocs,
8695 SourceLocation RBracLoc,
8696 MultiExprArg Args);
8697
8698 ExprResult BuildInstanceMessage(Expr *Receiver,
8699 QualType ReceiverType,
8700 SourceLocation SuperLoc,
8701 Selector Sel,
8702 ObjCMethodDecl *Method,
8703 SourceLocation LBracLoc,
8704 ArrayRef<SourceLocation> SelectorLocs,
8705 SourceLocation RBracLoc,
8706 MultiExprArg Args,
8707 bool isImplicit = false);
8708
8709 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8710 QualType ReceiverType,
8711 SourceLocation Loc,
8712 Selector Sel,
8713 ObjCMethodDecl *Method,
8714 MultiExprArg Args);
8715
8716 ExprResult ActOnInstanceMessage(Scope *S,
8717 Expr *Receiver,
8718 Selector Sel,
8719 SourceLocation LBracLoc,
8720 ArrayRef<SourceLocation> SelectorLocs,
8721 SourceLocation RBracLoc,
8722 MultiExprArg Args);
8723
8724 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8725 ObjCBridgeCastKind Kind,
8726 SourceLocation BridgeKeywordLoc,
8727 TypeSourceInfo *TSInfo,
8728 Expr *SubExpr);
8729
8730 ExprResult ActOnObjCBridgedCast(Scope *S,
8731 SourceLocation LParenLoc,
8732 ObjCBridgeCastKind Kind,
8733 SourceLocation BridgeKeywordLoc,
8734 ParsedType Type,
8735 SourceLocation RParenLoc,
8736 Expr *SubExpr);
8737
8738 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8739
8740 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8741
8742 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8743 CastKind &Kind);
8744
8745 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8746 QualType DestType, QualType SrcType,
8747 ObjCInterfaceDecl *&RelatedClass,
8748 ObjCMethodDecl *&ClassMethod,
8749 ObjCMethodDecl *&InstanceMethod,
8750 TypedefNameDecl *&TDNDecl,
8751 bool CfToNs, bool Diagnose = true);
8752
8753 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8754 QualType DestType, QualType SrcType,
8755 Expr *&SrcExpr, bool Diagnose = true);
8756
8757 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8758 bool Diagnose = true);
8759
8760 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8761
8762 /// Check whether the given new method is a valid override of the
8763 /// given overridden method, and set any properties that should be inherited.
8764 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8765 const ObjCMethodDecl *Overridden);
8766
8767 /// Describes the compatibility of a result type with its method.
8768 enum ResultTypeCompatibilityKind {
8769 RTC_Compatible,
8770 RTC_Incompatible,
8771 RTC_Unknown
8772 };
8773
8774 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8775 ObjCInterfaceDecl *CurrentClass,
8776 ResultTypeCompatibilityKind RTC);
8777
8778 enum PragmaOptionsAlignKind {
8779 POAK_Native, // #pragma options align=native
8780 POAK_Natural, // #pragma options align=natural
8781 POAK_Packed, // #pragma options align=packed
8782 POAK_Power, // #pragma options align=power
8783 POAK_Mac68k, // #pragma options align=mac68k
8784 POAK_Reset // #pragma options align=reset
8785 };
8786
8787 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8788 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8789 PragmaClangSectionAction Action,
8790 PragmaClangSectionKind SecKind, StringRef SecName);
8791
8792 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8793 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8794 SourceLocation PragmaLoc);
8795
8796 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8797 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8798 StringRef SlotLabel, Expr *Alignment);
8799
8800 enum class PragmaPackDiagnoseKind {
8801 NonDefaultStateAtInclude,
8802 ChangedStateAtExit
8803 };
8804
8805 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
8806 SourceLocation IncludeLoc);
8807 void DiagnoseUnterminatedPragmaPack();
8808
8809 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8810 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8811
8812 /// ActOnPragmaMSComment - Called on well formed
8813 /// \#pragma comment(kind, "arg").
8814 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8815 StringRef Arg);
8816
8817 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8818 /// pointers_to_members(representation method[, general purpose
8819 /// representation]).
8820 void ActOnPragmaMSPointersToMembers(
8821 LangOptions::PragmaMSPointersToMembersKind Kind,
8822 SourceLocation PragmaLoc);
8823
8824 /// Called on well formed \#pragma vtordisp().
8825 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8826 SourceLocation PragmaLoc,
8827 MSVtorDispAttr::Mode Value);
8828
8829 enum PragmaSectionKind {
8830 PSK_DataSeg,
8831 PSK_BSSSeg,
8832 PSK_ConstSeg,
8833 PSK_CodeSeg,
8834 };
8835
8836 bool UnifySection(StringRef SectionName,
8837 int SectionFlags,
8838 DeclaratorDecl *TheDecl);
8839 bool UnifySection(StringRef SectionName,
8840 int SectionFlags,
8841 SourceLocation PragmaSectionLocation);
8842
8843 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8844 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8845 PragmaMsStackAction Action,
8846 llvm::StringRef StackSlotLabel,
8847 StringLiteral *SegmentName,
8848 llvm::StringRef PragmaName);
8849
8850 /// Called on well formed \#pragma section().
8851 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8852 int SectionFlags, StringLiteral *SegmentName);
8853
8854 /// Called on well-formed \#pragma init_seg().
8855 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8856 StringLiteral *SegmentName);
8857
8858 /// Called on #pragma clang __debug dump II
8859 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8860
8861 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8862 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8863 StringRef Value);
8864
8865 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8866 void ActOnPragmaUnused(const Token &Identifier,
8867 Scope *curScope,
8868 SourceLocation PragmaLoc);
8869
8870 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8871 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8872 SourceLocation PragmaLoc);
8873
8874 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8875 SourceLocation Loc);
8876 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8877
8878 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8879 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8880 SourceLocation PragmaLoc,
8881 SourceLocation WeakNameLoc);
8882
8883 /// ActOnPragmaRedefineExtname - Called on well formed
8884 /// \#pragma redefine_extname oldname newname.
8885 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8886 IdentifierInfo* AliasName,
8887 SourceLocation PragmaLoc,
8888 SourceLocation WeakNameLoc,
8889 SourceLocation AliasNameLoc);
8890
8891 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8892 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8893 IdentifierInfo* AliasName,
8894 SourceLocation PragmaLoc,
8895 SourceLocation WeakNameLoc,
8896 SourceLocation AliasNameLoc);
8897
8898 /// ActOnPragmaFPContract - Called on well formed
8899 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8900 /// \#pragma clang fp contract
8901 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8902
8903 /// ActOnPragmaFenvAccess - Called on well formed
8904 /// \#pragma STDC FENV_ACCESS
8905 void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
8906
8907 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8908 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8909 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8910
8911 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8912 void AddMsStructLayoutForRecord(RecordDecl *RD);
8913
8914 /// FreePackedContext - Deallocate and null out PackContext.
8915 void FreePackedContext();
8916
8917 /// PushNamespaceVisibilityAttr - Note that we've entered a
8918 /// namespace with a visibility attribute.
8919 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8920 SourceLocation Loc);
8921
8922 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8923 /// add an appropriate visibility attribute.
8924 void AddPushedVisibilityAttribute(Decl *RD);
8925
8926 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8927 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8928 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8929
8930 /// FreeVisContext - Deallocate and null out VisContext.
8931 void FreeVisContext();
8932
8933 /// AddCFAuditedAttribute - Check whether we're currently within
8934 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8935 /// the appropriate attribute.
8936 void AddCFAuditedAttribute(Decl *D);
8937
8938 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
8939 SourceLocation PragmaLoc,
8940 attr::ParsedSubjectMatchRuleSet Rules);
8941 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
8942 const IdentifierInfo *Namespace);
8943
8944 /// Called on well-formed '\#pragma clang attribute pop'.
8945 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
8946 const IdentifierInfo *Namespace);
8947
8948 /// Adds the attributes that have been specified using the
8949 /// '\#pragma clang attribute push' directives to the given declaration.
8950 void AddPragmaAttributes(Scope *S, Decl *D);
8951
8952 void DiagnoseUnterminatedPragmaAttribute();
8953
8954 /// Called on well formed \#pragma clang optimize.
8955 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8956
8957 /// Get the location for the currently active "\#pragma clang optimize
8958 /// off". If this location is invalid, then the state of the pragma is "on".
8959 SourceLocation getOptimizeOffPragmaLocation() const {
8960 return OptimizeOffPragmaLocation;
8961 }
8962
8963 /// Only called on function definitions; if there is a pragma in scope
8964 /// with the effect of a range-based optnone, consider marking the function
8965 /// with attribute optnone.
8966 void AddRangeBasedOptnone(FunctionDecl *FD);
8967
8968 /// Adds the 'optnone' attribute to the function declaration if there
8969 /// are no conflicts; Loc represents the location causing the 'optnone'
8970 /// attribute to be added (usually because of a pragma).
8971 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8972
8973 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8974 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
8975 bool IsPackExpansion);
8976 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
8977 bool IsPackExpansion);
8978
8979 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8980 /// declaration.
8981 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
8982 Expr *OE);
8983
8984 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8985 /// declaration.
8986 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
8987 Expr *ParamExpr);
8988
8989 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8990 /// declaration.
8991 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
8992
8993 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8994 /// declaration.
8995 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
8996 Expr *MaxThreads, Expr *MinBlocks);
8997
8998 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8999 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
9000 bool InInstantiation = false);
9001
9002 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
9003 ParameterABI ABI);
9004
9005 enum class RetainOwnershipKind {NS, CF, OS};
9006 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
9007 RetainOwnershipKind K, bool IsTemplateInstantiation);
9008
9009 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
9010 /// attribute to a particular declaration.
9011 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
9012 Expr *Min, Expr *Max);
9013
9014 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
9015 /// particular declaration.
9016 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
9017 Expr *Min, Expr *Max);
9018
9019 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
9020
9021 //===--------------------------------------------------------------------===//
9022 // C++ Coroutines TS
9023 //
9024 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
9025 StringRef Keyword);
9026 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9027 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9028 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
9029
9030 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9031 bool IsImplicit = false);
9032 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9033 UnresolvedLookupExpr* Lookup);
9034 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
9035 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
9036 bool IsImplicit = false);
9037 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
9038 bool buildCoroutineParameterMoves(SourceLocation Loc);
9039 VarDecl *buildCoroutinePromise(SourceLocation Loc);
9040 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
9041 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
9042 SourceLocation FuncLoc);
9043
9044 //===--------------------------------------------------------------------===//
9045 // OpenCL extensions.
9046 //
9047private:
9048 std::string CurrOpenCLExtension;
9049 /// Extensions required by an OpenCL type.
9050 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
9051 /// Extensions required by an OpenCL declaration.
9052 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
9053public:
9054 llvm::StringRef getCurrentOpenCLExtension() const {
9055 return CurrOpenCLExtension;
9056 }
9057
9058 /// Check if a function declaration \p FD associates with any
9059 /// extensions present in OpenCLDeclExtMap and if so return the
9060 /// extension(s) name(s).
9061 std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
9062
9063 /// Check if a function type \p FT associates with any
9064 /// extensions present in OpenCLTypeExtMap and if so return the
9065 /// extension(s) name(s).
9066 std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
9067
9068 /// Find an extension in an appropriate extension map and return its name
9069 template<typename T, typename MapT>
9070 std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
9071
9072 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
9073 CurrOpenCLExtension = Ext;
9074 }
9075
9076 /// Set OpenCL extensions for a type which can only be used when these
9077 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
9078 /// \param Exts A space separated list of OpenCL extensions.
9079 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
9080
9081 /// Set OpenCL extensions for a declaration which can only be
9082 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
9083 /// nothing.
9084 /// \param Exts A space separated list of OpenCL extensions.
9085 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
9086
9087 /// Set current OpenCL extensions for a type which can only be used
9088 /// when these OpenCL extensions are enabled. If current OpenCL extension is
9089 /// empty, do nothing.
9090 void setCurrentOpenCLExtensionForType(QualType T);
9091
9092 /// Set current OpenCL extensions for a declaration which
9093 /// can only be used when these OpenCL extensions are enabled. If current
9094 /// OpenCL extension is empty, do nothing.
9095 void setCurrentOpenCLExtensionForDecl(Decl *FD);
9096
9097 bool isOpenCLDisabledDecl(Decl *FD);
9098
9099 /// Check if type \p T corresponding to declaration specifier \p DS
9100 /// is disabled due to required OpenCL extensions being disabled. If so,
9101 /// emit diagnostics.
9102 /// \return true if type is disabled.
9103 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
9104
9105 /// Check if declaration \p D used by expression \p E
9106 /// is disabled due to required OpenCL extensions being disabled. If so,
9107 /// emit diagnostics.
9108 /// \return true if type is disabled.
9109 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
9110
9111 //===--------------------------------------------------------------------===//
9112 // OpenMP directives and clauses.
9113 //
9114private:
9115 void *VarDataSharingAttributesStack;
9116 /// Number of nested '#pragma omp declare target' directives.
9117 unsigned DeclareTargetNestingLevel = 0;
9118 /// Initialization of data-sharing attributes stack.
9119 void InitDataSharingAttributesStack();
9120 void DestroyDataSharingAttributesStack();
9121 ExprResult
9122 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
9123 bool StrictlyPositive = true);
9124 /// Returns OpenMP nesting level for current directive.
9125 unsigned getOpenMPNestingLevel() const;
9126
9127 /// Adjusts the function scopes index for the target-based regions.
9128 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
9129 unsigned Level) const;
9130
9131 /// Returns the number of scopes associated with the construct on the given
9132 /// OpenMP level.
9133 int getNumberOfConstructScopes(unsigned Level) const;
9134
9135 /// Push new OpenMP function region for non-capturing function.
9136 void pushOpenMPFunctionRegion();
9137
9138 /// Pop OpenMP function region for non-capturing function.
9139 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
9140
9141 /// Check whether we're allowed to call Callee from the current function.
9142 void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
9143 bool CheckForDelayedContext = true);
9144
9145 /// Check whether we're allowed to call Callee from the current function.
9146 void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
9147 bool CheckCaller = true);
9148
9149 /// Check if the expression is allowed to be used in expressions for the
9150 /// OpenMP devices.
9151 void checkOpenMPDeviceExpr(const Expr *E);
9152
9153 /// Finishes analysis of the deferred functions calls that may be declared as
9154 /// host/nohost during device/host compilation.
9155 void finalizeOpenMPDelayedAnalysis();
9156
9157 /// Checks if a type or a declaration is disabled due to the owning extension
9158 /// being disabled, and emits diagnostic messages if it is disabled.
9159 /// \param D type or declaration to be checked.
9160 /// \param DiagLoc source location for the diagnostic message.
9161 /// \param DiagInfo information to be emitted for the diagnostic message.
9162 /// \param SrcRange source range of the declaration.
9163 /// \param Map maps type or declaration to the extensions.
9164 /// \param Selector selects diagnostic message: 0 for type and 1 for
9165 /// declaration.
9166 /// \return true if the type or declaration is disabled.
9167 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
9168 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
9169 MapT &Map, unsigned Selector = 0,
9170 SourceRange SrcRange = SourceRange());
9171
9172 /// Marks all the functions that might be required for the currently active
9173 /// OpenMP context.
9174 void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
9175 FunctionDecl *Func,
9176 bool MightBeOdrUse);
9177
9178public:
9179 /// Struct to store the context selectors info for declare variant directive.
9180 struct OpenMPDeclareVariantCtsSelectorData {
9181 OMPDeclareVariantAttr::CtxSelectorSetType CtxSet =
9182 OMPDeclareVariantAttr::CtxSetUnknown;
9183 OMPDeclareVariantAttr::CtxSelectorType Ctx =
9184 OMPDeclareVariantAttr::CtxUnknown;
9185 MutableArrayRef<StringRef> ImplVendors;
9186 ExprResult CtxScore;
9187 explicit OpenMPDeclareVariantCtsSelectorData() = default;
9188 explicit OpenMPDeclareVariantCtsSelectorData(
9189 OMPDeclareVariantAttr::CtxSelectorSetType CtxSet,
9190 OMPDeclareVariantAttr::CtxSelectorType Ctx,
9191 MutableArrayRef<StringRef> ImplVendors, ExprResult CtxScore)
9192 : CtxSet(CtxSet), Ctx(Ctx), ImplVendors(ImplVendors),
9193 CtxScore(CtxScore) {}
9194 };
9195
9196 /// Checks if the variant/multiversion functions are compatible.
9197 bool areMultiversionVariantFunctionsCompatible(
9198 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9199 const PartialDiagnostic &NoProtoDiagID,
9200 const PartialDiagnosticAt &NoteCausedDiagIDAt,
9201 const PartialDiagnosticAt &NoSupportDiagIDAt,
9202 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9203 bool ConstexprSupported, bool CLinkageMayDiffer);
9204
9205 /// Function tries to capture lambda's captured variables in the OpenMP region
9206 /// before the original lambda is captured.
9207 void tryCaptureOpenMPLambdas(ValueDecl *V);
9208
9209 /// Return true if the provided declaration \a VD should be captured by
9210 /// reference.
9211 /// \param Level Relative level of nested OpenMP construct for that the check
9212 /// is performed.
9213 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
9214 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
9215 unsigned OpenMPCaptureLevel) const;
9216
9217 /// Check if the specified variable is used in one of the private
9218 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
9219 /// constructs.
9220 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
9221 unsigned StopAt = 0);
9222 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9223 ExprObjectKind OK, SourceLocation Loc);
9224
9225 /// If the current region is a loop-based region, mark the start of the loop
9226 /// construct.
9227 void startOpenMPLoop();
9228
9229 /// If the current region is a range loop-based region, mark the start of the
9230 /// loop construct.
9231 void startOpenMPCXXRangeFor();
9232
9233 /// Check if the specified variable is used in 'private' clause.
9234 /// \param Level Relative level of nested OpenMP construct for that the check
9235 /// is performed.
9236 bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
9237
9238 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
9239 /// for \p FD based on DSA for the provided corresponding captured declaration
9240 /// \p D.
9241 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
9242
9243 /// Check if the specified variable is captured by 'target' directive.
9244 /// \param Level Relative level of nested OpenMP construct for that the check
9245 /// is performed.
9246 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
9247
9248 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
9249 Expr *Op);
9250 /// Called on start of new data sharing attribute block.
9251 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
9252 const DeclarationNameInfo &DirName, Scope *CurScope,
9253 SourceLocation Loc);
9254 /// Start analysis of clauses.
9255 void StartOpenMPClause(OpenMPClauseKind K);
9256 /// End analysis of clauses.
9257 void EndOpenMPClause();
9258 /// Called on end of data sharing attribute block.
9259 void EndOpenMPDSABlock(Stmt *CurDirective);
9260
9261 /// Check if the current region is an OpenMP loop region and if it is,
9262 /// mark loop control variable, used in \p Init for loop initialization, as
9263 /// private by default.
9264 /// \param Init First part of the for loop.
9265 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
9266
9267 // OpenMP directives and clauses.
9268 /// Called on correct id-expression from the '#pragma omp
9269 /// threadprivate'.
9270 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9271 const DeclarationNameInfo &Id,
9272 OpenMPDirectiveKind Kind);
9273 /// Called on well-formed '#pragma omp threadprivate'.
9274 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
9275 SourceLocation Loc,
9276 ArrayRef<Expr *> VarList);
9277 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
9278 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
9279 ArrayRef<Expr *> VarList);
9280 /// Called on well-formed '#pragma omp allocate'.
9281 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
9282 ArrayRef<Expr *> VarList,
9283 ArrayRef<OMPClause *> Clauses,
9284 DeclContext *Owner = nullptr);
9285 /// Called on well-formed '#pragma omp requires'.
9286 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
9287 ArrayRef<OMPClause *> ClauseList);
9288 /// Check restrictions on Requires directive
9289 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
9290 ArrayRef<OMPClause *> Clauses);
9291 /// Check if the specified type is allowed to be used in 'omp declare
9292 /// reduction' construct.
9293 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
9294 TypeResult ParsedType);
9295 /// Called on start of '#pragma omp declare reduction'.
9296 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
9297 Scope *S, DeclContext *DC, DeclarationName Name,
9298 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
9299 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
9300 /// Initialize declare reduction construct initializer.
9301 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
9302 /// Finish current declare reduction construct initializer.
9303 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
9304 /// Initialize declare reduction construct initializer.
9305 /// \return omp_priv variable.
9306 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
9307 /// Finish current declare reduction construct initializer.
9308 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
9309 VarDecl *OmpPrivParm);
9310 /// Called at the end of '#pragma omp declare reduction'.
9311 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
9312 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
9313
9314 /// Check variable declaration in 'omp declare mapper' construct.
9315 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
9316 /// Check if the specified type is allowed to be used in 'omp declare
9317 /// mapper' construct.
9318 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
9319 TypeResult ParsedType);
9320 /// Called on start of '#pragma omp declare mapper'.
9321 OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
9322 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
9323 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
9324 Decl *PrevDeclInScope = nullptr);
9325 /// Build the mapper variable of '#pragma omp declare mapper'.
9326 void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
9327 Scope *S, QualType MapperType,
9328 SourceLocation StartLoc,
9329 DeclarationName VN);
9330 /// Called at the end of '#pragma omp declare mapper'.
9331 DeclGroupPtrTy
9332 ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
9333 ArrayRef<OMPClause *> ClauseList);
9334
9335 /// Called on the start of target region i.e. '#pragma omp declare target'.
9336 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
9337 /// Called at the end of target region i.e. '#pragme omp end declare target'.
9338 void ActOnFinishOpenMPDeclareTargetDirective();
9339 /// Searches for the provided declaration name for OpenMP declare target
9340 /// directive.
9341 NamedDecl *
9342 lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9343 const DeclarationNameInfo &Id,
9344 NamedDeclSetType &SameDirectiveDecls);
9345 /// Called on correct id-expression from the '#pragma omp declare target'.
9346 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
9347 OMPDeclareTargetDeclAttr::MapTypeTy MT,
9348 OMPDeclareTargetDeclAttr::DevTypeTy DT);
9349 /// Check declaration inside target region.
9350 void
9351 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
9352 SourceLocation IdLoc = SourceLocation());
9353 /// Return true inside OpenMP declare target region.
9354 bool isInOpenMPDeclareTargetContext() const {
9355 return DeclareTargetNestingLevel > 0;
9356 }
9357 /// Return true inside OpenMP target region.
9358 bool isInOpenMPTargetExecutionDirective() const;
9359
9360 /// Return the number of captured regions created for an OpenMP directive.
9361 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
9362
9363 /// Initialization of captured region for OpenMP region.
9364 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
9365 /// End of OpenMP region.
9366 ///
9367 /// \param S Statement associated with the current OpenMP region.
9368 /// \param Clauses List of clauses for the current OpenMP region.
9369 ///
9370 /// \returns Statement for finished OpenMP region.
9371 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
9372 StmtResult ActOnOpenMPExecutableDirective(
9373 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
9374 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
9375 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
9376 /// Called on well-formed '\#pragma omp parallel' after parsing
9377 /// of the associated statement.
9378 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
9379 Stmt *AStmt,
9380 SourceLocation StartLoc,
9381 SourceLocation EndLoc);
9382 using VarsWithInheritedDSAType =
9383 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
9384 /// Called on well-formed '\#pragma omp simd' after parsing
9385 /// of the associated statement.
9386 StmtResult
9387 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9388 SourceLocation StartLoc, SourceLocation EndLoc,
9389 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9390 /// Called on well-formed '\#pragma omp for' after parsing
9391 /// of the associated statement.
9392 StmtResult
9393 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9394 SourceLocation StartLoc, SourceLocation EndLoc,
9395 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9396 /// Called on well-formed '\#pragma omp for simd' after parsing
9397 /// of the associated statement.
9398 StmtResult
9399 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9400 SourceLocation StartLoc, SourceLocation EndLoc,
9401 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9402 /// Called on well-formed '\#pragma omp sections' after parsing
9403 /// of the associated statement.
9404 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9405 Stmt *AStmt, SourceLocation StartLoc,
9406 SourceLocation EndLoc);
9407 /// Called on well-formed '\#pragma omp section' after parsing of the
9408 /// associated statement.
9409 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
9410 SourceLocation EndLoc);
9411 /// Called on well-formed '\#pragma omp single' after parsing of the
9412 /// associated statement.
9413 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9414 Stmt *AStmt, SourceLocation StartLoc,
9415 SourceLocation EndLoc);
9416 /// Called on well-formed '\#pragma omp master' after parsing of the
9417 /// associated statement.
9418 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
9419 SourceLocation EndLoc);
9420 /// Called on well-formed '\#pragma omp critical' after parsing of the
9421 /// associated statement.
9422 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
9423 ArrayRef<OMPClause *> Clauses,
9424 Stmt *AStmt, SourceLocation StartLoc,
9425 SourceLocation EndLoc);
9426 /// Called on well-formed '\#pragma omp parallel for' after parsing
9427 /// of the associated statement.
9428 StmtResult ActOnOpenMPParallelForDirective(
9429 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9430 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9431 /// Called on well-formed '\#pragma omp parallel for simd' after
9432 /// parsing of the associated statement.
9433 StmtResult ActOnOpenMPParallelForSimdDirective(
9434 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9435 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9436 /// Called on well-formed '\#pragma omp parallel sections' after
9437 /// parsing of the associated statement.
9438 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9439 Stmt *AStmt,
9440 SourceLocation StartLoc,
9441 SourceLocation EndLoc);
9442 /// Called on well-formed '\#pragma omp task' after parsing of the
9443 /// associated statement.
9444 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9445 Stmt *AStmt, SourceLocation StartLoc,
9446 SourceLocation EndLoc);
9447 /// Called on well-formed '\#pragma omp taskyield'.
9448 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9449 SourceLocation EndLoc);
9450 /// Called on well-formed '\#pragma omp barrier'.
9451 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9452 SourceLocation EndLoc);
9453 /// Called on well-formed '\#pragma omp taskwait'.
9454 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9455 SourceLocation EndLoc);
9456 /// Called on well-formed '\#pragma omp taskgroup'.
9457 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9458 Stmt *AStmt, SourceLocation StartLoc,
9459 SourceLocation EndLoc);
9460 /// Called on well-formed '\#pragma omp flush'.
9461 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9462 SourceLocation StartLoc,
9463 SourceLocation EndLoc);
9464 /// Called on well-formed '\#pragma omp ordered' after parsing of the
9465 /// associated statement.
9466 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9467 Stmt *AStmt, SourceLocation StartLoc,
9468 SourceLocation EndLoc);
9469 /// Called on well-formed '\#pragma omp atomic' after parsing of the
9470 /// associated statement.
9471 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9472 Stmt *AStmt, SourceLocation StartLoc,
9473 SourceLocation EndLoc);
9474 /// Called on well-formed '\#pragma omp target' after parsing of the
9475 /// associated statement.
9476 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9477 Stmt *AStmt, SourceLocation StartLoc,
9478 SourceLocation EndLoc);
9479 /// Called on well-formed '\#pragma omp target data' after parsing of
9480 /// the associated statement.
9481 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9482 Stmt *AStmt, SourceLocation StartLoc,
9483 SourceLocation EndLoc);
9484 /// Called on well-formed '\#pragma omp target enter data' after
9485 /// parsing of the associated statement.
9486 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9487 SourceLocation StartLoc,
9488 SourceLocation EndLoc,
9489 Stmt *AStmt);
9490 /// Called on well-formed '\#pragma omp target exit data' after
9491 /// parsing of the associated statement.
9492 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9493 SourceLocation StartLoc,
9494 SourceLocation EndLoc,
9495 Stmt *AStmt);
9496 /// Called on well-formed '\#pragma omp target parallel' after
9497 /// parsing of the associated statement.
9498 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9499 Stmt *AStmt,
9500 SourceLocation StartLoc,
9501 SourceLocation EndLoc);
9502 /// Called on well-formed '\#pragma omp target parallel for' after
9503 /// parsing of the associated statement.
9504 StmtResult ActOnOpenMPTargetParallelForDirective(
9505 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9506 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9507 /// Called on well-formed '\#pragma omp teams' after parsing of the
9508 /// associated statement.
9509 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9510 Stmt *AStmt, SourceLocation StartLoc,
9511 SourceLocation EndLoc);
9512 /// Called on well-formed '\#pragma omp cancellation point'.
9513 StmtResult
9514 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9515 SourceLocation EndLoc,
9516 OpenMPDirectiveKind CancelRegion);
9517 /// Called on well-formed '\#pragma omp cancel'.
9518 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9519 SourceLocation StartLoc,
9520 SourceLocation EndLoc,
9521 OpenMPDirectiveKind CancelRegion);
9522 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
9523 /// associated statement.
9524 StmtResult
9525 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9526 SourceLocation StartLoc, SourceLocation EndLoc,
9527 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9528 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
9529 /// the associated statement.
9530 StmtResult ActOnOpenMPTaskLoopSimdDirective(
9531 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9532 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9533 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
9534 /// associated statement.
9535 StmtResult ActOnOpenMPMasterTaskLoopDirective(
9536 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9537 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9538 /// Called on well-formed '\#pragma omp parallel master taskloop' after
9539 /// parsing of the associated statement.
9540 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
9541 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9542 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9543 /// Called on well-formed '\#pragma omp distribute' after parsing
9544 /// of the associated statement.
9545 StmtResult
9546 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9547 SourceLocation StartLoc, SourceLocation EndLoc,
9548 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9549 /// Called on well-formed '\#pragma omp target update'.
9550 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9551 SourceLocation StartLoc,
9552 SourceLocation EndLoc,
9553 Stmt *AStmt);
9554 /// Called on well-formed '\#pragma omp distribute parallel for' after
9555 /// parsing of the associated statement.
9556 StmtResult ActOnOpenMPDistributeParallelForDirective(
9557 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9558 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9559 /// Called on well-formed '\#pragma omp distribute parallel for simd'
9560 /// after parsing of the associated statement.
9561 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
9562 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9563 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9564 /// Called on well-formed '\#pragma omp distribute simd' after
9565 /// parsing of the associated statement.
9566 StmtResult ActOnOpenMPDistributeSimdDirective(
9567 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9568 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9569 /// Called on well-formed '\#pragma omp target parallel for simd' after
9570 /// parsing of the associated statement.
9571 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
9572 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9573 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9574 /// Called on well-formed '\#pragma omp target simd' after parsing of
9575 /// the associated statement.
9576 StmtResult
9577 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9578 SourceLocation StartLoc, SourceLocation EndLoc,
9579 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9580 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
9581 /// the associated statement.
9582 StmtResult ActOnOpenMPTeamsDistributeDirective(
9583 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9584 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9585 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
9586 /// of the associated statement.
9587 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
9588 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9589 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9590 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
9591 /// after parsing of the associated statement.
9592 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
9593 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9594 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9595 /// Called on well-formed '\#pragma omp teams distribute parallel for'
9596 /// after parsing of the associated statement.
9597 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
9598 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9599 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9600 /// Called on well-formed '\#pragma omp target teams' after parsing of the
9601 /// associated statement.
9602 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
9603 Stmt *AStmt,
9604 SourceLocation StartLoc,
9605 SourceLocation EndLoc);
9606 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
9607 /// of the associated statement.
9608 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
9609 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9610 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9611 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
9612 /// after parsing of the associated statement.
9613 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
9614 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9615 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9616 /// Called on well-formed '\#pragma omp target teams distribute parallel for
9617 /// simd' after parsing of the associated statement.
9618 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9619 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9620 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9621 /// Called on well-formed '\#pragma omp target teams distribute simd' after
9622 /// parsing of the associated statement.
9623 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
9624 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9625 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9626
9627 /// Checks correctness of linear modifiers.
9628 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9629 SourceLocation LinLoc);
9630 /// Checks that the specified declaration matches requirements for the linear
9631 /// decls.
9632 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
9633 OpenMPLinearClauseKind LinKind, QualType Type);
9634
9635 /// Called on well-formed '\#pragma omp declare simd' after parsing of
9636 /// the associated method/function.
9637 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
9638 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
9639 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
9640 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
9641 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
9642
9643 /// Checks '\#pragma omp declare variant' variant function and original
9644 /// functions after parsing of the associated method/function.
9645 /// \param DG Function declaration to which declare variant directive is
9646 /// applied to.
9647 /// \param VariantRef Expression that references the variant function, which
9648 /// must be used instead of the original one, specified in \p DG.
9649 /// \returns None, if the function/variant function are not compatible with
9650 /// the pragma, pair of original function/variant ref expression otherwise.
9651 Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(
9652 DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR);
9653
9654 /// Called on well-formed '\#pragma omp declare variant' after parsing of
9655 /// the associated method/function.
9656 /// \param FD Function declaration to which declare variant directive is
9657 /// applied to.
9658 /// \param VariantRef Expression that references the variant function, which
9659 /// must be used instead of the original one, specified in \p DG.
9660 /// \param Data Set of context-specific data for the specified context
9661 /// selector.
9662 void ActOnOpenMPDeclareVariantDirective(
9663 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
9664 const Sema::OpenMPDeclareVariantCtsSelectorData &Data);
9665
9666 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
9667 Expr *Expr,
9668 SourceLocation StartLoc,
9669 SourceLocation LParenLoc,
9670 SourceLocation EndLoc);
9671 /// Called on well-formed 'allocator' clause.
9672 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
9673 SourceLocation StartLoc,
9674 SourceLocation LParenLoc,
9675 SourceLocation EndLoc);
9676 /// Called on well-formed 'if' clause.
9677 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9678 Expr *Condition, SourceLocation StartLoc,
9679 SourceLocation LParenLoc,
9680 SourceLocation NameModifierLoc,
9681 SourceLocation ColonLoc,
9682 SourceLocation EndLoc);
9683 /// Called on well-formed 'final' clause.
9684 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
9685 SourceLocation LParenLoc,
9686 SourceLocation EndLoc);
9687 /// Called on well-formed 'num_threads' clause.
9688 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9689 SourceLocation StartLoc,
9690 SourceLocation LParenLoc,
9691 SourceLocation EndLoc);
9692 /// Called on well-formed 'safelen' clause.
9693 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
9694 SourceLocation StartLoc,
9695 SourceLocation LParenLoc,
9696 SourceLocation EndLoc);
9697 /// Called on well-formed 'simdlen' clause.
9698 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
9699 SourceLocation LParenLoc,
9700 SourceLocation EndLoc);
9701 /// Called on well-formed 'collapse' clause.
9702 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
9703 SourceLocation StartLoc,
9704 SourceLocation LParenLoc,
9705 SourceLocation EndLoc);
9706 /// Called on well-formed 'ordered' clause.
9707 OMPClause *
9708 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
9709 SourceLocation LParenLoc = SourceLocation(),
9710 Expr *NumForLoops = nullptr);
9711 /// Called on well-formed 'grainsize' clause.
9712 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
9713 SourceLocation LParenLoc,
9714 SourceLocation EndLoc);
9715 /// Called on well-formed 'num_tasks' clause.
9716 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
9717 SourceLocation LParenLoc,
9718 SourceLocation EndLoc);
9719 /// Called on well-formed 'hint' clause.
9720 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
9721 SourceLocation LParenLoc,
9722 SourceLocation EndLoc);
9723
9724 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
9725 unsigned Argument,
9726 SourceLocation ArgumentLoc,
9727 SourceLocation StartLoc,
9728 SourceLocation LParenLoc,
9729 SourceLocation EndLoc);
9730 /// Called on well-formed 'default' clause.
9731 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9732 SourceLocation KindLoc,
9733 SourceLocation StartLoc,
9734 SourceLocation LParenLoc,
9735 SourceLocation EndLoc);
9736 /// Called on well-formed 'proc_bind' clause.
9737 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9738 SourceLocation KindLoc,
9739 SourceLocation StartLoc,
9740 SourceLocation LParenLoc,
9741 SourceLocation EndLoc);
9742
9743 OMPClause *ActOnOpenMPSingleExprWithArgClause(
9744 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
9745 SourceLocation StartLoc, SourceLocation LParenLoc,
9746 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
9747 SourceLocation EndLoc);
9748 /// Called on well-formed 'schedule' clause.
9749 OMPClause *ActOnOpenMPScheduleClause(
9750 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9751 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9752 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9753 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
9754
9755 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
9756 SourceLocation EndLoc);
9757 /// Called on well-formed 'nowait' clause.
9758 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9759 SourceLocation EndLoc);
9760 /// Called on well-formed 'untied' clause.
9761 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9762 SourceLocation EndLoc);
9763 /// Called on well-formed 'mergeable' clause.
9764 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9765 SourceLocation EndLoc);
9766 /// Called on well-formed 'read' clause.
9767 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
9768 SourceLocation EndLoc);
9769 /// Called on well-formed 'write' clause.
9770 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
9771 SourceLocation EndLoc);
9772 /// Called on well-formed 'update' clause.
9773 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9774 SourceLocation EndLoc);
9775 /// Called on well-formed 'capture' clause.
9776 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9777 SourceLocation EndLoc);
9778 /// Called on well-formed 'seq_cst' clause.
9779 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9780 SourceLocation EndLoc);
9781 /// Called on well-formed 'threads' clause.
9782 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9783 SourceLocation EndLoc);
9784 /// Called on well-formed 'simd' clause.
9785 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9786 SourceLocation EndLoc);
9787 /// Called on well-formed 'nogroup' clause.
9788 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9789 SourceLocation EndLoc);
9790 /// Called on well-formed 'unified_address' clause.
9791 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9792 SourceLocation EndLoc);
9793
9794 /// Called on well-formed 'unified_address' clause.
9795 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9796 SourceLocation EndLoc);
9797
9798 /// Called on well-formed 'reverse_offload' clause.
9799 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9800 SourceLocation EndLoc);
9801
9802 /// Called on well-formed 'dynamic_allocators' clause.
9803 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9804 SourceLocation EndLoc);
9805
9806 /// Called on well-formed 'atomic_default_mem_order' clause.
9807 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
9808 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
9809 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
9810
9811 OMPClause *ActOnOpenMPVarListClause(
9812 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
9813 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
9814 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
9815 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
9816 OpenMPLinearClauseKind LinKind,
9817 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
9818 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
9819 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc);
9820 /// Called on well-formed 'allocate' clause.
9821 OMPClause *
9822 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
9823 SourceLocation StartLoc, SourceLocation ColonLoc,
9824 SourceLocation LParenLoc, SourceLocation EndLoc);
9825 /// Called on well-formed 'private' clause.
9826 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9827 SourceLocation StartLoc,
9828 SourceLocation LParenLoc,
9829 SourceLocation EndLoc);
9830 /// Called on well-formed 'firstprivate' clause.
9831 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9832 SourceLocation StartLoc,
9833 SourceLocation LParenLoc,
9834 SourceLocation EndLoc);
9835 /// Called on well-formed 'lastprivate' clause.
9836 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9837 SourceLocation StartLoc,
9838 SourceLocation LParenLoc,
9839 SourceLocation EndLoc);
9840 /// Called on well-formed 'shared' clause.
9841 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9842 SourceLocation StartLoc,
9843 SourceLocation LParenLoc,
9844 SourceLocation EndLoc);
9845 /// Called on well-formed 'reduction' clause.
9846 OMPClause *ActOnOpenMPReductionClause(
9847 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9848 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9849 CXXScopeSpec &ReductionIdScopeSpec,
9850 const DeclarationNameInfo &ReductionId,
9851 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9852 /// Called on well-formed 'task_reduction' clause.
9853 OMPClause *ActOnOpenMPTaskReductionClause(
9854 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9855 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9856 CXXScopeSpec &ReductionIdScopeSpec,
9857 const DeclarationNameInfo &ReductionId,
9858 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9859 /// Called on well-formed 'in_reduction' clause.
9860 OMPClause *ActOnOpenMPInReductionClause(
9861 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9862 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9863 CXXScopeSpec &ReductionIdScopeSpec,
9864 const DeclarationNameInfo &ReductionId,
9865 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9866 /// Called on well-formed 'linear' clause.
9867 OMPClause *
9868 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9869 SourceLocation StartLoc, SourceLocation LParenLoc,
9870 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9871 SourceLocation ColonLoc, SourceLocation EndLoc);
9872 /// Called on well-formed 'aligned' clause.
9873 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9874 Expr *Alignment,
9875 SourceLocation StartLoc,
9876 SourceLocation LParenLoc,
9877 SourceLocation ColonLoc,
9878 SourceLocation EndLoc);
9879 /// Called on well-formed 'copyin' clause.
9880 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9881 SourceLocation StartLoc,
9882 SourceLocation LParenLoc,
9883 SourceLocation EndLoc);
9884 /// Called on well-formed 'copyprivate' clause.
9885 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9886 SourceLocation StartLoc,
9887 SourceLocation LParenLoc,
9888 SourceLocation EndLoc);
9889 /// Called on well-formed 'flush' pseudo clause.
9890 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9891 SourceLocation StartLoc,
9892 SourceLocation LParenLoc,
9893 SourceLocation EndLoc);
9894 /// Called on well-formed 'depend' clause.
9895 OMPClause *
9896 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9897 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9898 SourceLocation StartLoc, SourceLocation LParenLoc,
9899 SourceLocation EndLoc);
9900 /// Called on well-formed 'device' clause.
9901 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9902 SourceLocation LParenLoc,
9903 SourceLocation EndLoc);
9904 /// Called on well-formed 'map' clause.
9905 OMPClause *
9906 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
9907 ArrayRef<SourceLocation> MapTypeModifiersLoc,
9908 CXXScopeSpec &MapperIdScopeSpec,
9909 DeclarationNameInfo &MapperId,
9910 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9911 SourceLocation MapLoc, SourceLocation ColonLoc,
9912 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
9913 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
9914 /// Called on well-formed 'num_teams' clause.
9915 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9916 SourceLocation LParenLoc,
9917 SourceLocation EndLoc);
9918 /// Called on well-formed 'thread_limit' clause.
9919 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9920 SourceLocation StartLoc,
9921 SourceLocation LParenLoc,
9922 SourceLocation EndLoc);
9923 /// Called on well-formed 'priority' clause.
9924 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9925 SourceLocation LParenLoc,
9926 SourceLocation EndLoc);
9927 /// Called on well-formed 'dist_schedule' clause.
9928 OMPClause *ActOnOpenMPDistScheduleClause(
9929 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9930 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9931 SourceLocation CommaLoc, SourceLocation EndLoc);
9932 /// Called on well-formed 'defaultmap' clause.
9933 OMPClause *ActOnOpenMPDefaultmapClause(
9934 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9935 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9936 SourceLocation KindLoc, SourceLocation EndLoc);
9937 /// Called on well-formed 'to' clause.
9938 OMPClause *
9939 ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
9940 DeclarationNameInfo &MapperId,
9941 const OMPVarListLocTy &Locs,
9942 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
9943 /// Called on well-formed 'from' clause.
9944 OMPClause *ActOnOpenMPFromClause(
9945 ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
9946 DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
9947 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
9948 /// Called on well-formed 'use_device_ptr' clause.
9949 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9950 const OMPVarListLocTy &Locs);
9951 /// Called on well-formed 'is_device_ptr' clause.
9952 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9953 const OMPVarListLocTy &Locs);
9954
9955 /// The kind of conversion being performed.
9956 enum CheckedConversionKind {
9957 /// An implicit conversion.
9958 CCK_ImplicitConversion,
9959 /// A C-style cast.
9960 CCK_CStyleCast,
9961 /// A functional-style cast.
9962 CCK_FunctionalCast,
9963 /// A cast other than a C-style cast.
9964 CCK_OtherCast,
9965 /// A conversion for an operand of a builtin overloaded operator.
9966 CCK_ForBuiltinOverloadedOp
9967 };
9968
9969 static bool isCast(CheckedConversionKind CCK) {
9970 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
9971 CCK == CCK_OtherCast;
9972 }
9973
9974 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9975 /// cast. If there is already an implicit cast, merge into the existing one.
9976 /// If isLvalue, the result of the cast is an lvalue.
9977 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9978 ExprValueKind VK = VK_RValue,
9979 const CXXCastPath *BasePath = nullptr,
9980 CheckedConversionKind CCK
9981 = CCK_ImplicitConversion);
9982
9983 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9984 /// to the conversion from scalar type ScalarTy to the Boolean type.
9985 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9986
9987 /// IgnoredValueConversions - Given that an expression's result is
9988 /// syntactically ignored, perform any conversions that are
9989 /// required.
9990 ExprResult IgnoredValueConversions(Expr *E);
9991
9992 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9993 // functions and arrays to their respective pointers (C99 6.3.2.1).
9994 ExprResult UsualUnaryConversions(Expr *E);
9995
9996 /// CallExprUnaryConversions - a special case of an unary conversion
9997 /// performed on a function designator of a call expression.
9998 ExprResult CallExprUnaryConversions(Expr *E);
9999
10000 // DefaultFunctionArrayConversion - converts functions and arrays
10001 // to their respective pointers (C99 6.3.2.1).
10002 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
10003
10004 // DefaultFunctionArrayLvalueConversion - converts functions and
10005 // arrays to their respective pointers and performs the
10006 // lvalue-to-rvalue conversion.
10007 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
10008 bool Diagnose = true);
10009
10010 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
10011 // the operand. This is DefaultFunctionArrayLvalueConversion,
10012 // except that it assumes the operand isn't of function or array
10013 // type.
10014 ExprResult DefaultLvalueConversion(Expr *E);
10015
10016 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
10017 // do not have a prototype. Integer promotions are performed on each
10018 // argument, and arguments that have type float are promoted to double.
10019 ExprResult DefaultArgumentPromotion(Expr *E);
10020
10021 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
10022 /// it as an xvalue. In C++98, the result will still be a prvalue, because
10023 /// we don't have xvalues there.
10024 ExprResult TemporaryMaterializationConversion(Expr *E);
10025
10026 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
10027 enum VariadicCallType {
10028 VariadicFunction,
10029 VariadicBlock,
10030 VariadicMethod,
10031 VariadicConstructor,
10032 VariadicDoesNotApply
10033 };
10034
10035 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
10036 const FunctionProtoType *Proto,
10037 Expr *Fn);
10038
10039 // Used for determining in which context a type is allowed to be passed to a
10040 // vararg function.
10041 enum VarArgKind {
10042 VAK_Valid,
10043 VAK_ValidInCXX11,
10044 VAK_Undefined,
10045 VAK_MSVCUndefined,
10046 VAK_Invalid
10047 };
10048
10049 // Determines which VarArgKind fits an expression.
10050 VarArgKind isValidVarArgType(const QualType &Ty);
10051
10052 /// Check to see if the given expression is a valid argument to a variadic
10053 /// function, issuing a diagnostic if not.
10054 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
10055
10056 /// Check to see if a given expression could have '.c_str()' called on it.
10057 bool hasCStrMethod(const Expr *E);
10058
10059 /// GatherArgumentsForCall - Collector argument expressions for various
10060 /// form of call prototypes.
10061 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
10062 const FunctionProtoType *Proto,
10063 unsigned FirstParam, ArrayRef<Expr *> Args,
10064 SmallVectorImpl<Expr *> &AllArgs,
10065 VariadicCallType CallType = VariadicDoesNotApply,
10066 bool AllowExplicit = false,
10067 bool IsListInitialization = false);
10068
10069 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
10070 // will create a runtime trap if the resulting type is not a POD type.
10071 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
10072 FunctionDecl *FDecl);
10073
10074 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
10075 // operands and then handles various conversions that are common to binary
10076 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
10077 // routine returns the first non-arithmetic type found. The client is
10078 // responsible for emitting appropriate error diagnostics.
10079 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
10080 bool IsCompAssign = false);
10081
10082 /// AssignConvertType - All of the 'assignment' semantic checks return this
10083 /// enum to indicate whether the assignment was allowed. These checks are
10084 /// done for simple assignments, as well as initialization, return from
10085 /// function, argument passing, etc. The query is phrased in terms of a
10086 /// source and destination type.
10087 enum AssignConvertType {
10088 /// Compatible - the types are compatible according to the standard.
10089 Compatible,
10090
10091 /// PointerToInt - The assignment converts a pointer to an int, which we
10092 /// accept as an extension.
10093 PointerToInt,
10094
10095 /// IntToPointer - The assignment converts an int to a pointer, which we
10096 /// accept as an extension.
10097 IntToPointer,
10098
10099 /// FunctionVoidPointer - The assignment is between a function pointer and
10100 /// void*, which the standard doesn't allow, but we accept as an extension.
10101 FunctionVoidPointer,
10102
10103 /// IncompatiblePointer - The assignment is between two pointers types that
10104 /// are not compatible, but we accept them as an extension.
10105 IncompatiblePointer,
10106
10107 /// IncompatiblePointerSign - The assignment is between two pointers types
10108 /// which point to integers which have a different sign, but are otherwise
10109 /// identical. This is a subset of the above, but broken out because it's by
10110 /// far the most common case of incompatible pointers.
10111 IncompatiblePointerSign,
10112
10113 /// CompatiblePointerDiscardsQualifiers - The assignment discards
10114 /// c/v/r qualifiers, which we accept as an extension.
10115 CompatiblePointerDiscardsQualifiers,
10116
10117 /// IncompatiblePointerDiscardsQualifiers - The assignment
10118 /// discards qualifiers that we don't permit to be discarded,
10119 /// like address spaces.
10120 IncompatiblePointerDiscardsQualifiers,
10121
10122 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
10123 /// changes address spaces in nested pointer types which is not allowed.
10124 /// For instance, converting __private int ** to __generic int ** is
10125 /// illegal even though __private could be converted to __generic.
10126 IncompatibleNestedPointerAddressSpaceMismatch,
10127
10128 /// IncompatibleNestedPointerQualifiers - The assignment is between two
10129 /// nested pointer types, and the qualifiers other than the first two
10130 /// levels differ e.g. char ** -> const char **, but we accept them as an
10131 /// extension.
10132 IncompatibleNestedPointerQualifiers,
10133
10134 /// IncompatibleVectors - The assignment is between two vector types that
10135 /// have the same size, which we accept as an extension.
10136 IncompatibleVectors,
10137
10138 /// IntToBlockPointer - The assignment converts an int to a block
10139 /// pointer. We disallow this.
10140 IntToBlockPointer,
10141
10142 /// IncompatibleBlockPointer - The assignment is between two block
10143 /// pointers types that are not compatible.
10144 IncompatibleBlockPointer,
10145
10146 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
10147 /// id type and something else (that is incompatible with it). For example,
10148 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
10149 IncompatibleObjCQualifiedId,
10150
10151 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
10152 /// object with __weak qualifier.
10153 IncompatibleObjCWeakRef,
10154
10155 /// Incompatible - We reject this conversion outright, it is invalid to
10156 /// represent it in the AST.
10157 Incompatible
10158 };
10159
10160 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
10161 /// assignment conversion type specified by ConvTy. This returns true if the
10162 /// conversion was invalid or false if the conversion was accepted.
10163 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
10164 SourceLocation Loc,
10165 QualType DstType, QualType SrcType,
10166 Expr *SrcExpr, AssignmentAction Action,
10167 bool *Complained = nullptr);
10168
10169 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
10170 /// enum. If AllowMask is true, then we also allow the complement of a valid
10171 /// value, to be used as a mask.
10172 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
10173 bool AllowMask) const;
10174
10175 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
10176 /// integer not in the range of enum values.
10177 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
10178 Expr *SrcExpr);
10179
10180 /// CheckAssignmentConstraints - Perform type checking for assignment,
10181 /// argument passing, variable initialization, and function return values.
10182 /// C99 6.5.16.
10183 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
10184 QualType LHSType,
10185 QualType RHSType);
10186
10187 /// Check assignment constraints and optionally prepare for a conversion of
10188 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
10189 /// is true.
10190 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
10191 ExprResult &RHS,
10192 CastKind &Kind,
10193 bool ConvertRHS = true);
10194
10195 /// Check assignment constraints for an assignment of RHS to LHSType.
10196 ///
10197 /// \param LHSType The destination type for the assignment.
10198 /// \param RHS The source expression for the assignment.
10199 /// \param Diagnose If \c true, diagnostics may be produced when checking
10200 /// for assignability. If a diagnostic is produced, \p RHS will be
10201 /// set to ExprError(). Note that this function may still return
10202 /// without producing a diagnostic, even for an invalid assignment.
10203 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
10204 /// in an audited Core Foundation API and does not need to be checked
10205 /// for ARC retain issues.
10206 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
10207 /// conversions necessary to perform the assignment. If \c false,
10208 /// \p Diagnose must also be \c false.
10209 AssignConvertType CheckSingleAssignmentConstraints(
10210 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
10211 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
10212
10213 // If the lhs type is a transparent union, check whether we
10214 // can initialize the transparent union with the given expression.
10215 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
10216 ExprResult &RHS);
10217
10218 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
10219
10220 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
10221
10222 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10223 AssignmentAction Action,
10224 bool AllowExplicit = false);
10225 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10226 AssignmentAction Action,
10227 bool AllowExplicit,
10228 ImplicitConversionSequence& ICS);
10229 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10230 const ImplicitConversionSequence& ICS,
10231 AssignmentAction Action,
10232 CheckedConversionKind CCK
10233 = CCK_ImplicitConversion);
10234 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10235 const StandardConversionSequence& SCS,
10236 AssignmentAction Action,
10237 CheckedConversionKind CCK);
10238
10239 ExprResult PerformQualificationConversion(
10240 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
10241 CheckedConversionKind CCK = CCK_ImplicitConversion);
10242
10243 /// the following "Check" methods will return a valid/converted QualType
10244 /// or a null QualType (indicating an error diagnostic was issued).
10245
10246 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
10247 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10248 ExprResult &RHS);
10249 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10250 ExprResult &RHS);
10251 QualType CheckPointerToMemberOperands( // C++ 5.5
10252 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
10253 SourceLocation OpLoc, bool isIndirect);
10254 QualType CheckMultiplyDivideOperands( // C99 6.5.5
10255 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
10256 bool IsDivide);
10257 QualType CheckRemainderOperands( // C99 6.5.5
10258 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10259 bool IsCompAssign = false);
10260 QualType CheckAdditionOperands( // C99 6.5.6
10261 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10262 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
10263 QualType CheckSubtractionOperands( // C99 6.5.6
10264 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10265 QualType* CompLHSTy = nullptr);
10266 QualType CheckShiftOperands( // C99 6.5.7
10267 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10268 BinaryOperatorKind Opc, bool IsCompAssign = false);
10269 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
10270 QualType CheckCompareOperands( // C99 6.5.8/9
10271 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10272 BinaryOperatorKind Opc);
10273 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
10274 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10275 BinaryOperatorKind Opc);
10276 QualType CheckLogicalOperands( // C99 6.5.[13,14]
10277 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10278 BinaryOperatorKind Opc);
10279 // CheckAssignmentOperands is used for both simple and compound assignment.
10280 // For simple assignment, pass both expressions and a null converted type.
10281 // For compound assignment, pass both expressions and the converted type.
10282 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
10283 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
10284
10285 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
10286 UnaryOperatorKind Opcode, Expr *Op);
10287 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
10288 BinaryOperatorKind Opcode,
10289 Expr *LHS, Expr *RHS);
10290 ExprResult checkPseudoObjectRValue(Expr *E);
10291 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
10292
10293 QualType CheckConditionalOperands( // C99 6.5.15
10294 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
10295 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
10296 QualType CXXCheckConditionalOperands( // C++ 5.16
10297 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
10298 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
10299 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
10300 bool ConvertArgs = true);
10301 QualType FindCompositePointerType(SourceLocation Loc,
10302 ExprResult &E1, ExprResult &E2,
10303 bool ConvertArgs = true) {
10304 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
10305 QualType Composite =
10306 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
10307 E1 = E1Tmp;
10308 E2 = E2Tmp;
10309 return Composite;
10310 }
10311
10312 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
10313 SourceLocation QuestionLoc);
10314
10315 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
10316 SourceLocation QuestionLoc);
10317
10318 void DiagnoseAlwaysNonNullPointer(Expr *E,
10319 Expr::NullPointerConstantKind NullType,
10320 bool IsEqual, SourceRange Range);
10321
10322 /// type checking for vector binary operators.
10323 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10324 SourceLocation Loc, bool IsCompAssign,
10325 bool AllowBothBool, bool AllowBoolConversion);
10326 QualType GetSignedVectorType(QualType V);
10327 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10328 SourceLocation Loc,
10329 BinaryOperatorKind Opc);
10330 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10331 SourceLocation Loc);
10332
10333 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
10334 bool isLaxVectorConversion(QualType srcType, QualType destType);
10335
10336 /// type checking declaration initializers (C99 6.7.8)
10337 bool CheckForConstantInitializer(Expr *e, QualType t);
10338
10339 // type checking C++ declaration initializers (C++ [dcl.init]).
10340
10341 /// ReferenceCompareResult - Expresses the result of comparing two
10342 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10343 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10344 enum ReferenceCompareResult {
10345 /// Ref_Incompatible - The two types are incompatible, so direct
10346 /// reference binding is not possible.
10347 Ref_Incompatible = 0,
10348 /// Ref_Related - The two types are reference-related, which means
10349 /// that their unqualified forms (T1 and T2) are either the same
10350 /// or T1 is a base class of T2.
10351 Ref_Related,
10352 /// Ref_Compatible - The two types are reference-compatible.
10353 Ref_Compatible
10354 };
10355
10356 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
10357 QualType T1, QualType T2,
10358 bool &DerivedToBase,
10359 bool &ObjCConversion,
10360 bool &ObjCLifetimeConversion);
10361
10362 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10363 Expr *CastExpr, CastKind &CastKind,
10364 ExprValueKind &VK, CXXCastPath &Path);
10365
10366 /// Force an expression with unknown-type to an expression of the
10367 /// given type.
10368 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
10369
10370 /// Type-check an expression that's being passed to an
10371 /// __unknown_anytype parameter.
10372 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
10373 Expr *result, QualType &paramType);
10374
10375 // CheckVectorCast - check type constraints for vectors.
10376 // Since vectors are an extension, there are no C standard reference for this.
10377 // We allow casting between vectors and integer datatypes of the same size.
10378 // returns true if the cast is invalid
10379 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
10380 CastKind &Kind);
10381
10382 /// Prepare `SplattedExpr` for a vector splat operation, adding
10383 /// implicit casts if necessary.
10384 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
10385
10386 // CheckExtVectorCast - check type constraints for extended vectors.
10387 // Since vectors are an extension, there are no C standard reference for this.
10388 // We allow casting between vectors and integer datatypes of the same size,
10389 // or vectors and the element type of that vector.
10390 // returns the cast expr
10391 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
10392 CastKind &Kind);
10393
10394 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
10395 SourceLocation LParenLoc,
10396 Expr *CastExpr,
10397 SourceLocation RParenLoc);
10398
10399 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
10400
10401 /// Checks for invalid conversions and casts between
10402 /// retainable pointers and other pointer kinds for ARC and Weak.
10403 ARCConversionResult CheckObjCConversion(SourceRange castRange,
10404 QualType castType, Expr *&op,
10405 CheckedConversionKind CCK,
10406 bool Diagnose = true,
10407 bool DiagnoseCFAudited = false,
10408 BinaryOperatorKind Opc = BO_PtrMemD
10409 );
10410
10411 Expr *stripARCUnbridgedCast(Expr *e);
10412 void diagnoseARCUnbridgedCast(Expr *e);
10413
10414 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
10415 QualType ExprType);
10416
10417 /// checkRetainCycles - Check whether an Objective-C message send
10418 /// might create an obvious retain cycle.
10419 void checkRetainCycles(ObjCMessageExpr *msg);
10420 void checkRetainCycles(Expr *receiver, Expr *argument);
10421 void checkRetainCycles(VarDecl *Var, Expr *Init);
10422
10423 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
10424 /// to weak/__unsafe_unretained type.
10425 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
10426
10427 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
10428 /// to weak/__unsafe_unretained expression.
10429 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
10430
10431 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
10432 /// \param Method - May be null.
10433 /// \param [out] ReturnType - The return type of the send.
10434 /// \return true iff there were any incompatible types.
10435 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
10436 MultiExprArg Args, Selector Sel,
10437 ArrayRef<SourceLocation> SelectorLocs,
10438 ObjCMethodDecl *Method, bool isClassMessage,
10439 bool isSuperMessage, SourceLocation lbrac,
10440 SourceLocation rbrac, SourceRange RecRange,
10441 QualType &ReturnType, ExprValueKind &VK);
10442
10443 /// Determine the result of a message send expression based on
10444 /// the type of the receiver, the method expected to receive the message,
10445 /// and the form of the message send.
10446 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
10447 ObjCMethodDecl *Method, bool isClassMessage,
10448 bool isSuperMessage);
10449
10450 /// If the given expression involves a message send to a method
10451 /// with a related result type, emit a note describing what happened.
10452 void EmitRelatedResultTypeNote(const Expr *E);
10453
10454 /// Given that we had incompatible pointer types in a return
10455 /// statement, check whether we're in a method with a related result
10456 /// type, and if so, emit a note describing what happened.
10457 void EmitRelatedResultTypeNoteForReturn(QualType destType);
10458
10459 class ConditionResult {
10460 Decl *ConditionVar;
10461 FullExprArg Condition;
10462 bool Invalid;
10463 bool HasKnownValue;
10464 bool KnownValue;
10465
10466 friend class Sema;
10467 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
10468 bool IsConstexpr)
10469 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
10470 HasKnownValue(IsConstexpr && Condition.get() &&
10471 !Condition.get()->isValueDependent()),
10472 KnownValue(HasKnownValue &&
10473 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
10474 explicit ConditionResult(bool Invalid)
10475 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
10476 HasKnownValue(false), KnownValue(false) {}
10477
10478 public:
10479 ConditionResult() : ConditionResult(false) {}
10480 bool isInvalid() const { return Invalid; }
10481 std::pair<VarDecl *, Expr *> get() const {
10482 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
10483 Condition.get());
10484 }
10485 llvm::Optional<bool> getKnownValue() const {
10486 if (!HasKnownValue)
10487 return None;
10488 return KnownValue;
10489 }
10490 };
10491 static ConditionResult ConditionError() { return ConditionResult(true); }
10492
10493 enum class ConditionKind {
10494 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
10495 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
10496 Switch ///< An integral condition for a 'switch' statement.
10497 };
10498
10499 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
10500 Expr *SubExpr, ConditionKind CK);
10501
10502 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
10503 SourceLocation StmtLoc,
10504 ConditionKind CK);
10505
10506 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
10507
10508 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
10509 SourceLocation StmtLoc,
10510 ConditionKind CK);
10511 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
10512
10513 /// CheckBooleanCondition - Diagnose problems involving the use of
10514 /// the given expression as a boolean condition (e.g. in an if
10515 /// statement). Also performs the standard function and array
10516 /// decays, possibly changing the input variable.
10517 ///
10518 /// \param Loc - A location associated with the condition, e.g. the
10519 /// 'if' keyword.
10520 /// \return true iff there were any errors
10521 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
10522 bool IsConstexpr = false);
10523
10524 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
10525 /// found in an explicit(bool) specifier.
10526 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
10527
10528 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
10529 /// Returns true if the explicit specifier is now resolved.
10530 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
10531
10532 /// DiagnoseAssignmentAsCondition - Given that an expression is
10533 /// being used as a boolean condition, warn if it's an assignment.
10534 void DiagnoseAssignmentAsCondition(Expr *E);
10535
10536 /// Redundant parentheses over an equality comparison can indicate
10537 /// that the user intended an assignment used as condition.
10538 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
10539
10540 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
10541 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
10542
10543 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
10544 /// the specified width and sign. If an overflow occurs, detect it and emit
10545 /// the specified diagnostic.
10546 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
10547 unsigned NewWidth, bool NewSign,
10548 SourceLocation Loc, unsigned DiagID);
10549
10550 /// Checks that the Objective-C declaration is declared in the global scope.
10551 /// Emits an error and marks the declaration as invalid if it's not declared
10552 /// in the global scope.
10553 bool CheckObjCDeclScope(Decl *D);
10554
10555 /// Abstract base class used for diagnosing integer constant
10556 /// expression violations.
10557 class VerifyICEDiagnoser {
10558 public:
10559 bool Suppress;
10560
10561 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
10562
10563 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
10564 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
10565 virtual ~VerifyICEDiagnoser() { }
10566 };
10567
10568 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
10569 /// and reports the appropriate diagnostics. Returns false on success.
10570 /// Can optionally return the value of the expression.
10571 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10572 VerifyICEDiagnoser &Diagnoser,
10573 bool AllowFold = true);
10574 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10575 unsigned DiagID,
10576 bool AllowFold = true);
10577 ExprResult VerifyIntegerConstantExpression(Expr *E,
10578 llvm::APSInt *Result = nullptr);
10579
10580 /// VerifyBitField - verifies that a bit field expression is an ICE and has
10581 /// the correct width, and that the field type is valid.
10582 /// Returns false on success.
10583 /// Can optionally return whether the bit-field is of width 0
10584 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
10585 QualType FieldTy, bool IsMsStruct,
10586 Expr *BitWidth, bool *ZeroWidth = nullptr);
10587
10588private:
10589 unsigned ForceCUDAHostDeviceDepth = 0;
10590
10591public:
10592 /// Increments our count of the number of times we've seen a pragma forcing
10593 /// functions to be __host__ __device__. So long as this count is greater
10594 /// than zero, all functions encountered will be __host__ __device__.
10595 void PushForceCUDAHostDevice();
10596
10597 /// Decrements our count of the number of times we've seen a pragma forcing
10598 /// functions to be __host__ __device__. Returns false if the count is 0
10599 /// before incrementing, so you can emit an error.
10600 bool PopForceCUDAHostDevice();
10601
10602 /// Diagnostics that are emitted only if we discover that the given function
10603 /// must be codegen'ed. Because handling these correctly adds overhead to
10604 /// compilation, this is currently only enabled for CUDA compilations.
10605 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
10606 std::vector<PartialDiagnosticAt>>
10607 DeviceDeferredDiags;
10608
10609 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
10610 /// key in a hashtable, both the FD and location are hashed.
10611 struct FunctionDeclAndLoc {
10612 CanonicalDeclPtr<FunctionDecl> FD;
10613 SourceLocation Loc;
10614 };
10615
10616 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
10617 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
10618 /// same deferred diag twice.
10619 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
10620
10621 /// An inverse call graph, mapping known-emitted functions to one of their
10622 /// known-emitted callers (plus the location of the call).
10623 ///
10624 /// Functions that we can tell a priori must be emitted aren't added to this
10625 /// map.
10626 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
10627 /* Caller = */ FunctionDeclAndLoc>
10628 DeviceKnownEmittedFns;
10629
10630 /// A partial call graph maintained during CUDA/OpenMP device code compilation
10631 /// to support deferred diagnostics.
10632 ///
10633 /// Functions are only added here if, at the time they're considered, they are
10634 /// not known-emitted. As soon as we discover that a function is
10635 /// known-emitted, we remove it and everything it transitively calls from this
10636 /// set and add those functions to DeviceKnownEmittedFns.
10637 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
10638 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
10639 SourceLocation>>
10640 DeviceCallGraph;
10641
10642 /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
10643 /// deferred.
10644 ///
10645 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
10646 /// which are not allowed to appear inside __device__ functions and are
10647 /// allowed to appear in __host__ __device__ functions only if the host+device
10648 /// function is never codegen'ed.
10649 ///
10650 /// To handle this, we use the notion of "deferred diagnostics", where we
10651 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
10652 ///
10653 /// This class lets you emit either a regular diagnostic, a deferred
10654 /// diagnostic, or no diagnostic at all, according to an argument you pass to
10655 /// its constructor, thus simplifying the process of creating these "maybe
10656 /// deferred" diagnostics.
10657 class DeviceDiagBuilder {
10658 public:
10659 enum Kind {
10660 /// Emit no diagnostics.
10661 K_Nop,
10662 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
10663 K_Immediate,
10664 /// Emit the diagnostic immediately, and, if it's a warning or error, also
10665 /// emit a call stack showing how this function can be reached by an a
10666 /// priori known-emitted function.
10667 K_ImmediateWithCallStack,
10668 /// Create a deferred diagnostic, which is emitted only if the function
10669 /// it's attached to is codegen'ed. Also emit a call stack as with
10670 /// K_ImmediateWithCallStack.
10671 K_Deferred
10672 };
10673
10674 DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
10675 FunctionDecl *Fn, Sema &S);
10676 DeviceDiagBuilder(DeviceDiagBuilder &&D);
10677 DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
10678 ~DeviceDiagBuilder();
10679
10680 /// Convertible to bool: True if we immediately emitted an error, false if
10681 /// we didn't emit an error or we created a deferred error.
10682 ///
10683 /// Example usage:
10684 ///
10685 /// if (DeviceDiagBuilder(...) << foo << bar)
10686 /// return ExprError();
10687 ///
10688 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
10689 /// want to use these instead of creating a DeviceDiagBuilder yourself.
10690 operator bool() const { return ImmediateDiag.hasValue(); }
10691
10692 template <typename T>
10693 friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
10694 const T &Value) {
10695 if (Diag.ImmediateDiag.hasValue())
10696 *Diag.ImmediateDiag << Value;
10697 else if (Diag.PartialDiagId.hasValue())
10698 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
10699 << Value;
10700 return Diag;
10701 }
10702
10703 private:
10704 Sema &S;
10705 SourceLocation Loc;
10706 unsigned DiagID;
10707 FunctionDecl *Fn;
10708 bool ShowCallStack;
10709
10710 // Invariant: At most one of these Optionals has a value.
10711 // FIXME: Switch these to a Variant once that exists.
10712 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
10713 llvm::Optional<unsigned> PartialDiagId;
10714 };
10715
10716 /// Indicate that this function (and thus everything it transtively calls)
10717 /// will be codegen'ed, and emit any deferred diagnostics on this function and
10718 /// its (transitive) callees.
10719 void markKnownEmitted(
10720 Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
10721 SourceLocation OrigLoc,
10722 const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
10723
10724 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
10725 /// is "used as device code".
10726 ///
10727 /// - If CurContext is a __host__ function, does not emit any diagnostics.
10728 /// - If CurContext is a __device__ or __global__ function, emits the
10729 /// diagnostics immediately.
10730 /// - If CurContext is a __host__ __device__ function and we are compiling for
10731 /// the device, creates a diagnostic which is emitted if and when we realize
10732 /// that the function will be codegen'ed.
10733 ///
10734 /// Example usage:
10735 ///
10736 /// // Variable-length arrays are not allowed in CUDA device code.
10737 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
10738 /// return ExprError();
10739 /// // Otherwise, continue parsing as normal.
10740 DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
10741
10742 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
10743 /// is "used as host code".
10744 ///
10745 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
10746 DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
10747
10748 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
10749 /// context is "used as device code".
10750 ///
10751 /// - If CurContext is a `declare target` function or it is known that the
10752 /// function is emitted for the device, emits the diagnostics immediately.
10753 /// - If CurContext is a non-`declare target` function and we are compiling
10754 /// for the device, creates a diagnostic which is emitted if and when we
10755 /// realize that the function will be codegen'ed.
10756 ///
10757 /// Example usage:
10758 ///
10759 /// // Variable-length arrays are not allowed in NVPTX device code.
10760 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
10761 /// return ExprError();
10762 /// // Otherwise, continue parsing as normal.
10763 DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
10764
10765 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
10766 /// context is "used as host code".
10767 ///
10768 /// - If CurContext is a `declare target` function or it is known that the
10769 /// function is emitted for the host, emits the diagnostics immediately.
10770 /// - If CurContext is a non-host function, just ignore it.
10771 ///
10772 /// Example usage:
10773 ///
10774 /// // Variable-length arrays are not allowed in NVPTX device code.
10775 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
10776 /// return ExprError();
10777 /// // Otherwise, continue parsing as normal.
10778 DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
10779
10780 DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
10781
10782 enum CUDAFunctionTarget {
10783 CFT_Device,
10784 CFT_Global,
10785 CFT_Host,
10786 CFT_HostDevice,
10787 CFT_InvalidTarget
10788 };
10789
10790 /// Determines whether the given function is a CUDA device/host/kernel/etc.
10791 /// function.
10792 ///
10793 /// Use this rather than examining the function's attributes yourself -- you
10794 /// will get it wrong. Returns CFT_Host if D is null.
10795 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
10796 bool IgnoreImplicitHDAttr = false);
10797 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
10798
10799 /// Gets the CUDA target for the current context.
10800 CUDAFunctionTarget CurrentCUDATarget() {
10801 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
10802 }
10803
10804 // CUDA function call preference. Must be ordered numerically from
10805 // worst to best.
10806 enum CUDAFunctionPreference {
10807 CFP_Never, // Invalid caller/callee combination.
10808 CFP_WrongSide, // Calls from host-device to host or device
10809 // function that do not match current compilation
10810 // mode.
10811 CFP_HostDevice, // Any calls to host/device functions.
10812 CFP_SameSide, // Calls from host-device to host or device
10813 // function matching current compilation mode.
10814 CFP_Native, // host-to-host or device-to-device calls.
10815 };
10816
10817 /// Identifies relative preference of a given Caller/Callee
10818 /// combination, based on their host/device attributes.
10819 /// \param Caller function which needs address of \p Callee.
10820 /// nullptr in case of global context.
10821 /// \param Callee target function
10822 ///
10823 /// \returns preference value for particular Caller/Callee combination.
10824 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
10825 const FunctionDecl *Callee);
10826
10827 /// Determines whether Caller may invoke Callee, based on their CUDA
10828 /// host/device attributes. Returns false if the call is not allowed.
10829 ///
10830 /// Note: Will return true for CFP_WrongSide calls. These may appear in
10831 /// semantically correct CUDA programs, but only if they're never codegen'ed.
10832 bool IsAllowedCUDACall(const FunctionDecl *Caller,
10833 const FunctionDecl *Callee) {
10834 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
10835 }
10836
10837 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
10838 /// depending on FD and the current compilation settings.
10839 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
10840 const LookupResult &Previous);
10841
10842public:
10843 /// Check whether we're allowed to call Callee from the current context.
10844 ///
10845 /// - If the call is never allowed in a semantically-correct program
10846 /// (CFP_Never), emits an error and returns false.
10847 ///
10848 /// - If the call is allowed in semantically-correct programs, but only if
10849 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
10850 /// be emitted if and when the caller is codegen'ed, and returns true.
10851 ///
10852 /// Will only create deferred diagnostics for a given SourceLocation once,
10853 /// so you can safely call this multiple times without generating duplicate
10854 /// deferred errors.
10855 ///
10856 /// - Otherwise, returns true without emitting any diagnostics.
10857 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
10858
10859 /// Set __device__ or __host__ __device__ attributes on the given lambda
10860 /// operator() method.
10861 ///
10862 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
10863 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
10864 /// functions become __host__ __device__ themselves.
10865 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
10866
10867 /// Finds a function in \p Matches with highest calling priority
10868 /// from \p Caller context and erases all functions with lower
10869 /// calling priority.
10870 void EraseUnwantedCUDAMatches(
10871 const FunctionDecl *Caller,
10872 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
10873
10874 /// Given a implicit special member, infer its CUDA target from the
10875 /// calls it needs to make to underlying base/field special members.
10876 /// \param ClassDecl the class for which the member is being created.
10877 /// \param CSM the kind of special member.
10878 /// \param MemberDecl the special member itself.
10879 /// \param ConstRHS true if this is a copy operation with a const object on
10880 /// its RHS.
10881 /// \param Diagnose true if this call should emit diagnostics.
10882 /// \return true if there was an error inferring.
10883 /// The result of this call is implicit CUDA target attribute(s) attached to
10884 /// the member declaration.
10885 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
10886 CXXSpecialMember CSM,
10887 CXXMethodDecl *MemberDecl,
10888 bool ConstRHS,
10889 bool Diagnose);
10890
10891 /// \return true if \p CD can be considered empty according to CUDA
10892 /// (E.2.3.1 in CUDA 7.5 Programming guide).
10893 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
10894 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
10895
10896 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
10897 // case of error emits appropriate diagnostic and invalidates \p Var.
10898 //
10899 // \details CUDA allows only empty constructors as initializers for global
10900 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
10901 // __shared__ variables whether they are local or not (they all are implicitly
10902 // static in CUDA). One exception is that CUDA allows constant initializers
10903 // for __constant__ and __device__ variables.
10904 void checkAllowedCUDAInitializer(VarDecl *VD);
10905
10906 /// Check whether NewFD is a valid overload for CUDA. Emits
10907 /// diagnostics and invalidates NewFD if not.
10908 void checkCUDATargetOverload(FunctionDecl *NewFD,
10909 const LookupResult &Previous);
10910 /// Copies target attributes from the template TD to the function FD.
10911 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
10912
10913 /// Returns the name of the launch configuration function. This is the name
10914 /// of the function that will be called to configure kernel call, with the
10915 /// parameters specified via <<<>>>.
10916 std::string getCudaConfigureFuncName() const;
10917
10918 /// \name Code completion
10919 //@{
10920 /// Describes the context in which code completion occurs.
10921 enum ParserCompletionContext {
10922 /// Code completion occurs at top-level or namespace context.
10923 PCC_Namespace,
10924 /// Code completion occurs within a class, struct, or union.
10925 PCC_Class,
10926 /// Code completion occurs within an Objective-C interface, protocol,
10927 /// or category.
10928 PCC_ObjCInterface,
10929 /// Code completion occurs within an Objective-C implementation or
10930 /// category implementation
10931 PCC_ObjCImplementation,
10932 /// Code completion occurs within the list of instance variables
10933 /// in an Objective-C interface, protocol, category, or implementation.
10934 PCC_ObjCInstanceVariableList,
10935 /// Code completion occurs following one or more template
10936 /// headers.
10937 PCC_Template,
10938 /// Code completion occurs following one or more template
10939 /// headers within a class.
10940 PCC_MemberTemplate,
10941 /// Code completion occurs within an expression.
10942 PCC_Expression,
10943 /// Code completion occurs within a statement, which may
10944 /// also be an expression or a declaration.
10945 PCC_Statement,
10946 /// Code completion occurs at the beginning of the
10947 /// initialization statement (or expression) in a for loop.
10948 PCC_ForInit,
10949 /// Code completion occurs within the condition of an if,
10950 /// while, switch, or for statement.
10951 PCC_Condition,
10952 /// Code completion occurs within the body of a function on a
10953 /// recovery path, where we do not have a specific handle on our position
10954 /// in the grammar.
10955 PCC_RecoveryInFunction,
10956 /// Code completion occurs where only a type is permitted.
10957 PCC_Type,
10958 /// Code completion occurs in a parenthesized expression, which
10959 /// might also be a type cast.
10960 PCC_ParenthesizedExpression,
10961 /// Code completion occurs within a sequence of declaration
10962 /// specifiers within a function, method, or block.
10963 PCC_LocalDeclarationSpecifiers
10964 };
10965
10966 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10967 void CodeCompleteOrdinaryName(Scope *S,
10968 ParserCompletionContext CompletionContext);
10969 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10970 bool AllowNonIdentifiers,
10971 bool AllowNestedNameSpecifiers);
10972
10973 struct CodeCompleteExpressionData;
10974 void CodeCompleteExpression(Scope *S,
10975 const CodeCompleteExpressionData &Data);
10976 void CodeCompleteExpression(Scope *S, QualType PreferredType,
10977 bool IsParenthesized = false);
10978 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
10979 SourceLocation OpLoc, bool IsArrow,
10980 bool IsBaseExprStatement,
10981 QualType PreferredType);
10982 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
10983 QualType PreferredType);
10984 void CodeCompleteTag(Scope *S, unsigned TagSpec);
10985 void CodeCompleteTypeQualifiers(DeclSpec &DS);
10986 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10987 const VirtSpecifiers *VS = nullptr);
10988 void CodeCompleteBracketDeclarator(Scope *S);
10989 void CodeCompleteCase(Scope *S);
10990 /// Reports signatures for a call to CodeCompleteConsumer and returns the
10991 /// preferred type for the current argument. Returned type can be null.
10992 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
10993 SourceLocation OpenParLoc);
10994 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
10995 SourceLocation Loc,
10996 ArrayRef<Expr *> Args,
10997 SourceLocation OpenParLoc);
10998 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
10999 CXXScopeSpec SS,
11000 ParsedType TemplateTypeTy,
11001 ArrayRef<Expr *> ArgExprs,
11002 IdentifierInfo *II,
11003 SourceLocation OpenParLoc);
11004 void CodeCompleteInitializer(Scope *S, Decl *D);
11005 void CodeCompleteAfterIf(Scope *S);
11006
11007 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
11008 QualType BaseType, QualType PreferredType);
11009 void CodeCompleteUsing(Scope *S);
11010 void CodeCompleteUsingDirective(Scope *S);
11011 void CodeCompleteNamespaceDecl(Scope *S);
11012 void CodeCompleteNamespaceAliasDecl(Scope *S);
11013 void CodeCompleteOperatorName(Scope *S);
11014 void CodeCompleteConstructorInitializer(
11015 Decl *Constructor,
11016 ArrayRef<CXXCtorInitializer *> Initializers);
11017
11018 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
11019 bool AfterAmpersand);
11020
11021 void CodeCompleteObjCAtDirective(Scope *S);
11022 void CodeCompleteObjCAtVisibility(Scope *S);
11023 void CodeCompleteObjCAtStatement(Scope *S);
11024 void CodeCompleteObjCAtExpression(Scope *S);
11025 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
11026 void CodeCompleteObjCPropertyGetter(Scope *S);
11027 void CodeCompleteObjCPropertySetter(Scope *S);
11028 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
11029 bool IsParameter);
11030 void CodeCompleteObjCMessageReceiver(Scope *S);
11031 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
11032 ArrayRef<IdentifierInfo *> SelIdents,
11033 bool AtArgumentExpression);
11034 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
11035 ArrayRef<IdentifierInfo *> SelIdents,
11036 bool AtArgumentExpression,
11037 bool IsSuper = false);
11038 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
11039 ArrayRef<IdentifierInfo *> SelIdents,
11040 bool AtArgumentExpression,
11041 ObjCInterfaceDecl *Super = nullptr);
11042 void CodeCompleteObjCForCollection(Scope *S,
11043 DeclGroupPtrTy IterationVar);
11044 void CodeCompleteObjCSelector(Scope *S,
11045 ArrayRef<IdentifierInfo *> SelIdents);
11046 void CodeCompleteObjCProtocolReferences(
11047 ArrayRef<IdentifierLocPair> Protocols);
11048 void CodeCompleteObjCProtocolDecl(Scope *S);
11049 void CodeCompleteObjCInterfaceDecl(Scope *S);
11050 void CodeCompleteObjCSuperclass(Scope *S,
11051 IdentifierInfo *ClassName,
11052 SourceLocation ClassNameLoc);
11053 void CodeCompleteObjCImplementationDecl(Scope *S);
11054 void CodeCompleteObjCInterfaceCategory(Scope *S,
11055 IdentifierInfo *ClassName,
11056 SourceLocation ClassNameLoc);
11057 void CodeCompleteObjCImplementationCategory(Scope *S,
11058 IdentifierInfo *ClassName,
11059 SourceLocation ClassNameLoc);
11060 void CodeCompleteObjCPropertyDefinition(Scope *S);
11061 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
11062 IdentifierInfo *PropertyName);
11063 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
11064 ParsedType ReturnType);
11065 void CodeCompleteObjCMethodDeclSelector(Scope *S,
11066 bool IsInstanceMethod,
11067 bool AtParameterName,
11068 ParsedType ReturnType,
11069 ArrayRef<IdentifierInfo *> SelIdents);
11070 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
11071 SourceLocation ClassNameLoc,
11072 bool IsBaseExprStatement);
11073 void CodeCompletePreprocessorDirective(bool InConditional);
11074 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
11075 void CodeCompletePreprocessorMacroName(bool IsDefinition);
11076 void CodeCompletePreprocessorExpression();
11077 void CodeCompletePreprocessorMacroArgument(Scope *S,
11078 IdentifierInfo *Macro,
11079 MacroInfo *MacroInfo,
11080 unsigned Argument);
11081 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
11082 void CodeCompleteNaturalLanguage();
11083 void CodeCompleteAvailabilityPlatformName();
11084 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
11085 CodeCompletionTUInfo &CCTUInfo,
11086 SmallVectorImpl<CodeCompletionResult> &Results);
11087 //@}
11088
11089 //===--------------------------------------------------------------------===//
11090 // Extra semantic analysis beyond the C type system
11091
11092public:
11093 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
11094 unsigned ByteNo) const;
11095
11096private:
11097 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11098 const ArraySubscriptExpr *ASE=nullptr,
11099 bool AllowOnePastEnd=true, bool IndexNegated=false);
11100 void CheckArrayAccess(const Expr *E);
11101 // Used to grab the relevant information from a FormatAttr and a
11102 // FunctionDeclaration.
11103 struct FormatStringInfo {
11104 unsigned FormatIdx;
11105 unsigned FirstDataArg;
11106 bool HasVAListArg;
11107 };
11108
11109 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
11110 FormatStringInfo *FSI);
11111 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
11112 const FunctionProtoType *Proto);
11113 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
11114 ArrayRef<const Expr *> Args);
11115 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
11116 const FunctionProtoType *Proto);
11117 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
11118 void CheckConstructorCall(FunctionDecl *FDecl,
11119 ArrayRef<const Expr *> Args,
11120 const FunctionProtoType *Proto,
11121 SourceLocation Loc);
11122
11123 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
11124 const Expr *ThisArg, ArrayRef<const Expr *> Args,
11125 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
11126 VariadicCallType CallType);
11127
11128 bool CheckObjCString(Expr *Arg);
11129 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
11130
11131 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
11132 unsigned BuiltinID, CallExpr *TheCall);
11133 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
11134
11135 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
11136 unsigned MaxWidth);
11137 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11138 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11139
11140 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11141 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11142 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11143 bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
11144 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
11145 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11146 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11147 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
11148 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
11149 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11150 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11151
11152 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
11153 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
11154 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
11155 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
11156 bool SemaBuiltinVSX(CallExpr *TheCall);
11157 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
11158
11159public:
11160 // Used by C++ template instantiation.
11161 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
11162 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
11163 SourceLocation BuiltinLoc,
11164 SourceLocation RParenLoc);
11165
11166private:
11167 bool SemaBuiltinPrefetch(CallExpr *TheCall);
11168 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
11169 bool SemaBuiltinAssume(CallExpr *TheCall);
11170 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
11171 bool SemaBuiltinLongjmp(CallExpr *TheCall);
11172 bool SemaBuiltinSetjmp(CallExpr *TheCall);
11173 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
11174 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
11175 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
11176 AtomicExpr::AtomicOp Op);
11177 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
11178 bool IsDelete);
11179 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
11180 llvm::APSInt &Result);
11181 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
11182 int High, bool RangeIsError = true);
11183 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
11184 unsigned Multiple);
11185 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
11186 int ArgNum, unsigned ExpectedFieldNum,
11187 bool AllowName);
11188 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
11189public:
11190 enum FormatStringType {
11191 FST_Scanf,
11192 FST_Printf,
11193 FST_NSString,
11194 FST_Strftime,
11195 FST_Strfmon,
11196 FST_Kprintf,
11197 FST_FreeBSDKPrintf,
11198 FST_OSTrace,
11199 FST_OSLog,
11200 FST_Unknown
11201 };
11202 static FormatStringType GetFormatStringType(const FormatAttr *Format);
11203
11204 bool FormatStringHasSArg(const StringLiteral *FExpr);
11205
11206 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
11207
11208private:
11209 bool CheckFormatArguments(const FormatAttr *Format,
11210 ArrayRef<const Expr *> Args,
11211 bool IsCXXMember,
11212 VariadicCallType CallType,
11213 SourceLocation Loc, SourceRange Range,
11214 llvm::SmallBitVector &CheckedVarArgs);
11215 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
11216 bool HasVAListArg, unsigned format_idx,
11217 unsigned firstDataArg, FormatStringType Type,
11218 VariadicCallType CallType,
11219 SourceLocation Loc, SourceRange range,
11220 llvm::SmallBitVector &CheckedVarArgs);
11221
11222 void CheckAbsoluteValueFunction(const CallExpr *Call,
11223 const FunctionDecl *FDecl);
11224
11225 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
11226
11227 void CheckMemaccessArguments(const CallExpr *Call,
11228 unsigned BId,
11229 IdentifierInfo *FnName);
11230
11231 void CheckStrlcpycatArguments(const CallExpr *Call,
11232 IdentifierInfo *FnName);
11233
11234 void CheckStrncatArguments(const CallExpr *Call,
11235 IdentifierInfo *FnName);
11236
11237 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11238 SourceLocation ReturnLoc,
11239 bool isObjCMethod = false,
11240 const AttrVec *Attrs = nullptr,
11241 const FunctionDecl *FD = nullptr);
11242
11243public:
11244 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
11245
11246private:
11247 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
11248 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
11249 void CheckForIntOverflow(Expr *E);
11250 void CheckUnsequencedOperations(Expr *E);
11251
11252 /// Perform semantic checks on a completed expression. This will either
11253 /// be a full-expression or a default argument expression.
11254 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
11255 bool IsConstexpr = false);
11256
11257 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
11258 Expr *Init);
11259
11260 /// Check if there is a field shadowing.
11261 void CheckShadowInheritedFields(const SourceLocation &Loc,
11262 DeclarationName FieldName,
11263 const CXXRecordDecl *RD,
11264 bool DeclIsField = true);
11265
11266 /// Check if the given expression contains 'break' or 'continue'
11267 /// statement that produces control flow different from GCC.
11268 void CheckBreakContinueBinding(Expr *E);
11269
11270 /// Check whether receiver is mutable ObjC container which
11271 /// attempts to add itself into the container
11272 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
11273
11274 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
11275 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
11276 bool DeleteWasArrayForm);
11277public:
11278 /// Register a magic integral constant to be used as a type tag.
11279 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11280 uint64_t MagicValue, QualType Type,
11281 bool LayoutCompatible, bool MustBeNull);
11282
11283 struct TypeTagData {
11284 TypeTagData() {}
11285
11286 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
11287 Type(Type), LayoutCompatible(LayoutCompatible),
11288 MustBeNull(MustBeNull)
11289 {}
11290
11291 QualType Type;
11292
11293 /// If true, \c Type should be compared with other expression's types for
11294 /// layout-compatibility.
11295 unsigned LayoutCompatible : 1;
11296 unsigned MustBeNull : 1;
11297 };
11298
11299 /// A pair of ArgumentKind identifier and magic value. This uniquely
11300 /// identifies the magic value.
11301 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
11302
11303private:
11304 /// A map from magic value to type information.
11305 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
11306 TypeTagForDatatypeMagicValues;
11307
11308 /// Peform checks on a call of a function with argument_with_type_tag
11309 /// or pointer_with_type_tag attributes.
11310 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11311 const ArrayRef<const Expr *> ExprArgs,
11312 SourceLocation CallSiteLoc);
11313
11314 /// Check if we are taking the address of a packed field
11315 /// as this may be a problem if the pointer value is dereferenced.
11316 void CheckAddressOfPackedMember(Expr *rhs);
11317
11318 /// The parser's current scope.
11319 ///
11320 /// The parser maintains this state here.
11321 Scope *CurScope;
11322
11323 mutable IdentifierInfo *Ident_super;
11324 mutable IdentifierInfo *Ident___float128;
11325
11326 /// Nullability type specifiers.
11327 IdentifierInfo *Ident__Nonnull = nullptr;
11328 IdentifierInfo *Ident__Nullable = nullptr;
11329 IdentifierInfo *Ident__Null_unspecified = nullptr;
11330
11331 IdentifierInfo *Ident_NSError = nullptr;
11332
11333 /// The handler for the FileChanged preprocessor events.
11334 ///
11335 /// Used for diagnostics that implement custom semantic analysis for #include
11336 /// directives, like -Wpragma-pack.
11337 sema::SemaPPCallbacks *SemaPPCallbackHandler;
11338
11339protected:
11340 friend class Parser;
11341 friend class InitializationSequence;
11342 friend class ASTReader;
11343 friend class ASTDeclReader;
11344 friend class ASTWriter;
11345
11346public:
11347 /// Retrieve the keyword associated
11348 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
11349
11350 /// The struct behind the CFErrorRef pointer.
11351 RecordDecl *CFError = nullptr;
11352
11353 /// Retrieve the identifier "NSError".
11354 IdentifierInfo *getNSErrorIdent();
11355
11356 /// Retrieve the parser's current scope.
11357 ///
11358 /// This routine must only be used when it is certain that semantic analysis
11359 /// and the parser are in precisely the same context, which is not the case
11360 /// when, e.g., we are performing any kind of template instantiation.
11361 /// Therefore, the only safe places to use this scope are in the parser
11362 /// itself and in routines directly invoked from the parser and *never* from
11363 /// template substitution or instantiation.
11364 Scope *getCurScope() const { return CurScope; }
11365
11366 void incrementMSManglingNumber() const {
11367 return CurScope->incrementMSManglingNumber();
11368 }
11369
11370 IdentifierInfo *getSuperIdentifier() const;
11371 IdentifierInfo *getFloat128Identifier() const;
11372
11373 Decl *getObjCDeclContext() const;
11374
11375 DeclContext *getCurLexicalContext() const {
11376 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
11377 }
11378
11379 const DeclContext *getCurObjCLexicalContext() const {
11380 const DeclContext *DC = getCurLexicalContext();
11381 // A category implicitly has the attribute of the interface.
11382 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
11383 DC = CatD->getClassInterface();
11384 return DC;
11385 }
11386
11387 /// To be used for checking whether the arguments being passed to
11388 /// function exceeds the number of parameters expected for it.
11389 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
11390 bool PartialOverloading = false) {
11391 // We check whether we're just after a comma in code-completion.
11392 if (NumArgs > 0 && PartialOverloading)
5
Assuming 'NumArgs' is > 0
6
Assuming 'PartialOverloading' is false
7
Taking false branch
11393 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
11394 return NumArgs > NumParams;
8
Assuming 'NumArgs' is > 'NumParams'
9
Returning the value 1, which participates in a condition later
11395 }
11396
11397 // Emitting members of dllexported classes is delayed until the class
11398 // (including field initializers) is fully parsed.
11399 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
11400 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
11401
11402private:
11403 class SavePendingParsedClassStateRAII {
11404 public:
11405 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
11406
11407 ~SavePendingParsedClassStateRAII() {
11408 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 11409, __PRETTY_FUNCTION__))
11409 "there shouldn't be any pending delayed exception spec checks")((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 11409, __PRETTY_FUNCTION__))
;
11410 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 11411, __PRETTY_FUNCTION__))
11411 "there shouldn't be any pending delayed exception spec checks")((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 11411, __PRETTY_FUNCTION__))
;
11412 assert(S.DelayedDllExportClasses.empty() &&((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 11413, __PRETTY_FUNCTION__))
11413 "there shouldn't be any pending delayed DLL export classes")((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h"
, 11413, __PRETTY_FUNCTION__))
;
11414 swapSavedState();
11415 }
11416
11417 private:
11418 Sema &S;
11419 decltype(DelayedOverridingExceptionSpecChecks)
11420 SavedOverridingExceptionSpecChecks;
11421 decltype(DelayedEquivalentExceptionSpecChecks)
11422 SavedEquivalentExceptionSpecChecks;
11423 decltype(DelayedDllExportClasses) SavedDllExportClasses;
11424
11425 void swapSavedState() {
11426 SavedOverridingExceptionSpecChecks.swap(
11427 S.DelayedOverridingExceptionSpecChecks);
11428 SavedEquivalentExceptionSpecChecks.swap(
11429 S.DelayedEquivalentExceptionSpecChecks);
11430 SavedDllExportClasses.swap(S.DelayedDllExportClasses);
11431 }
11432 };
11433
11434 /// Helper class that collects misaligned member designations and
11435 /// their location info for delayed diagnostics.
11436 struct MisalignedMember {
11437 Expr *E;
11438 RecordDecl *RD;
11439 ValueDecl *MD;
11440 CharUnits Alignment;
11441
11442 MisalignedMember() : E(), RD(), MD(), Alignment() {}
11443 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
11444 CharUnits Alignment)
11445 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
11446 explicit MisalignedMember(Expr *E)
11447 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
11448
11449 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
11450 };
11451 /// Small set of gathered accesses to potentially misaligned members
11452 /// due to the packed attribute.
11453 SmallVector<MisalignedMember, 4> MisalignedMembers;
11454
11455 /// Adds an expression to the set of gathered misaligned members.
11456 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11457 CharUnits Alignment);
11458
11459public:
11460 /// Diagnoses the current set of gathered accesses. This typically
11461 /// happens at full expression level. The set is cleared after emitting the
11462 /// diagnostics.
11463 void DiagnoseMisalignedMembers();
11464
11465 /// This function checks if the expression is in the sef of potentially
11466 /// misaligned members and it is converted to some pointer type T with lower
11467 /// or equal alignment requirements. If so it removes it. This is used when
11468 /// we do not want to diagnose such misaligned access (e.g. in conversions to
11469 /// void*).
11470 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
11471
11472 /// This function calls Action when it determines that E designates a
11473 /// misaligned member due to the packed attribute. This is used to emit
11474 /// local diagnostics like in reference binding.
11475 void RefersToMemberWithReducedAlignment(
11476 Expr *E,
11477 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11478 Action);
11479
11480 /// Describes the reason a calling convention specification was ignored, used
11481 /// for diagnostics.
11482 enum class CallingConventionIgnoredReason {
11483 ForThisTarget = 0,
11484 VariadicFunction,
11485 ConstructorDestructor,
11486 BuiltinFunction
11487 };
11488};
11489
11490/// RAII object that enters a new expression evaluation context.
11491class EnterExpressionEvaluationContext {
11492 Sema &Actions;
11493 bool Entered = true;
11494
11495public:
11496 EnterExpressionEvaluationContext(
11497 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
11498 Decl *LambdaContextDecl = nullptr,
11499 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
11500 Sema::ExpressionEvaluationContextRecord::EK_Other,
11501 bool ShouldEnter = true)
11502 : Actions(Actions), Entered(ShouldEnter) {
11503 if (Entered)
11504 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
11505 ExprContext);
11506 }
11507 EnterExpressionEvaluationContext(
11508 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
11509 Sema::ReuseLambdaContextDecl_t,
11510 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
11511 Sema::ExpressionEvaluationContextRecord::EK_Other)
11512 : Actions(Actions) {
11513 Actions.PushExpressionEvaluationContext(
11514 NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
11515 }
11516
11517 enum InitListTag { InitList };
11518 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
11519 bool ShouldEnter = true)
11520 : Actions(Actions), Entered(false) {
11521 // In C++11 onwards, narrowing checks are performed on the contents of
11522 // braced-init-lists, even when they occur within unevaluated operands.
11523 // Therefore we still need to instantiate constexpr functions used in such
11524 // a context.
11525 if (ShouldEnter && Actions.isUnevaluatedContext() &&
11526 Actions.getLangOpts().CPlusPlus11) {
11527 Actions.PushExpressionEvaluationContext(
11528 Sema::ExpressionEvaluationContext::UnevaluatedList);
11529 Entered = true;
11530 }
11531 }
11532
11533 ~EnterExpressionEvaluationContext() {
11534 if (Entered)
11535 Actions.PopExpressionEvaluationContext();
11536 }
11537};
11538
11539DeductionFailureInfo
11540MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
11541 sema::TemplateDeductionInfo &Info);
11542
11543/// Contains a late templated function.
11544/// Will be parsed at the end of the translation unit, used by Sema & Parser.
11545struct LateParsedTemplate {
11546 CachedTokens Toks;
11547 /// The template function declaration to be late parsed.
11548 Decl *D;
11549};
11550} // end namespace clang
11551
11552namespace llvm {
11553// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
11554// SourceLocation.
11555template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
11556 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
11557 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
11558
11559 static FunctionDeclAndLoc getEmptyKey() {
11560 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
11561 }
11562
11563 static FunctionDeclAndLoc getTombstoneKey() {
11564 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
11565 }
11566
11567 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
11568 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
11569 FDL.Loc.getRawEncoding());
11570 }
11571
11572 static bool isEqual(const FunctionDeclAndLoc &LHS,
11573 const FunctionDeclAndLoc &RHS) {
11574 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
11575 }
11576};
11577} // namespace llvm
11578
11579#endif