Bug Summary

File:clang/lib/Sema/SemaTemplateDeduction.cpp
Warning:line 3732, column 31
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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -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-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaTemplateDeduction.cpp

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- 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/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/DependencyFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class Type;
65
66enum {
67 TypeAlignmentInBits = 4,
68 TypeAlignment = 1 << TypeAlignmentInBits
69};
70
71namespace serialization {
72 template <class T> class AbstractTypeReader;
73 template <class T> class AbstractTypeWriter;
74}
75
76} // namespace clang
77
78namespace llvm {
79
80 template <typename T>
81 struct PointerLikeTypeTraits;
82 template<>
83 struct PointerLikeTypeTraits< ::clang::Type*> {
84 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
85
86 static inline ::clang::Type *getFromVoidPointer(void *P) {
87 return static_cast< ::clang::Type*>(P);
88 }
89
90 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
91 };
92
93 template<>
94 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
95 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
96
97 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
98 return static_cast< ::clang::ExtQuals*>(P);
99 }
100
101 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
102 };
103
104} // namespace llvm
105
106namespace clang {
107
108class ASTContext;
109template <typename> class CanQual;
110class CXXRecordDecl;
111class DeclContext;
112class EnumDecl;
113class Expr;
114class ExtQualsTypeCommonBase;
115class FunctionDecl;
116class IdentifierInfo;
117class NamedDecl;
118class ObjCInterfaceDecl;
119class ObjCProtocolDecl;
120class ObjCTypeParamDecl;
121struct PrintingPolicy;
122class RecordDecl;
123class Stmt;
124class TagDecl;
125class TemplateArgument;
126class TemplateArgumentListInfo;
127class TemplateArgumentLoc;
128class TemplateTypeParmDecl;
129class TypedefNameDecl;
130class UnresolvedUsingTypenameDecl;
131
132using CanQualType = CanQual<Type>;
133
134// Provide forward declarations for all of the *Type classes.
135#define TYPE(Class, Base) class Class##Type;
136#include "clang/AST/TypeNodes.inc"
137
138/// The collection of all-type qualifiers we support.
139/// Clang supports five independent qualifiers:
140/// * C99: const, volatile, and restrict
141/// * MS: __unaligned
142/// * Embedded C (TR18037): address spaces
143/// * Objective C: the GC attributes (none, weak, or strong)
144class Qualifiers {
145public:
146 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
147 Const = 0x1,
148 Restrict = 0x2,
149 Volatile = 0x4,
150 CVRMask = Const | Volatile | Restrict
151 };
152
153 enum GC {
154 GCNone = 0,
155 Weak,
156 Strong
157 };
158
159 enum ObjCLifetime {
160 /// There is no lifetime qualification on this type.
161 OCL_None,
162
163 /// This object can be modified without requiring retains or
164 /// releases.
165 OCL_ExplicitNone,
166
167 /// Assigning into this object requires the old value to be
168 /// released and the new value to be retained. The timing of the
169 /// release of the old value is inexact: it may be moved to
170 /// immediately after the last known point where the value is
171 /// live.
172 OCL_Strong,
173
174 /// Reading or writing from this object requires a barrier call.
175 OCL_Weak,
176
177 /// Assigning into this object requires a lifetime extension.
178 OCL_Autoreleasing
179 };
180
181 enum {
182 /// The maximum supported address space number.
183 /// 23 bits should be enough for anyone.
184 MaxAddressSpace = 0x7fffffu,
185
186 /// The width of the "fast" qualifier mask.
187 FastWidth = 3,
188
189 /// The fast qualifier mask.
190 FastMask = (1 << FastWidth) - 1
191 };
192
193 /// Returns the common set of qualifiers while removing them from
194 /// the given sets.
195 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
196 // If both are only CVR-qualified, bit operations are sufficient.
197 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
198 Qualifiers Q;
199 Q.Mask = L.Mask & R.Mask;
200 L.Mask &= ~Q.Mask;
201 R.Mask &= ~Q.Mask;
202 return Q;
203 }
204
205 Qualifiers Q;
206 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
207 Q.addCVRQualifiers(CommonCRV);
208 L.removeCVRQualifiers(CommonCRV);
209 R.removeCVRQualifiers(CommonCRV);
210
211 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
212 Q.setObjCGCAttr(L.getObjCGCAttr());
213 L.removeObjCGCAttr();
214 R.removeObjCGCAttr();
215 }
216
217 if (L.getObjCLifetime() == R.getObjCLifetime()) {
218 Q.setObjCLifetime(L.getObjCLifetime());
219 L.removeObjCLifetime();
220 R.removeObjCLifetime();
221 }
222
223 if (L.getAddressSpace() == R.getAddressSpace()) {
224 Q.setAddressSpace(L.getAddressSpace());
225 L.removeAddressSpace();
226 R.removeAddressSpace();
227 }
228 return Q;
229 }
230
231 static Qualifiers fromFastMask(unsigned Mask) {
232 Qualifiers Qs;
233 Qs.addFastQualifiers(Mask);
234 return Qs;
235 }
236
237 static Qualifiers fromCVRMask(unsigned CVR) {
238 Qualifiers Qs;
239 Qs.addCVRQualifiers(CVR);
240 return Qs;
241 }
242
243 static Qualifiers fromCVRUMask(unsigned CVRU) {
244 Qualifiers Qs;
245 Qs.addCVRUQualifiers(CVRU);
246 return Qs;
247 }
248
249 // Deserialize qualifiers from an opaque representation.
250 static Qualifiers fromOpaqueValue(unsigned opaque) {
251 Qualifiers Qs;
252 Qs.Mask = opaque;
253 return Qs;
254 }
255
256 // Serialize these qualifiers into an opaque representation.
257 unsigned getAsOpaqueValue() const {
258 return Mask;
259 }
260
261 bool hasConst() const { return Mask & Const; }
262 bool hasOnlyConst() const { return Mask == Const; }
263 void removeConst() { Mask &= ~Const; }
264 void addConst() { Mask |= Const; }
265
266 bool hasVolatile() const { return Mask & Volatile; }
267 bool hasOnlyVolatile() const { return Mask == Volatile; }
268 void removeVolatile() { Mask &= ~Volatile; }
269 void addVolatile() { Mask |= Volatile; }
270
271 bool hasRestrict() const { return Mask & Restrict; }
272 bool hasOnlyRestrict() const { return Mask == Restrict; }
273 void removeRestrict() { Mask &= ~Restrict; }
274 void addRestrict() { Mask |= Restrict; }
275
276 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
277 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
278 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
279
280 void setCVRQualifiers(unsigned mask) {
281 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 281, __PRETTY_FUNCTION__))
;
282 Mask = (Mask & ~CVRMask) | mask;
283 }
284 void removeCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask &= ~mask;
287 }
288 void removeCVRQualifiers() {
289 removeCVRQualifiers(CVRMask);
290 }
291 void addCVRQualifiers(unsigned mask) {
292 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 292, __PRETTY_FUNCTION__))
;
293 Mask |= mask;
294 }
295 void addCVRUQualifiers(unsigned mask) {
296 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 296, __PRETTY_FUNCTION__))
;
297 Mask |= mask;
298 }
299
300 bool hasUnaligned() const { return Mask & UMask; }
301 void setUnaligned(bool flag) {
302 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
303 }
304 void removeUnaligned() { Mask &= ~UMask; }
305 void addUnaligned() { Mask |= UMask; }
306
307 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
308 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
309 void setObjCGCAttr(GC type) {
310 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
311 }
312 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
313 void addObjCGCAttr(GC type) {
314 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 314, __PRETTY_FUNCTION__))
;
315 setObjCGCAttr(type);
316 }
317 Qualifiers withoutObjCGCAttr() const {
318 Qualifiers qs = *this;
319 qs.removeObjCGCAttr();
320 return qs;
321 }
322 Qualifiers withoutObjCLifetime() const {
323 Qualifiers qs = *this;
324 qs.removeObjCLifetime();
325 return qs;
326 }
327 Qualifiers withoutAddressSpace() const {
328 Qualifiers qs = *this;
329 qs.removeAddressSpace();
330 return qs;
331 }
332
333 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
334 ObjCLifetime getObjCLifetime() const {
335 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
336 }
337 void setObjCLifetime(ObjCLifetime type) {
338 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
339 }
340 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
341 void addObjCLifetime(ObjCLifetime type) {
342 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 342, __PRETTY_FUNCTION__))
;
343 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 343, __PRETTY_FUNCTION__))
;
344 Mask |= (type << LifetimeShift);
345 }
346
347 /// True if the lifetime is neither None or ExplicitNone.
348 bool hasNonTrivialObjCLifetime() const {
349 ObjCLifetime lifetime = getObjCLifetime();
350 return (lifetime > OCL_ExplicitNone);
351 }
352
353 /// True if the lifetime is either strong or weak.
354 bool hasStrongOrWeakObjCLifetime() const {
355 ObjCLifetime lifetime = getObjCLifetime();
356 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
357 }
358
359 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
360 LangAS getAddressSpace() const {
361 return static_cast<LangAS>(Mask >> AddressSpaceShift);
362 }
363 bool hasTargetSpecificAddressSpace() const {
364 return isTargetAddressSpace(getAddressSpace());
365 }
366 /// Get the address space attribute value to be printed by diagnostics.
367 unsigned getAddressSpaceAttributePrintValue() const {
368 auto Addr = getAddressSpace();
369 // This function is not supposed to be used with language specific
370 // address spaces. If that happens, the diagnostic message should consider
371 // printing the QualType instead of the address space value.
372 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 372, __PRETTY_FUNCTION__))
;
373 if (Addr != LangAS::Default)
374 return toTargetAddressSpace(Addr);
375 // TODO: The diagnostic messages where Addr may be 0 should be fixed
376 // since it cannot differentiate the situation where 0 denotes the default
377 // address space or user specified __attribute__((address_space(0))).
378 return 0;
379 }
380 void setAddressSpace(LangAS space) {
381 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 381, __PRETTY_FUNCTION__))
;
382 Mask = (Mask & ~AddressSpaceMask)
383 | (((uint32_t) space) << AddressSpaceShift);
384 }
385 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
386 void addAddressSpace(LangAS space) {
387 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 387, __PRETTY_FUNCTION__))
;
388 setAddressSpace(space);
389 }
390
391 // Fast qualifiers are those that can be allocated directly
392 // on a QualType object.
393 bool hasFastQualifiers() const { return getFastQualifiers(); }
394 unsigned getFastQualifiers() const { return Mask & FastMask; }
395 void setFastQualifiers(unsigned mask) {
396 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 396, __PRETTY_FUNCTION__))
;
397 Mask = (Mask & ~FastMask) | mask;
398 }
399 void removeFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask &= ~mask;
402 }
403 void removeFastQualifiers() {
404 removeFastQualifiers(FastMask);
405 }
406 void addFastQualifiers(unsigned mask) {
407 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 407, __PRETTY_FUNCTION__))
;
408 Mask |= mask;
409 }
410
411 /// Return true if the set contains any qualifiers which require an ExtQuals
412 /// node to be allocated.
413 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
414 Qualifiers getNonFastQualifiers() const {
415 Qualifiers Quals = *this;
416 Quals.setFastQualifiers(0);
417 return Quals;
418 }
419
420 /// Return true if the set contains any qualifiers.
421 bool hasQualifiers() const { return Mask; }
422 bool empty() const { return !Mask; }
423
424 /// Add the qualifiers from the given set to this set.
425 void addQualifiers(Qualifiers Q) {
426 // If the other set doesn't have any non-boolean qualifiers, just
427 // bit-or it in.
428 if (!(Q.Mask & ~CVRMask))
429 Mask |= Q.Mask;
430 else {
431 Mask |= (Q.Mask & CVRMask);
432 if (Q.hasAddressSpace())
433 addAddressSpace(Q.getAddressSpace());
434 if (Q.hasObjCGCAttr())
435 addObjCGCAttr(Q.getObjCGCAttr());
436 if (Q.hasObjCLifetime())
437 addObjCLifetime(Q.getObjCLifetime());
438 }
439 }
440
441 /// Remove the qualifiers from the given set from this set.
442 void removeQualifiers(Qualifiers Q) {
443 // If the other set doesn't have any non-boolean qualifiers, just
444 // bit-and the inverse in.
445 if (!(Q.Mask & ~CVRMask))
446 Mask &= ~Q.Mask;
447 else {
448 Mask &= ~(Q.Mask & CVRMask);
449 if (getObjCGCAttr() == Q.getObjCGCAttr())
450 removeObjCGCAttr();
451 if (getObjCLifetime() == Q.getObjCLifetime())
452 removeObjCLifetime();
453 if (getAddressSpace() == Q.getAddressSpace())
454 removeAddressSpace();
455 }
456 }
457
458 /// Add the qualifiers from the given set to this set, given that
459 /// they don't conflict.
460 void addConsistentQualifiers(Qualifiers qs) {
461 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
462 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
;
463 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
464 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
;
465 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
466 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
;
467 Mask |= qs.Mask;
468 }
469
470 /// Returns true if address space A is equal to or a superset of B.
471 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
472 /// overlapping address spaces.
473 /// CL1.1 or CL1.2:
474 /// every address space is a superset of itself.
475 /// CL2.0 adds:
476 /// __generic is a superset of any address space except for __constant.
477 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
478 // Address spaces must match exactly.
479 return A == B ||
480 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
481 // for __constant can be used as __generic.
482 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
483 // Consider pointer size address spaces to be equivalent to default.
484 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
485 (isPtrSizeAddressSpace(B) || B == LangAS::Default));
486 }
487
488 /// Returns true if the address space in these qualifiers is equal to or
489 /// a superset of the address space in the argument qualifiers.
490 bool isAddressSpaceSupersetOf(Qualifiers other) const {
491 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
492 }
493
494 /// Determines if these qualifiers compatibly include another set.
495 /// Generally this answers the question of whether an object with the other
496 /// qualifiers can be safely used as an object with these qualifiers.
497 bool compatiblyIncludes(Qualifiers other) const {
498 return isAddressSpaceSupersetOf(other) &&
499 // ObjC GC qualifiers can match, be added, or be removed, but can't
500 // be changed.
501 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
502 !other.hasObjCGCAttr()) &&
503 // ObjC lifetime qualifiers must match exactly.
504 getObjCLifetime() == other.getObjCLifetime() &&
505 // CVR qualifiers may subset.
506 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
507 // U qualifier may superset.
508 (!other.hasUnaligned() || hasUnaligned());
509 }
510
511 /// Determines if these qualifiers compatibly include another set of
512 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
513 ///
514 /// One set of Objective-C lifetime qualifiers compatibly includes the other
515 /// if the lifetime qualifiers match, or if both are non-__weak and the
516 /// including set also contains the 'const' qualifier, or both are non-__weak
517 /// and one is None (which can only happen in non-ARC modes).
518 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
519 if (getObjCLifetime() == other.getObjCLifetime())
520 return true;
521
522 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
523 return false;
524
525 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
526 return true;
527
528 return hasConst();
529 }
530
531 /// Determine whether this set of qualifiers is a strict superset of
532 /// another set of qualifiers, not considering qualifier compatibility.
533 bool isStrictSupersetOf(Qualifiers Other) const;
534
535 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
536 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
537
538 explicit operator bool() const { return hasQualifiers(); }
539
540 Qualifiers &operator+=(Qualifiers R) {
541 addQualifiers(R);
542 return *this;
543 }
544
545 // Union two qualifier sets. If an enumerated qualifier appears
546 // in both sets, use the one from the right.
547 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
548 L += R;
549 return L;
550 }
551
552 Qualifiers &operator-=(Qualifiers R) {
553 removeQualifiers(R);
554 return *this;
555 }
556
557 /// Compute the difference between two qualifier sets.
558 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
559 L -= R;
560 return L;
561 }
562
563 std::string getAsString() const;
564 std::string getAsString(const PrintingPolicy &Policy) const;
565
566 static std::string getAddrSpaceAsString(LangAS AS);
567
568 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
569 void print(raw_ostream &OS, const PrintingPolicy &Policy,
570 bool appendSpaceIfNonEmpty = false) const;
571
572 void Profile(llvm::FoldingSetNodeID &ID) const {
573 ID.AddInteger(Mask);
574 }
575
576private:
577 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
578 // |C R V|U|GCAttr|Lifetime|AddressSpace|
579 uint32_t Mask = 0;
580
581 static const uint32_t UMask = 0x8;
582 static const uint32_t UShift = 3;
583 static const uint32_t GCAttrMask = 0x30;
584 static const uint32_t GCAttrShift = 4;
585 static const uint32_t LifetimeMask = 0x1C0;
586 static const uint32_t LifetimeShift = 6;
587 static const uint32_t AddressSpaceMask =
588 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
589 static const uint32_t AddressSpaceShift = 9;
590};
591
592/// A std::pair-like structure for storing a qualified type split
593/// into its local qualifiers and its locally-unqualified type.
594struct SplitQualType {
595 /// The locally-unqualified type.
596 const Type *Ty = nullptr;
597
598 /// The local qualifiers.
599 Qualifiers Quals;
600
601 SplitQualType() = default;
602 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
603
604 SplitQualType getSingleStepDesugaredType() const; // end of this file
605
606 // Make std::tie work.
607 std::pair<const Type *,Qualifiers> asPair() const {
608 return std::pair<const Type *, Qualifiers>(Ty, Quals);
609 }
610
611 friend bool operator==(SplitQualType a, SplitQualType b) {
612 return a.Ty == b.Ty && a.Quals == b.Quals;
613 }
614 friend bool operator!=(SplitQualType a, SplitQualType b) {
615 return a.Ty != b.Ty || a.Quals != b.Quals;
616 }
617};
618
619/// The kind of type we are substituting Objective-C type arguments into.
620///
621/// The kind of substitution affects the replacement of type parameters when
622/// no concrete type information is provided, e.g., when dealing with an
623/// unspecialized type.
624enum class ObjCSubstitutionContext {
625 /// An ordinary type.
626 Ordinary,
627
628 /// The result type of a method or function.
629 Result,
630
631 /// The parameter type of a method or function.
632 Parameter,
633
634 /// The type of a property.
635 Property,
636
637 /// The superclass of a type.
638 Superclass,
639};
640
641/// A (possibly-)qualified type.
642///
643/// For efficiency, we don't store CV-qualified types as nodes on their
644/// own: instead each reference to a type stores the qualifiers. This
645/// greatly reduces the number of nodes we need to allocate for types (for
646/// example we only need one for 'int', 'const int', 'volatile int',
647/// 'const volatile int', etc).
648///
649/// As an added efficiency bonus, instead of making this a pair, we
650/// just store the two bits we care about in the low bits of the
651/// pointer. To handle the packing/unpacking, we make QualType be a
652/// simple wrapper class that acts like a smart pointer. A third bit
653/// indicates whether there are extended qualifiers present, in which
654/// case the pointer points to a special structure.
655class QualType {
656 friend class QualifierCollector;
657
658 // Thankfully, these are efficiently composable.
659 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
660 Qualifiers::FastWidth> Value;
661
662 const ExtQuals *getExtQualsUnsafe() const {
663 return Value.getPointer().get<const ExtQuals*>();
664 }
665
666 const Type *getTypePtrUnsafe() const {
667 return Value.getPointer().get<const Type*>();
668 }
669
670 const ExtQualsTypeCommonBase *getCommonPtr() const {
671 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 671, __PRETTY_FUNCTION__))
;
672 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
673 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
674 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
675 }
676
677public:
678 QualType() = default;
679 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
680 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
681
682 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
683 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
684
685 /// Retrieves a pointer to the underlying (unqualified) type.
686 ///
687 /// This function requires that the type not be NULL. If the type might be
688 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
689 const Type *getTypePtr() const;
690
691 const Type *getTypePtrOrNull() const;
692
693 /// Retrieves a pointer to the name of the base type.
694 const IdentifierInfo *getBaseTypeIdentifier() const;
695
696 /// Divides a QualType into its unqualified type and a set of local
697 /// qualifiers.
698 SplitQualType split() const;
699
700 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
701
702 static QualType getFromOpaquePtr(const void *Ptr) {
703 QualType T;
704 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
705 return T;
706 }
707
708 const Type &operator*() const {
709 return *getTypePtr();
710 }
711
712 const Type *operator->() const {
713 return getTypePtr();
714 }
715
716 bool isCanonical() const;
717 bool isCanonicalAsParam() const;
718
719 /// Return true if this QualType doesn't point to a type yet.
720 bool isNull() const {
721 return Value.getPointer().isNull();
722 }
723
724 /// Determine whether this particular QualType instance has the
725 /// "const" qualifier set, without looking through typedefs that may have
726 /// added "const" at a different level.
727 bool isLocalConstQualified() const {
728 return (getLocalFastQualifiers() & Qualifiers::Const);
729 }
730
731 /// Determine whether this type is const-qualified.
732 bool isConstQualified() const;
733
734 /// Determine whether this particular QualType instance has the
735 /// "restrict" qualifier set, without looking through typedefs that may have
736 /// added "restrict" at a different level.
737 bool isLocalRestrictQualified() const {
738 return (getLocalFastQualifiers() & Qualifiers::Restrict);
739 }
740
741 /// Determine whether this type is restrict-qualified.
742 bool isRestrictQualified() const;
743
744 /// Determine whether this particular QualType instance has the
745 /// "volatile" qualifier set, without looking through typedefs that may have
746 /// added "volatile" at a different level.
747 bool isLocalVolatileQualified() const {
748 return (getLocalFastQualifiers() & Qualifiers::Volatile);
749 }
750
751 /// Determine whether this type is volatile-qualified.
752 bool isVolatileQualified() const;
753
754 /// Determine whether this particular QualType instance has any
755 /// qualifiers, without looking through any typedefs that might add
756 /// qualifiers at a different level.
757 bool hasLocalQualifiers() const {
758 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
759 }
760
761 /// Determine whether this type has any qualifiers.
762 bool hasQualifiers() const;
763
764 /// Determine whether this particular QualType instance has any
765 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
766 /// instance.
767 bool hasLocalNonFastQualifiers() const {
768 return Value.getPointer().is<const ExtQuals*>();
769 }
770
771 /// Retrieve the set of qualifiers local to this particular QualType
772 /// instance, not including any qualifiers acquired through typedefs or
773 /// other sugar.
774 Qualifiers getLocalQualifiers() const;
775
776 /// Retrieve the set of qualifiers applied to this type.
777 Qualifiers getQualifiers() const;
778
779 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
780 /// local to this particular QualType instance, not including any qualifiers
781 /// acquired through typedefs or other sugar.
782 unsigned getLocalCVRQualifiers() const {
783 return getLocalFastQualifiers();
784 }
785
786 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
787 /// applied to this type.
788 unsigned getCVRQualifiers() const;
789
790 bool isConstant(const ASTContext& Ctx) const {
791 return QualType::isConstant(*this, Ctx);
792 }
793
794 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
795 bool isPODType(const ASTContext &Context) const;
796
797 /// Return true if this is a POD type according to the rules of the C++98
798 /// standard, regardless of the current compilation's language.
799 bool isCXX98PODType(const ASTContext &Context) const;
800
801 /// Return true if this is a POD type according to the more relaxed rules
802 /// of the C++11 standard, regardless of the current compilation's language.
803 /// (C++0x [basic.types]p9). Note that, unlike
804 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
805 bool isCXX11PODType(const ASTContext &Context) const;
806
807 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
808 bool isTrivialType(const ASTContext &Context) const;
809
810 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
811 bool isTriviallyCopyableType(const ASTContext &Context) const;
812
813
814 /// Returns true if it is a class and it might be dynamic.
815 bool mayBeDynamicClass() const;
816
817 /// Returns true if it is not a class or if the class might not be dynamic.
818 bool mayBeNotDynamicClass() const;
819
820 // Don't promise in the API that anything besides 'const' can be
821 // easily added.
822
823 /// Add the `const` type qualifier to this QualType.
824 void addConst() {
825 addFastQualifiers(Qualifiers::Const);
826 }
827 QualType withConst() const {
828 return withFastQualifiers(Qualifiers::Const);
829 }
830
831 /// Add the `volatile` type qualifier to this QualType.
832 void addVolatile() {
833 addFastQualifiers(Qualifiers::Volatile);
834 }
835 QualType withVolatile() const {
836 return withFastQualifiers(Qualifiers::Volatile);
837 }
838
839 /// Add the `restrict` qualifier to this QualType.
840 void addRestrict() {
841 addFastQualifiers(Qualifiers::Restrict);
842 }
843 QualType withRestrict() const {
844 return withFastQualifiers(Qualifiers::Restrict);
845 }
846
847 QualType withCVRQualifiers(unsigned CVR) const {
848 return withFastQualifiers(CVR);
849 }
850
851 void addFastQualifiers(unsigned TQs) {
852 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 853, __PRETTY_FUNCTION__))
853 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 853, __PRETTY_FUNCTION__))
;
854 Value.setInt(Value.getInt() | TQs);
855 }
856
857 void removeLocalConst();
858 void removeLocalVolatile();
859 void removeLocalRestrict();
860 void removeLocalCVRQualifiers(unsigned Mask);
861
862 void removeLocalFastQualifiers() { Value.setInt(0); }
863 void removeLocalFastQualifiers(unsigned Mask) {
864 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 864, __PRETTY_FUNCTION__))
;
865 Value.setInt(Value.getInt() & ~Mask);
866 }
867
868 // Creates a type with the given qualifiers in addition to any
869 // qualifiers already on this type.
870 QualType withFastQualifiers(unsigned TQs) const {
871 QualType T = *this;
872 T.addFastQualifiers(TQs);
873 return T;
874 }
875
876 // Creates a type with exactly the given fast qualifiers, removing
877 // any existing fast qualifiers.
878 QualType withExactLocalFastQualifiers(unsigned TQs) const {
879 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
880 }
881
882 // Removes fast qualifiers, but leaves any extended qualifiers in place.
883 QualType withoutLocalFastQualifiers() const {
884 QualType T = *this;
885 T.removeLocalFastQualifiers();
886 return T;
887 }
888
889 QualType getCanonicalType() const;
890
891 /// Return this type with all of the instance-specific qualifiers
892 /// removed, but without removing any qualifiers that may have been applied
893 /// through typedefs.
894 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
895
896 /// Retrieve the unqualified variant of the given type,
897 /// removing as little sugar as possible.
898 ///
899 /// This routine looks through various kinds of sugar to find the
900 /// least-desugared type that is unqualified. For example, given:
901 ///
902 /// \code
903 /// typedef int Integer;
904 /// typedef const Integer CInteger;
905 /// typedef CInteger DifferenceType;
906 /// \endcode
907 ///
908 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
909 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
910 ///
911 /// The resulting type might still be qualified if it's sugar for an array
912 /// type. To strip qualifiers even from within a sugared array type, use
913 /// ASTContext::getUnqualifiedArrayType.
914 inline QualType getUnqualifiedType() const;
915
916 /// Retrieve the unqualified variant of the given type, removing as little
917 /// sugar as possible.
918 ///
919 /// Like getUnqualifiedType(), but also returns the set of
920 /// qualifiers that were built up.
921 ///
922 /// The resulting type might still be qualified if it's sugar for an array
923 /// type. To strip qualifiers even from within a sugared array type, use
924 /// ASTContext::getUnqualifiedArrayType.
925 inline SplitQualType getSplitUnqualifiedType() const;
926
927 /// Determine whether this type is more qualified than the other
928 /// given type, requiring exact equality for non-CVR qualifiers.
929 bool isMoreQualifiedThan(QualType Other) const;
930
931 /// Determine whether this type is at least as qualified as the other
932 /// given type, requiring exact equality for non-CVR qualifiers.
933 bool isAtLeastAsQualifiedAs(QualType Other) const;
934
935 QualType getNonReferenceType() const;
936
937 /// Determine the type of a (typically non-lvalue) expression with the
938 /// specified result type.
939 ///
940 /// This routine should be used for expressions for which the return type is
941 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
942 /// an lvalue. It removes a top-level reference (since there are no
943 /// expressions of reference type) and deletes top-level cvr-qualifiers
944 /// from non-class types (in C++) or all types (in C).
945 QualType getNonLValueExprType(const ASTContext &Context) const;
946
947 /// Return the specified type with any "sugar" removed from
948 /// the type. This takes off typedefs, typeof's etc. If the outer level of
949 /// the type is already concrete, it returns it unmodified. This is similar
950 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
951 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
952 /// concrete.
953 ///
954 /// Qualifiers are left in place.
955 QualType getDesugaredType(const ASTContext &Context) const {
956 return getDesugaredType(*this, Context);
957 }
958
959 SplitQualType getSplitDesugaredType() const {
960 return getSplitDesugaredType(*this);
961 }
962
963 /// Return the specified type with one level of "sugar" removed from
964 /// the type.
965 ///
966 /// This routine takes off the first typedef, typeof, etc. If the outer level
967 /// of the type is already concrete, it returns it unmodified.
968 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
969 return getSingleStepDesugaredTypeImpl(*this, Context);
970 }
971
972 /// Returns the specified type after dropping any
973 /// outer-level parentheses.
974 QualType IgnoreParens() const {
975 if (isa<ParenType>(*this))
976 return QualType::IgnoreParens(*this);
977 return *this;
978 }
979
980 /// Indicate whether the specified types and qualifiers are identical.
981 friend bool operator==(const QualType &LHS, const QualType &RHS) {
982 return LHS.Value == RHS.Value;
18
Calling 'PointerIntPair::operator=='
21
Returning from 'PointerIntPair::operator=='
22
Returning zero, which participates in a condition later
983 }
984 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
985 return LHS.Value != RHS.Value;
986 }
987 friend bool operator<(const QualType &LHS, const QualType &RHS) {
988 return LHS.Value < RHS.Value;
989 }
990
991 static std::string getAsString(SplitQualType split,
992 const PrintingPolicy &Policy) {
993 return getAsString(split.Ty, split.Quals, Policy);
994 }
995 static std::string getAsString(const Type *ty, Qualifiers qs,
996 const PrintingPolicy &Policy);
997
998 std::string getAsString() const;
999 std::string getAsString(const PrintingPolicy &Policy) const;
1000
1001 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1002 const Twine &PlaceHolder = Twine(),
1003 unsigned Indentation = 0) const;
1004
1005 static void print(SplitQualType split, raw_ostream &OS,
1006 const PrintingPolicy &policy, const Twine &PlaceHolder,
1007 unsigned Indentation = 0) {
1008 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1009 }
1010
1011 static void print(const Type *ty, Qualifiers qs,
1012 raw_ostream &OS, const PrintingPolicy &policy,
1013 const Twine &PlaceHolder,
1014 unsigned Indentation = 0);
1015
1016 void getAsStringInternal(std::string &Str,
1017 const PrintingPolicy &Policy) const;
1018
1019 static void getAsStringInternal(SplitQualType split, std::string &out,
1020 const PrintingPolicy &policy) {
1021 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1022 }
1023
1024 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1025 std::string &out,
1026 const PrintingPolicy &policy);
1027
1028 class StreamedQualTypeHelper {
1029 const QualType &T;
1030 const PrintingPolicy &Policy;
1031 const Twine &PlaceHolder;
1032 unsigned Indentation;
1033
1034 public:
1035 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder, unsigned Indentation)
1037 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1038 Indentation(Indentation) {}
1039
1040 friend raw_ostream &operator<<(raw_ostream &OS,
1041 const StreamedQualTypeHelper &SQT) {
1042 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1043 return OS;
1044 }
1045 };
1046
1047 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1048 const Twine &PlaceHolder = Twine(),
1049 unsigned Indentation = 0) const {
1050 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1051 }
1052
1053 void dump(const char *s) const;
1054 void dump() const;
1055 void dump(llvm::raw_ostream &OS) const;
1056
1057 void Profile(llvm::FoldingSetNodeID &ID) const {
1058 ID.AddPointer(getAsOpaquePtr());
1059 }
1060
1061 /// Check if this type has any address space qualifier.
1062 inline bool hasAddressSpace() const;
1063
1064 /// Return the address space of this type.
1065 inline LangAS getAddressSpace() const;
1066
1067 /// Returns gc attribute of this type.
1068 inline Qualifiers::GC getObjCGCAttr() const;
1069
1070 /// true when Type is objc's weak.
1071 bool isObjCGCWeak() const {
1072 return getObjCGCAttr() == Qualifiers::Weak;
1073 }
1074
1075 /// true when Type is objc's strong.
1076 bool isObjCGCStrong() const {
1077 return getObjCGCAttr() == Qualifiers::Strong;
1078 }
1079
1080 /// Returns lifetime attribute of this type.
1081 Qualifiers::ObjCLifetime getObjCLifetime() const {
1082 return getQualifiers().getObjCLifetime();
1083 }
1084
1085 bool hasNonTrivialObjCLifetime() const {
1086 return getQualifiers().hasNonTrivialObjCLifetime();
1087 }
1088
1089 bool hasStrongOrWeakObjCLifetime() const {
1090 return getQualifiers().hasStrongOrWeakObjCLifetime();
1091 }
1092
1093 // true when Type is objc's weak and weak is enabled but ARC isn't.
1094 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1095
1096 enum PrimitiveDefaultInitializeKind {
1097 /// The type does not fall into any of the following categories. Note that
1098 /// this case is zero-valued so that values of this enum can be used as a
1099 /// boolean condition for non-triviality.
1100 PDIK_Trivial,
1101
1102 /// The type is an Objective-C retainable pointer type that is qualified
1103 /// with the ARC __strong qualifier.
1104 PDIK_ARCStrong,
1105
1106 /// The type is an Objective-C retainable pointer type that is qualified
1107 /// with the ARC __weak qualifier.
1108 PDIK_ARCWeak,
1109
1110 /// The type is a struct containing a field whose type is not PCK_Trivial.
1111 PDIK_Struct
1112 };
1113
1114 /// Functions to query basic properties of non-trivial C struct types.
1115
1116 /// Check if this is a non-trivial type that would cause a C struct
1117 /// transitively containing this type to be non-trivial to default initialize
1118 /// and return the kind.
1119 PrimitiveDefaultInitializeKind
1120 isNonTrivialToPrimitiveDefaultInitialize() const;
1121
1122 enum PrimitiveCopyKind {
1123 /// The type does not fall into any of the following categories. Note that
1124 /// this case is zero-valued so that values of this enum can be used as a
1125 /// boolean condition for non-triviality.
1126 PCK_Trivial,
1127
1128 /// The type would be trivial except that it is volatile-qualified. Types
1129 /// that fall into one of the other non-trivial cases may additionally be
1130 /// volatile-qualified.
1131 PCK_VolatileTrivial,
1132
1133 /// The type is an Objective-C retainable pointer type that is qualified
1134 /// with the ARC __strong qualifier.
1135 PCK_ARCStrong,
1136
1137 /// The type is an Objective-C retainable pointer type that is qualified
1138 /// with the ARC __weak qualifier.
1139 PCK_ARCWeak,
1140
1141 /// The type is a struct containing a field whose type is neither
1142 /// PCK_Trivial nor PCK_VolatileTrivial.
1143 /// Note that a C++ struct type does not necessarily match this; C++ copying
1144 /// semantics are too complex to express here, in part because they depend
1145 /// on the exact constructor or assignment operator that is chosen by
1146 /// overload resolution to do the copy.
1147 PCK_Struct
1148 };
1149
1150 /// Check if this is a non-trivial type that would cause a C struct
1151 /// transitively containing this type to be non-trivial to copy and return the
1152 /// kind.
1153 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1154
1155 /// Check if this is a non-trivial type that would cause a C struct
1156 /// transitively containing this type to be non-trivial to destructively
1157 /// move and return the kind. Destructive move in this context is a C++-style
1158 /// move in which the source object is placed in a valid but unspecified state
1159 /// after it is moved, as opposed to a truly destructive move in which the
1160 /// source object is placed in an uninitialized state.
1161 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1162
1163 enum DestructionKind {
1164 DK_none,
1165 DK_cxx_destructor,
1166 DK_objc_strong_lifetime,
1167 DK_objc_weak_lifetime,
1168 DK_nontrivial_c_struct
1169 };
1170
1171 /// Returns a nonzero value if objects of this type require
1172 /// non-trivial work to clean up after. Non-zero because it's
1173 /// conceivable that qualifiers (objc_gc(weak)?) could make
1174 /// something require destruction.
1175 DestructionKind isDestructedType() const {
1176 return isDestructedTypeImpl(*this);
1177 }
1178
1179 /// Check if this is or contains a C union that is non-trivial to
1180 /// default-initialize, which is a union that has a member that is non-trivial
1181 /// to default-initialize. If this returns true,
1182 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1183 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1184
1185 /// Check if this is or contains a C union that is non-trivial to destruct,
1186 /// which is a union that has a member that is non-trivial to destruct. If
1187 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1188 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1189
1190 /// Check if this is or contains a C union that is non-trivial to copy, which
1191 /// is a union that has a member that is non-trivial to copy. If this returns
1192 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1193 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1194
1195 /// Determine whether expressions of the given type are forbidden
1196 /// from being lvalues in C.
1197 ///
1198 /// The expression types that are forbidden to be lvalues are:
1199 /// - 'void', but not qualified void
1200 /// - function types
1201 ///
1202 /// The exact rule here is C99 6.3.2.1:
1203 /// An lvalue is an expression with an object type or an incomplete
1204 /// type other than void.
1205 bool isCForbiddenLValueType() const;
1206
1207 /// Substitute type arguments for the Objective-C type parameters used in the
1208 /// subject type.
1209 ///
1210 /// \param ctx ASTContext in which the type exists.
1211 ///
1212 /// \param typeArgs The type arguments that will be substituted for the
1213 /// Objective-C type parameters in the subject type, which are generally
1214 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1215 /// parameters will be replaced with their bounds or id/Class, as appropriate
1216 /// for the context.
1217 ///
1218 /// \param context The context in which the subject type was written.
1219 ///
1220 /// \returns the resulting type.
1221 QualType substObjCTypeArgs(ASTContext &ctx,
1222 ArrayRef<QualType> typeArgs,
1223 ObjCSubstitutionContext context) const;
1224
1225 /// Substitute type arguments from an object type for the Objective-C type
1226 /// parameters used in the subject type.
1227 ///
1228 /// This operation combines the computation of type arguments for
1229 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1230 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1231 /// callers that need to perform a single substitution in isolation.
1232 ///
1233 /// \param objectType The type of the object whose member type we're
1234 /// substituting into. For example, this might be the receiver of a message
1235 /// or the base of a property access.
1236 ///
1237 /// \param dc The declaration context from which the subject type was
1238 /// retrieved, which indicates (for example) which type parameters should
1239 /// be substituted.
1240 ///
1241 /// \param context The context in which the subject type was written.
1242 ///
1243 /// \returns the subject type after replacing all of the Objective-C type
1244 /// parameters with their corresponding arguments.
1245 QualType substObjCMemberType(QualType objectType,
1246 const DeclContext *dc,
1247 ObjCSubstitutionContext context) const;
1248
1249 /// Strip Objective-C "__kindof" types from the given type.
1250 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1251
1252 /// Remove all qualifiers including _Atomic.
1253 QualType getAtomicUnqualifiedType() const;
1254
1255private:
1256 // These methods are implemented in a separate translation unit;
1257 // "static"-ize them to avoid creating temporary QualTypes in the
1258 // caller.
1259 static bool isConstant(QualType T, const ASTContext& Ctx);
1260 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1261 static SplitQualType getSplitDesugaredType(QualType T);
1262 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1263 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1264 const ASTContext &C);
1265 static QualType IgnoreParens(QualType T);
1266 static DestructionKind isDestructedTypeImpl(QualType type);
1267
1268 /// Check if \param RD is or contains a non-trivial C union.
1269 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1270 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1271 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1272};
1273
1274} // namespace clang
1275
1276namespace llvm {
1277
1278/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1279/// to a specific Type class.
1280template<> struct simplify_type< ::clang::QualType> {
1281 using SimpleType = const ::clang::Type *;
1282
1283 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1284 return Val.getTypePtr();
1285 }
1286};
1287
1288// Teach SmallPtrSet that QualType is "basically a pointer".
1289template<>
1290struct PointerLikeTypeTraits<clang::QualType> {
1291 static inline void *getAsVoidPointer(clang::QualType P) {
1292 return P.getAsOpaquePtr();
1293 }
1294
1295 static inline clang::QualType getFromVoidPointer(void *P) {
1296 return clang::QualType::getFromOpaquePtr(P);
1297 }
1298
1299 // Various qualifiers go in low bits.
1300 static constexpr int NumLowBitsAvailable = 0;
1301};
1302
1303} // namespace llvm
1304
1305namespace clang {
1306
1307/// Base class that is common to both the \c ExtQuals and \c Type
1308/// classes, which allows \c QualType to access the common fields between the
1309/// two.
1310class ExtQualsTypeCommonBase {
1311 friend class ExtQuals;
1312 friend class QualType;
1313 friend class Type;
1314
1315 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1316 /// a self-referential pointer (for \c Type).
1317 ///
1318 /// This pointer allows an efficient mapping from a QualType to its
1319 /// underlying type pointer.
1320 const Type *const BaseType;
1321
1322 /// The canonical type of this type. A QualType.
1323 QualType CanonicalType;
1324
1325 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1326 : BaseType(baseType), CanonicalType(canon) {}
1327};
1328
1329/// We can encode up to four bits in the low bits of a
1330/// type pointer, but there are many more type qualifiers that we want
1331/// to be able to apply to an arbitrary type. Therefore we have this
1332/// struct, intended to be heap-allocated and used by QualType to
1333/// store qualifiers.
1334///
1335/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1336/// in three low bits on the QualType pointer; a fourth bit records whether
1337/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1338/// Objective-C GC attributes) are much more rare.
1339class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1340 // NOTE: changing the fast qualifiers should be straightforward as
1341 // long as you don't make 'const' non-fast.
1342 // 1. Qualifiers:
1343 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1344 // Fast qualifiers must occupy the low-order bits.
1345 // b) Update Qualifiers::FastWidth and FastMask.
1346 // 2. QualType:
1347 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1348 // b) Update remove{Volatile,Restrict}, defined near the end of
1349 // this header.
1350 // 3. ASTContext:
1351 // a) Update get{Volatile,Restrict}Type.
1352
1353 /// The immutable set of qualifiers applied by this node. Always contains
1354 /// extended qualifiers.
1355 Qualifiers Quals;
1356
1357 ExtQuals *this_() { return this; }
1358
1359public:
1360 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1361 : ExtQualsTypeCommonBase(baseType,
1362 canon.isNull() ? QualType(this_(), 0) : canon),
1363 Quals(quals) {
1364 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1365, __PRETTY_FUNCTION__))
1365 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1365, __PRETTY_FUNCTION__))
;
1366 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1367, __PRETTY_FUNCTION__))
1367 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1367, __PRETTY_FUNCTION__))
;
1368 }
1369
1370 Qualifiers getQualifiers() const { return Quals; }
1371
1372 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1373 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1374
1375 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1376 Qualifiers::ObjCLifetime getObjCLifetime() const {
1377 return Quals.getObjCLifetime();
1378 }
1379
1380 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1381 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1382
1383 const Type *getBaseType() const { return BaseType; }
1384
1385public:
1386 void Profile(llvm::FoldingSetNodeID &ID) const {
1387 Profile(ID, getBaseType(), Quals);
1388 }
1389
1390 static void Profile(llvm::FoldingSetNodeID &ID,
1391 const Type *BaseType,
1392 Qualifiers Quals) {
1393 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1393, __PRETTY_FUNCTION__))
;
1394 ID.AddPointer(BaseType);
1395 Quals.Profile(ID);
1396 }
1397};
1398
1399/// The kind of C++11 ref-qualifier associated with a function type.
1400/// This determines whether a member function's "this" object can be an
1401/// lvalue, rvalue, or neither.
1402enum RefQualifierKind {
1403 /// No ref-qualifier was provided.
1404 RQ_None = 0,
1405
1406 /// An lvalue ref-qualifier was provided (\c &).
1407 RQ_LValue,
1408
1409 /// An rvalue ref-qualifier was provided (\c &&).
1410 RQ_RValue
1411};
1412
1413/// Which keyword(s) were used to create an AutoType.
1414enum class AutoTypeKeyword {
1415 /// auto
1416 Auto,
1417
1418 /// decltype(auto)
1419 DecltypeAuto,
1420
1421 /// __auto_type (GNU extension)
1422 GNUAutoType
1423};
1424
1425/// The base class of the type hierarchy.
1426///
1427/// A central concept with types is that each type always has a canonical
1428/// type. A canonical type is the type with any typedef names stripped out
1429/// of it or the types it references. For example, consider:
1430///
1431/// typedef int foo;
1432/// typedef foo* bar;
1433/// 'int *' 'foo *' 'bar'
1434///
1435/// There will be a Type object created for 'int'. Since int is canonical, its
1436/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1437/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1438/// there is a PointerType that represents 'int*', which, like 'int', is
1439/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1440/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1441/// is also 'int*'.
1442///
1443/// Non-canonical types are useful for emitting diagnostics, without losing
1444/// information about typedefs being used. Canonical types are useful for type
1445/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1446/// about whether something has a particular form (e.g. is a function type),
1447/// because they implicitly, recursively, strip all typedefs out of a type.
1448///
1449/// Types, once created, are immutable.
1450///
1451class alignas(8) Type : public ExtQualsTypeCommonBase {
1452public:
1453 enum TypeClass {
1454#define TYPE(Class, Base) Class,
1455#define LAST_TYPE(Class) TypeLast = Class
1456#define ABSTRACT_TYPE(Class, Base)
1457#include "clang/AST/TypeNodes.inc"
1458 };
1459
1460private:
1461 /// Bitfields required by the Type class.
1462 class TypeBitfields {
1463 friend class Type;
1464 template <class T> friend class TypePropertyCache;
1465
1466 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1467 unsigned TC : 8;
1468
1469 /// Store information on the type dependency.
1470 /*TypeDependence*/ unsigned Dependence : TypeDependenceBits;
1471
1472 /// True if the cache (i.e. the bitfields here starting with
1473 /// 'Cache') is valid.
1474 mutable unsigned CacheValid : 1;
1475
1476 /// Linkage of this type.
1477 mutable unsigned CachedLinkage : 3;
1478
1479 /// Whether this type involves and local or unnamed types.
1480 mutable unsigned CachedLocalOrUnnamed : 1;
1481
1482 /// Whether this type comes from an AST file.
1483 mutable unsigned FromAST : 1;
1484
1485 bool isCacheValid() const {
1486 return CacheValid;
1487 }
1488
1489 Linkage getLinkage() const {
1490 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1490, __PRETTY_FUNCTION__))
;
1491 return static_cast<Linkage>(CachedLinkage);
1492 }
1493
1494 bool hasLocalOrUnnamedType() const {
1495 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 1495, __PRETTY_FUNCTION__))
;
1496 return CachedLocalOrUnnamed;
1497 }
1498 };
1499 enum { NumTypeBits = 18 };
1500
1501protected:
1502 // These classes allow subclasses to somewhat cleanly pack bitfields
1503 // into Type.
1504
1505 class ArrayTypeBitfields {
1506 friend class ArrayType;
1507
1508 unsigned : NumTypeBits;
1509
1510 /// CVR qualifiers from declarations like
1511 /// 'int X[static restrict 4]'. For function parameters only.
1512 unsigned IndexTypeQuals : 3;
1513
1514 /// Storage class qualifiers from declarations like
1515 /// 'int X[static restrict 4]'. For function parameters only.
1516 /// Actually an ArrayType::ArraySizeModifier.
1517 unsigned SizeModifier : 3;
1518 };
1519
1520 class ConstantArrayTypeBitfields {
1521 friend class ConstantArrayType;
1522
1523 unsigned : NumTypeBits + 3 + 3;
1524
1525 /// Whether we have a stored size expression.
1526 unsigned HasStoredSizeExpr : 1;
1527 };
1528
1529 class BuiltinTypeBitfields {
1530 friend class BuiltinType;
1531
1532 unsigned : NumTypeBits;
1533
1534 /// The kind (BuiltinType::Kind) of builtin type this is.
1535 unsigned Kind : 8;
1536 };
1537
1538 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1539 /// Only common bits are stored here. Additional uncommon bits are stored
1540 /// in a trailing object after FunctionProtoType.
1541 class FunctionTypeBitfields {
1542 friend class FunctionProtoType;
1543 friend class FunctionType;
1544
1545 unsigned : NumTypeBits;
1546
1547 /// Extra information which affects how the function is called, like
1548 /// regparm and the calling convention.
1549 unsigned ExtInfo : 12;
1550
1551 /// The ref-qualifier associated with a \c FunctionProtoType.
1552 ///
1553 /// This is a value of type \c RefQualifierKind.
1554 unsigned RefQualifier : 2;
1555
1556 /// Used only by FunctionProtoType, put here to pack with the
1557 /// other bitfields.
1558 /// The qualifiers are part of FunctionProtoType because...
1559 ///
1560 /// C++ 8.3.5p4: The return type, the parameter type list and the
1561 /// cv-qualifier-seq, [...], are part of the function type.
1562 unsigned FastTypeQuals : Qualifiers::FastWidth;
1563 /// Whether this function has extended Qualifiers.
1564 unsigned HasExtQuals : 1;
1565
1566 /// The number of parameters this function has, not counting '...'.
1567 /// According to [implimits] 8 bits should be enough here but this is
1568 /// somewhat easy to exceed with metaprogramming and so we would like to
1569 /// keep NumParams as wide as reasonably possible.
1570 unsigned NumParams : 16;
1571
1572 /// The type of exception specification this function has.
1573 unsigned ExceptionSpecType : 4;
1574
1575 /// Whether this function has extended parameter information.
1576 unsigned HasExtParameterInfos : 1;
1577
1578 /// Whether the function is variadic.
1579 unsigned Variadic : 1;
1580
1581 /// Whether this function has a trailing return type.
1582 unsigned HasTrailingReturn : 1;
1583 };
1584
1585 class ObjCObjectTypeBitfields {
1586 friend class ObjCObjectType;
1587
1588 unsigned : NumTypeBits;
1589
1590 /// The number of type arguments stored directly on this object type.
1591 unsigned NumTypeArgs : 7;
1592
1593 /// The number of protocols stored directly on this object type.
1594 unsigned NumProtocols : 6;
1595
1596 /// Whether this is a "kindof" type.
1597 unsigned IsKindOf : 1;
1598 };
1599
1600 class ReferenceTypeBitfields {
1601 friend class ReferenceType;
1602
1603 unsigned : NumTypeBits;
1604
1605 /// True if the type was originally spelled with an lvalue sigil.
1606 /// This is never true of rvalue references but can also be false
1607 /// on lvalue references because of C++0x [dcl.typedef]p9,
1608 /// as follows:
1609 ///
1610 /// typedef int &ref; // lvalue, spelled lvalue
1611 /// typedef int &&rvref; // rvalue
1612 /// ref &a; // lvalue, inner ref, spelled lvalue
1613 /// ref &&a; // lvalue, inner ref
1614 /// rvref &a; // lvalue, inner ref, spelled lvalue
1615 /// rvref &&a; // rvalue, inner ref
1616 unsigned SpelledAsLValue : 1;
1617
1618 /// True if the inner type is a reference type. This only happens
1619 /// in non-canonical forms.
1620 unsigned InnerRef : 1;
1621 };
1622
1623 class TypeWithKeywordBitfields {
1624 friend class TypeWithKeyword;
1625
1626 unsigned : NumTypeBits;
1627
1628 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1629 unsigned Keyword : 8;
1630 };
1631
1632 enum { NumTypeWithKeywordBits = 8 };
1633
1634 class ElaboratedTypeBitfields {
1635 friend class ElaboratedType;
1636
1637 unsigned : NumTypeBits;
1638 unsigned : NumTypeWithKeywordBits;
1639
1640 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1641 unsigned HasOwnedTagDecl : 1;
1642 };
1643
1644 class VectorTypeBitfields {
1645 friend class VectorType;
1646 friend class DependentVectorType;
1647
1648 unsigned : NumTypeBits;
1649
1650 /// The kind of vector, either a generic vector type or some
1651 /// target-specific vector type such as for AltiVec or Neon.
1652 unsigned VecKind : 3;
1653
1654 /// The number of elements in the vector.
1655 unsigned NumElements : 29 - NumTypeBits;
1656
1657 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1658 };
1659
1660 class AttributedTypeBitfields {
1661 friend class AttributedType;
1662
1663 unsigned : NumTypeBits;
1664
1665 /// An AttributedType::Kind
1666 unsigned AttrKind : 32 - NumTypeBits;
1667 };
1668
1669 class AutoTypeBitfields {
1670 friend class AutoType;
1671
1672 unsigned : NumTypeBits;
1673
1674 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1675 /// or '__auto_type'? AutoTypeKeyword value.
1676 unsigned Keyword : 2;
1677
1678 /// The number of template arguments in the type-constraints, which is
1679 /// expected to be able to hold at least 1024 according to [implimits].
1680 /// However as this limit is somewhat easy to hit with template
1681 /// metaprogramming we'd prefer to keep it as large as possible.
1682 /// At the moment it has been left as a non-bitfield since this type
1683 /// safely fits in 64 bits as an unsigned, so there is no reason to
1684 /// introduce the performance impact of a bitfield.
1685 unsigned NumArgs;
1686 };
1687
1688 class SubstTemplateTypeParmPackTypeBitfields {
1689 friend class SubstTemplateTypeParmPackType;
1690
1691 unsigned : NumTypeBits;
1692
1693 /// The number of template arguments in \c Arguments, which is
1694 /// expected to be able to hold at least 1024 according to [implimits].
1695 /// However as this limit is somewhat easy to hit with template
1696 /// metaprogramming we'd prefer to keep it as large as possible.
1697 /// At the moment it has been left as a non-bitfield since this type
1698 /// safely fits in 64 bits as an unsigned, so there is no reason to
1699 /// introduce the performance impact of a bitfield.
1700 unsigned NumArgs;
1701 };
1702
1703 class TemplateSpecializationTypeBitfields {
1704 friend class TemplateSpecializationType;
1705
1706 unsigned : NumTypeBits;
1707
1708 /// Whether this template specialization type is a substituted type alias.
1709 unsigned TypeAlias : 1;
1710
1711 /// The number of template arguments named in this class template
1712 /// specialization, which is expected to be able to hold at least 1024
1713 /// according to [implimits]. However, as this limit is somewhat easy to
1714 /// hit with template metaprogramming we'd prefer to keep it as large
1715 /// as possible. At the moment it has been left as a non-bitfield since
1716 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1717 /// to introduce the performance impact of a bitfield.
1718 unsigned NumArgs;
1719 };
1720
1721 class DependentTemplateSpecializationTypeBitfields {
1722 friend class DependentTemplateSpecializationType;
1723
1724 unsigned : NumTypeBits;
1725 unsigned : NumTypeWithKeywordBits;
1726
1727 /// The number of template arguments named in this class template
1728 /// specialization, which is expected to be able to hold at least 1024
1729 /// according to [implimits]. However, as this limit is somewhat easy to
1730 /// hit with template metaprogramming we'd prefer to keep it as large
1731 /// as possible. At the moment it has been left as a non-bitfield since
1732 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1733 /// to introduce the performance impact of a bitfield.
1734 unsigned NumArgs;
1735 };
1736
1737 class PackExpansionTypeBitfields {
1738 friend class PackExpansionType;
1739
1740 unsigned : NumTypeBits;
1741
1742 /// The number of expansions that this pack expansion will
1743 /// generate when substituted (+1), which is expected to be able to
1744 /// hold at least 1024 according to [implimits]. However, as this limit
1745 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1746 /// keep it as large as possible. At the moment it has been left as a
1747 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1748 /// there is no reason to introduce the performance impact of a bitfield.
1749 ///
1750 /// This field will only have a non-zero value when some of the parameter
1751 /// packs that occur within the pattern have been substituted but others
1752 /// have not.
1753 unsigned NumExpansions;
1754 };
1755
1756 union {
1757 TypeBitfields TypeBits;
1758 ArrayTypeBitfields ArrayTypeBits;
1759 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1760 AttributedTypeBitfields AttributedTypeBits;
1761 AutoTypeBitfields AutoTypeBits;
1762 BuiltinTypeBitfields BuiltinTypeBits;
1763 FunctionTypeBitfields FunctionTypeBits;
1764 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1765 ReferenceTypeBitfields ReferenceTypeBits;
1766 TypeWithKeywordBitfields TypeWithKeywordBits;
1767 ElaboratedTypeBitfields ElaboratedTypeBits;
1768 VectorTypeBitfields VectorTypeBits;
1769 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1770 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1771 DependentTemplateSpecializationTypeBitfields
1772 DependentTemplateSpecializationTypeBits;
1773 PackExpansionTypeBitfields PackExpansionTypeBits;
1774
1775 static_assert(sizeof(TypeBitfields) <= 8,
1776 "TypeBitfields is larger than 8 bytes!");
1777 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1778 "ArrayTypeBitfields is larger than 8 bytes!");
1779 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1780 "AttributedTypeBitfields is larger than 8 bytes!");
1781 static_assert(sizeof(AutoTypeBitfields) <= 8,
1782 "AutoTypeBitfields is larger than 8 bytes!");
1783 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1784 "BuiltinTypeBitfields is larger than 8 bytes!");
1785 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1786 "FunctionTypeBitfields is larger than 8 bytes!");
1787 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1788 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1789 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1790 "ReferenceTypeBitfields is larger than 8 bytes!");
1791 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1792 "TypeWithKeywordBitfields is larger than 8 bytes!");
1793 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1794 "ElaboratedTypeBitfields is larger than 8 bytes!");
1795 static_assert(sizeof(VectorTypeBitfields) <= 8,
1796 "VectorTypeBitfields is larger than 8 bytes!");
1797 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1798 "SubstTemplateTypeParmPackTypeBitfields is larger"
1799 " than 8 bytes!");
1800 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1801 "TemplateSpecializationTypeBitfields is larger"
1802 " than 8 bytes!");
1803 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1804 "DependentTemplateSpecializationTypeBitfields is larger"
1805 " than 8 bytes!");
1806 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1807 "PackExpansionTypeBitfields is larger than 8 bytes");
1808 };
1809
1810private:
1811 template <class T> friend class TypePropertyCache;
1812
1813 /// Set whether this type comes from an AST file.
1814 void setFromAST(bool V = true) const {
1815 TypeBits.FromAST = V;
1816 }
1817
1818protected:
1819 friend class ASTContext;
1820
1821 Type(TypeClass tc, QualType canon, bool Dependent,
1822 bool InstantiationDependent, bool VariablyModified,
1823 bool ContainsUnexpandedParameterPack)
1824 : ExtQualsTypeCommonBase(this,
1825 canon.isNull() ? QualType(this_(), 0) : canon) {
1826 auto Deps = TypeDependence::None;
1827 if (Dependent)
1828 Deps |= TypeDependence::Dependent | TypeDependence::Instantiation;
1829 if (InstantiationDependent)
1830 Deps |= TypeDependence::Instantiation;
1831 if (ContainsUnexpandedParameterPack)
1832 Deps |= TypeDependence::UnexpandedPack;
1833 if (VariablyModified)
1834 Deps |= TypeDependence::VariablyModified;
1835
1836 TypeBits.TC = tc;
1837 TypeBits.Dependence = static_cast<unsigned>(Deps);
1838 TypeBits.CacheValid = false;
1839 TypeBits.CachedLocalOrUnnamed = false;
1840 TypeBits.CachedLinkage = NoLinkage;
1841 TypeBits.FromAST = false;
1842 }
1843
1844 // silence VC++ warning C4355: 'this' : used in base member initializer list
1845 Type *this_() { return this; }
1846
1847 void setDependent(bool D = true) {
1848 if (!D) {
1849 TypeBits.Dependence &= ~static_cast<unsigned>(TypeDependence::Dependent);
1850 return;
1851 }
1852 TypeBits.Dependence |= static_cast<unsigned>(TypeDependence::Dependent |
1853 TypeDependence::Instantiation);
1854 }
1855
1856 void setInstantiationDependent(bool D = true) {
1857 if (D)
1858 TypeBits.Dependence |=
1859 static_cast<unsigned>(TypeDependence::Instantiation);
1860 else
1861 TypeBits.Dependence &=
1862 ~static_cast<unsigned>(TypeDependence::Instantiation);
1863 }
1864
1865 void setVariablyModified(bool VM = true) {
1866 if (VM)
1867 TypeBits.Dependence |=
1868 static_cast<unsigned>(TypeDependence::VariablyModified);
1869 else
1870 TypeBits.Dependence &=
1871 ~static_cast<unsigned>(TypeDependence::VariablyModified);
1872 }
1873
1874 void setContainsUnexpandedParameterPack(bool PP = true) {
1875 if (PP)
1876 TypeBits.Dependence |=
1877 static_cast<unsigned>(TypeDependence::UnexpandedPack);
1878 else
1879 TypeBits.Dependence &=
1880 ~static_cast<unsigned>(TypeDependence::UnexpandedPack);
1881 }
1882
1883public:
1884 friend class ASTReader;
1885 friend class ASTWriter;
1886 template <class T> friend class serialization::AbstractTypeReader;
1887 template <class T> friend class serialization::AbstractTypeWriter;
1888
1889 Type(const Type &) = delete;
1890 Type(Type &&) = delete;
1891 Type &operator=(const Type &) = delete;
1892 Type &operator=(Type &&) = delete;
1893
1894 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1895
1896 /// Whether this type comes from an AST file.
1897 bool isFromAST() const { return TypeBits.FromAST; }
1898
1899 /// Whether this type is or contains an unexpanded parameter
1900 /// pack, used to support C++0x variadic templates.
1901 ///
1902 /// A type that contains a parameter pack shall be expanded by the
1903 /// ellipsis operator at some point. For example, the typedef in the
1904 /// following example contains an unexpanded parameter pack 'T':
1905 ///
1906 /// \code
1907 /// template<typename ...T>
1908 /// struct X {
1909 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1910 /// };
1911 /// \endcode
1912 ///
1913 /// Note that this routine does not specify which
1914 bool containsUnexpandedParameterPack() const {
1915 return getDependence() & TypeDependence::UnexpandedPack;
1916 }
1917
1918 /// Determines if this type would be canonical if it had no further
1919 /// qualification.
1920 bool isCanonicalUnqualified() const {
1921 return CanonicalType == QualType(this, 0);
1922 }
1923
1924 /// Pull a single level of sugar off of this locally-unqualified type.
1925 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1926 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1927 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1928
1929 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1930 /// object types, function types, and incomplete types.
1931
1932 /// Return true if this is an incomplete type.
1933 /// A type that can describe objects, but which lacks information needed to
1934 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1935 /// routine will need to determine if the size is actually required.
1936 ///
1937 /// Def If non-null, and the type refers to some kind of declaration
1938 /// that can be completed (such as a C struct, C++ class, or Objective-C
1939 /// class), will be set to the declaration.
1940 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1941
1942 /// Return true if this is an incomplete or object
1943 /// type, in other words, not a function type.
1944 bool isIncompleteOrObjectType() const {
1945 return !isFunctionType();
1946 }
1947
1948 /// Determine whether this type is an object type.
1949 bool isObjectType() const {
1950 // C++ [basic.types]p8:
1951 // An object type is a (possibly cv-qualified) type that is not a
1952 // function type, not a reference type, and not a void type.
1953 return !isReferenceType() && !isFunctionType() && !isVoidType();
1954 }
1955
1956 /// Return true if this is a literal type
1957 /// (C++11 [basic.types]p10)
1958 bool isLiteralType(const ASTContext &Ctx) const;
1959
1960 /// Test if this type is a standard-layout type.
1961 /// (C++0x [basic.type]p9)
1962 bool isStandardLayoutType() const;
1963
1964 /// Helper methods to distinguish type categories. All type predicates
1965 /// operate on the canonical type, ignoring typedefs and qualifiers.
1966
1967 /// Returns true if the type is a builtin type.
1968 bool isBuiltinType() const;
1969
1970 /// Test for a particular builtin type.
1971 bool isSpecificBuiltinType(unsigned K) const;
1972
1973 /// Test for a type which does not represent an actual type-system type but
1974 /// is instead used as a placeholder for various convenient purposes within
1975 /// Clang. All such types are BuiltinTypes.
1976 bool isPlaceholderType() const;
1977 const BuiltinType *getAsPlaceholderType() const;
1978
1979 /// Test for a specific placeholder type.
1980 bool isSpecificPlaceholderType(unsigned K) const;
1981
1982 /// Test for a placeholder type other than Overload; see
1983 /// BuiltinType::isNonOverloadPlaceholderType.
1984 bool isNonOverloadPlaceholderType() const;
1985
1986 /// isIntegerType() does *not* include complex integers (a GCC extension).
1987 /// isComplexIntegerType() can be used to test for complex integers.
1988 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1989 bool isEnumeralType() const;
1990
1991 /// Determine whether this type is a scoped enumeration type.
1992 bool isScopedEnumeralType() const;
1993 bool isBooleanType() const;
1994 bool isCharType() const;
1995 bool isWideCharType() const;
1996 bool isChar8Type() const;
1997 bool isChar16Type() const;
1998 bool isChar32Type() const;
1999 bool isAnyCharacterType() const;
2000 bool isIntegralType(const ASTContext &Ctx) const;
2001
2002 /// Determine whether this type is an integral or enumeration type.
2003 bool isIntegralOrEnumerationType() const;
2004
2005 /// Determine whether this type is an integral or unscoped enumeration type.
2006 bool isIntegralOrUnscopedEnumerationType() const;
2007 bool isUnscopedEnumerationType() const;
2008
2009 /// Floating point categories.
2010 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
2011 /// isComplexType() does *not* include complex integers (a GCC extension).
2012 /// isComplexIntegerType() can be used to test for complex integers.
2013 bool isComplexType() const; // C99 6.2.5p11 (complex)
2014 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2015 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2016 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2017 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2018 bool isFloat128Type() const;
2019 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2020 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2021 bool isVoidType() const; // C99 6.2.5p19
2022 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2023 bool isAggregateType() const;
2024 bool isFundamentalType() const;
2025 bool isCompoundType() const;
2026
2027 // Type Predicates: Check to see if this type is structurally the specified
2028 // type, ignoring typedefs and qualifiers.
2029 bool isFunctionType() const;
2030 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2031 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2032 bool isPointerType() const;
2033 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2034 bool isBlockPointerType() const;
2035 bool isVoidPointerType() const;
2036 bool isReferenceType() const;
2037 bool isLValueReferenceType() const;
2038 bool isRValueReferenceType() const;
2039 bool isObjectPointerType() const;
2040 bool isFunctionPointerType() const;
2041 bool isFunctionReferenceType() const;
2042 bool isMemberPointerType() const;
2043 bool isMemberFunctionPointerType() const;
2044 bool isMemberDataPointerType() const;
2045 bool isArrayType() const;
2046 bool isConstantArrayType() const;
2047 bool isIncompleteArrayType() const;
2048 bool isVariableArrayType() const;
2049 bool isDependentSizedArrayType() const;
2050 bool isRecordType() const;
2051 bool isClassType() const;
2052 bool isStructureType() const;
2053 bool isObjCBoxableRecordType() const;
2054 bool isInterfaceType() const;
2055 bool isStructureOrClassType() const;
2056 bool isUnionType() const;
2057 bool isComplexIntegerType() const; // GCC _Complex integer type.
2058 bool isVectorType() const; // GCC vector type.
2059 bool isExtVectorType() const; // Extended vector type.
2060 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2061 bool isObjCObjectPointerType() const; // pointer to ObjC object
2062 bool isObjCRetainableType() const; // ObjC object or block pointer
2063 bool isObjCLifetimeType() const; // (array of)* retainable type
2064 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2065 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2066 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2067 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2068 // for the common case.
2069 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2070 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2071 bool isObjCQualifiedIdType() const; // id<foo>
2072 bool isObjCQualifiedClassType() const; // Class<foo>
2073 bool isObjCObjectOrInterfaceType() const;
2074 bool isObjCIdType() const; // id
2075 bool isDecltypeType() const;
2076 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2077 /// qualifier?
2078 ///
2079 /// This approximates the answer to the following question: if this
2080 /// translation unit were compiled in ARC, would this type be qualified
2081 /// with __unsafe_unretained?
2082 bool isObjCInertUnsafeUnretainedType() const {
2083 return hasAttr(attr::ObjCInertUnsafeUnretained);
2084 }
2085
2086 /// Whether the type is Objective-C 'id' or a __kindof type of an
2087 /// object type, e.g., __kindof NSView * or __kindof id
2088 /// <NSCopying>.
2089 ///
2090 /// \param bound Will be set to the bound on non-id subtype types,
2091 /// which will be (possibly specialized) Objective-C class type, or
2092 /// null for 'id.
2093 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2094 const ObjCObjectType *&bound) const;
2095
2096 bool isObjCClassType() const; // Class
2097
2098 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2099 /// Class type, e.g., __kindof Class <NSCopying>.
2100 ///
2101 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2102 /// here because Objective-C's type system cannot express "a class
2103 /// object for a subclass of NSFoo".
2104 bool isObjCClassOrClassKindOfType() const;
2105
2106 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2107 bool isObjCSelType() const; // Class
2108 bool isObjCBuiltinType() const; // 'id' or 'Class'
2109 bool isObjCARCBridgableType() const;
2110 bool isCARCBridgableType() const;
2111 bool isTemplateTypeParmType() const; // C++ template type parameter
2112 bool isNullPtrType() const; // C++11 std::nullptr_t
2113 bool isNothrowT() const; // C++ std::nothrow_t
2114 bool isAlignValT() const; // C++17 std::align_val_t
2115 bool isStdByteType() const; // C++17 std::byte
2116 bool isAtomicType() const; // C11 _Atomic()
2117 bool isUndeducedAutoType() const; // C++11 auto or
2118 // C++14 decltype(auto)
2119
2120#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2121 bool is##Id##Type() const;
2122#include "clang/Basic/OpenCLImageTypes.def"
2123
2124 bool isImageType() const; // Any OpenCL image type
2125
2126 bool isSamplerT() const; // OpenCL sampler_t
2127 bool isEventT() const; // OpenCL event_t
2128 bool isClkEventT() const; // OpenCL clk_event_t
2129 bool isQueueT() const; // OpenCL queue_t
2130 bool isReserveIDT() const; // OpenCL reserve_id_t
2131
2132#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2133 bool is##Id##Type() const;
2134#include "clang/Basic/OpenCLExtensionTypes.def"
2135 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2136 bool isOCLIntelSubgroupAVCType() const;
2137 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2138
2139 bool isPipeType() const; // OpenCL pipe type
2140 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2141
2142 /// Determines if this type, which must satisfy
2143 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2144 /// than implicitly __strong.
2145 bool isObjCARCImplicitlyUnretainedType() const;
2146
2147 /// Return the implicit lifetime for this type, which must not be dependent.
2148 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2149
2150 enum ScalarTypeKind {
2151 STK_CPointer,
2152 STK_BlockPointer,
2153 STK_ObjCObjectPointer,
2154 STK_MemberPointer,
2155 STK_Bool,
2156 STK_Integral,
2157 STK_Floating,
2158 STK_IntegralComplex,
2159 STK_FloatingComplex,
2160 STK_FixedPoint
2161 };
2162
2163 /// Given that this is a scalar type, classify it.
2164 ScalarTypeKind getScalarTypeKind() const;
2165
2166 TypeDependence getDependence() const {
2167 return static_cast<TypeDependence>(TypeBits.Dependence);
2168 }
2169
2170 /// Whether this type is a dependent type, meaning that its definition
2171 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2172 bool isDependentType() const {
2173 return getDependence() & TypeDependence::Dependent;
2174 }
2175
2176 /// Determine whether this type is an instantiation-dependent type,
2177 /// meaning that the type involves a template parameter (even if the
2178 /// definition does not actually depend on the type substituted for that
2179 /// template parameter).
2180 bool isInstantiationDependentType() const {
2181 return getDependence() & TypeDependence::Instantiation;
2182 }
2183
2184 /// Determine whether this type is an undeduced type, meaning that
2185 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2186 /// deduced.
2187 bool isUndeducedType() const;
2188
2189 /// Whether this type is a variably-modified type (C99 6.7.5).
2190 bool isVariablyModifiedType() const {
2191 return getDependence() & TypeDependence::VariablyModified;
2192 }
2193
2194 /// Whether this type involves a variable-length array type
2195 /// with a definite size.
2196 bool hasSizedVLAType() const;
2197
2198 /// Whether this type is or contains a local or unnamed type.
2199 bool hasUnnamedOrLocalType() const;
2200
2201 bool isOverloadableType() const;
2202
2203 /// Determine wither this type is a C++ elaborated-type-specifier.
2204 bool isElaboratedTypeSpecifier() const;
2205
2206 bool canDecayToPointerType() const;
2207
2208 /// Whether this type is represented natively as a pointer. This includes
2209 /// pointers, references, block pointers, and Objective-C interface,
2210 /// qualified id, and qualified interface types, as well as nullptr_t.
2211 bool hasPointerRepresentation() const;
2212
2213 /// Whether this type can represent an objective pointer type for the
2214 /// purpose of GC'ability
2215 bool hasObjCPointerRepresentation() const;
2216
2217 /// Determine whether this type has an integer representation
2218 /// of some sort, e.g., it is an integer type or a vector.
2219 bool hasIntegerRepresentation() const;
2220
2221 /// Determine whether this type has an signed integer representation
2222 /// of some sort, e.g., it is an signed integer type or a vector.
2223 bool hasSignedIntegerRepresentation() const;
2224
2225 /// Determine whether this type has an unsigned integer representation
2226 /// of some sort, e.g., it is an unsigned integer type or a vector.
2227 bool hasUnsignedIntegerRepresentation() const;
2228
2229 /// Determine whether this type has a floating-point representation
2230 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2231 bool hasFloatingRepresentation() const;
2232
2233 // Type Checking Functions: Check to see if this type is structurally the
2234 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2235 // the best type we can.
2236 const RecordType *getAsStructureType() const;
2237 /// NOTE: getAs*ArrayType are methods on ASTContext.
2238 const RecordType *getAsUnionType() const;
2239 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2240 const ObjCObjectType *getAsObjCInterfaceType() const;
2241
2242 // The following is a convenience method that returns an ObjCObjectPointerType
2243 // for object declared using an interface.
2244 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2245 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2246 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2247 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2248
2249 /// Retrieves the CXXRecordDecl that this type refers to, either
2250 /// because the type is a RecordType or because it is the injected-class-name
2251 /// type of a class template or class template partial specialization.
2252 CXXRecordDecl *getAsCXXRecordDecl() const;
2253
2254 /// Retrieves the RecordDecl this type refers to.
2255 RecordDecl *getAsRecordDecl() const;
2256
2257 /// Retrieves the TagDecl that this type refers to, either
2258 /// because the type is a TagType or because it is the injected-class-name
2259 /// type of a class template or class template partial specialization.
2260 TagDecl *getAsTagDecl() const;
2261
2262 /// If this is a pointer or reference to a RecordType, return the
2263 /// CXXRecordDecl that the type refers to.
2264 ///
2265 /// If this is not a pointer or reference, or the type being pointed to does
2266 /// not refer to a CXXRecordDecl, returns NULL.
2267 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2268
2269 /// Get the DeducedType whose type will be deduced for a variable with
2270 /// an initializer of this type. This looks through declarators like pointer
2271 /// types, but not through decltype or typedefs.
2272 DeducedType *getContainedDeducedType() const;
2273
2274 /// Get the AutoType whose type will be deduced for a variable with
2275 /// an initializer of this type. This looks through declarators like pointer
2276 /// types, but not through decltype or typedefs.
2277 AutoType *getContainedAutoType() const {
2278 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2279 }
2280
2281 /// Determine whether this type was written with a leading 'auto'
2282 /// corresponding to a trailing return type (possibly for a nested
2283 /// function type within a pointer to function type or similar).
2284 bool hasAutoForTrailingReturnType() const;
2285
2286 /// Member-template getAs<specific type>'. Look through sugar for
2287 /// an instance of \<specific type>. This scheme will eventually
2288 /// replace the specific getAsXXXX methods above.
2289 ///
2290 /// There are some specializations of this member template listed
2291 /// immediately following this class.
2292 template <typename T> const T *getAs() const;
2293
2294 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2295 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2296 /// This is used when you need to walk over sugar nodes that represent some
2297 /// kind of type adjustment from a type that was written as a \<specific type>
2298 /// to another type that is still canonically a \<specific type>.
2299 template <typename T> const T *getAsAdjusted() const;
2300
2301 /// A variant of getAs<> for array types which silently discards
2302 /// qualifiers from the outermost type.
2303 const ArrayType *getAsArrayTypeUnsafe() const;
2304
2305 /// Member-template castAs<specific type>. Look through sugar for
2306 /// the underlying instance of \<specific type>.
2307 ///
2308 /// This method has the same relationship to getAs<T> as cast<T> has
2309 /// to dyn_cast<T>; which is to say, the underlying type *must*
2310 /// have the intended type, and this method will never return null.
2311 template <typename T> const T *castAs() const;
2312
2313 /// A variant of castAs<> for array type which silently discards
2314 /// qualifiers from the outermost type.
2315 const ArrayType *castAsArrayTypeUnsafe() const;
2316
2317 /// Determine whether this type had the specified attribute applied to it
2318 /// (looking through top-level type sugar).
2319 bool hasAttr(attr::Kind AK) const;
2320
2321 /// Get the base element type of this type, potentially discarding type
2322 /// qualifiers. This should never be used when type qualifiers
2323 /// are meaningful.
2324 const Type *getBaseElementTypeUnsafe() const;
2325
2326 /// If this is an array type, return the element type of the array,
2327 /// potentially with type qualifiers missing.
2328 /// This should never be used when type qualifiers are meaningful.
2329 const Type *getArrayElementTypeNoTypeQual() const;
2330
2331 /// If this is a pointer type, return the pointee type.
2332 /// If this is an array type, return the array element type.
2333 /// This should never be used when type qualifiers are meaningful.
2334 const Type *getPointeeOrArrayElementType() const;
2335
2336 /// If this is a pointer, ObjC object pointer, or block
2337 /// pointer, this returns the respective pointee.
2338 QualType getPointeeType() const;
2339
2340 /// Return the specified type with any "sugar" removed from the type,
2341 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2342 const Type *getUnqualifiedDesugaredType() const;
2343
2344 /// More type predicates useful for type checking/promotion
2345 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2346
2347 /// Return true if this is an integer type that is
2348 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2349 /// or an enum decl which has a signed representation.
2350 bool isSignedIntegerType() const;
2351
2352 /// Return true if this is an integer type that is
2353 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2354 /// or an enum decl which has an unsigned representation.
2355 bool isUnsignedIntegerType() const;
2356
2357 /// Determines whether this is an integer type that is signed or an
2358 /// enumeration types whose underlying type is a signed integer type.
2359 bool isSignedIntegerOrEnumerationType() const;
2360
2361 /// Determines whether this is an integer type that is unsigned or an
2362 /// enumeration types whose underlying type is a unsigned integer type.
2363 bool isUnsignedIntegerOrEnumerationType() const;
2364
2365 /// Return true if this is a fixed point type according to
2366 /// ISO/IEC JTC1 SC22 WG14 N1169.
2367 bool isFixedPointType() const;
2368
2369 /// Return true if this is a fixed point or integer type.
2370 bool isFixedPointOrIntegerType() const;
2371
2372 /// Return true if this is a saturated fixed point type according to
2373 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2374 bool isSaturatedFixedPointType() const;
2375
2376 /// Return true if this is a saturated fixed point type according to
2377 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2378 bool isUnsaturatedFixedPointType() const;
2379
2380 /// Return true if this is a fixed point type that is signed according
2381 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2382 bool isSignedFixedPointType() const;
2383
2384 /// Return true if this is a fixed point type that is unsigned according
2385 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2386 bool isUnsignedFixedPointType() const;
2387
2388 /// Return true if this is not a variable sized type,
2389 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2390 /// incomplete types.
2391 bool isConstantSizeType() const;
2392
2393 /// Returns true if this type can be represented by some
2394 /// set of type specifiers.
2395 bool isSpecifierType() const;
2396
2397 /// Determine the linkage of this type.
2398 Linkage getLinkage() const;
2399
2400 /// Determine the visibility of this type.
2401 Visibility getVisibility() const {
2402 return getLinkageAndVisibility().getVisibility();
2403 }
2404
2405 /// Return true if the visibility was explicitly set is the code.
2406 bool isVisibilityExplicit() const {
2407 return getLinkageAndVisibility().isVisibilityExplicit();
2408 }
2409
2410 /// Determine the linkage and visibility of this type.
2411 LinkageInfo getLinkageAndVisibility() const;
2412
2413 /// True if the computed linkage is valid. Used for consistency
2414 /// checking. Should always return true.
2415 bool isLinkageValid() const;
2416
2417 /// Determine the nullability of the given type.
2418 ///
2419 /// Note that nullability is only captured as sugar within the type
2420 /// system, not as part of the canonical type, so nullability will
2421 /// be lost by canonicalization and desugaring.
2422 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2423
2424 /// Determine whether the given type can have a nullability
2425 /// specifier applied to it, i.e., if it is any kind of pointer type.
2426 ///
2427 /// \param ResultIfUnknown The value to return if we don't yet know whether
2428 /// this type can have nullability because it is dependent.
2429 bool canHaveNullability(bool ResultIfUnknown = true) const;
2430
2431 /// Retrieve the set of substitutions required when accessing a member
2432 /// of the Objective-C receiver type that is declared in the given context.
2433 ///
2434 /// \c *this is the type of the object we're operating on, e.g., the
2435 /// receiver for a message send or the base of a property access, and is
2436 /// expected to be of some object or object pointer type.
2437 ///
2438 /// \param dc The declaration context for which we are building up a
2439 /// substitution mapping, which should be an Objective-C class, extension,
2440 /// category, or method within.
2441 ///
2442 /// \returns an array of type arguments that can be substituted for
2443 /// the type parameters of the given declaration context in any type described
2444 /// within that context, or an empty optional to indicate that no
2445 /// substitution is required.
2446 Optional<ArrayRef<QualType>>
2447 getObjCSubstitutions(const DeclContext *dc) const;
2448
2449 /// Determines if this is an ObjC interface type that may accept type
2450 /// parameters.
2451 bool acceptsObjCTypeParams() const;
2452
2453 const char *getTypeClassName() const;
2454
2455 QualType getCanonicalTypeInternal() const {
2456 return CanonicalType;
2457 }
2458
2459 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2460 void dump() const;
2461 void dump(llvm::raw_ostream &OS) const;
2462};
2463
2464/// This will check for a TypedefType by removing any existing sugar
2465/// until it reaches a TypedefType or a non-sugared type.
2466template <> const TypedefType *Type::getAs() const;
2467
2468/// This will check for a TemplateSpecializationType by removing any
2469/// existing sugar until it reaches a TemplateSpecializationType or a
2470/// non-sugared type.
2471template <> const TemplateSpecializationType *Type::getAs() const;
2472
2473/// This will check for an AttributedType by removing any existing sugar
2474/// until it reaches an AttributedType or a non-sugared type.
2475template <> const AttributedType *Type::getAs() const;
2476
2477// We can do canonical leaf types faster, because we don't have to
2478// worry about preserving child type decoration.
2479#define TYPE(Class, Base)
2480#define LEAF_TYPE(Class) \
2481template <> inline const Class##Type *Type::getAs() const { \
2482 return dyn_cast<Class##Type>(CanonicalType); \
2483} \
2484template <> inline const Class##Type *Type::castAs() const { \
2485 return cast<Class##Type>(CanonicalType); \
2486}
2487#include "clang/AST/TypeNodes.inc"
2488
2489/// This class is used for builtin types like 'int'. Builtin
2490/// types are always canonical and have a literal name field.
2491class BuiltinType : public Type {
2492public:
2493 enum Kind {
2494// OpenCL image types
2495#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2496#include "clang/Basic/OpenCLImageTypes.def"
2497// OpenCL extension types
2498#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2499#include "clang/Basic/OpenCLExtensionTypes.def"
2500// SVE Types
2501#define SVE_TYPE(Name, Id, SingletonId) Id,
2502#include "clang/Basic/AArch64SVEACLETypes.def"
2503// All other builtin types
2504#define BUILTIN_TYPE(Id, SingletonId) Id,
2505#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2506#include "clang/AST/BuiltinTypes.def"
2507 };
2508
2509private:
2510 friend class ASTContext; // ASTContext creates these.
2511
2512 BuiltinType(Kind K)
2513 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2514 /*InstantiationDependent=*/(K == Dependent),
2515 /*VariablyModified=*/false,
2516 /*Unexpanded parameter pack=*/false) {
2517 BuiltinTypeBits.Kind = K;
2518 }
2519
2520public:
2521 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2522 StringRef getName(const PrintingPolicy &Policy) const;
2523
2524 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2525 // The StringRef is null-terminated.
2526 StringRef str = getName(Policy);
2527 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 2527, __PRETTY_FUNCTION__))
;
2528 return str.data();
2529 }
2530
2531 bool isSugared() const { return false; }
2532 QualType desugar() const { return QualType(this, 0); }
2533
2534 bool isInteger() const {
2535 return getKind() >= Bool && getKind() <= Int128;
2536 }
2537
2538 bool isSignedInteger() const {
2539 return getKind() >= Char_S && getKind() <= Int128;
2540 }
2541
2542 bool isUnsignedInteger() const {
2543 return getKind() >= Bool && getKind() <= UInt128;
2544 }
2545
2546 bool isFloatingPoint() const {
2547 return getKind() >= Half && getKind() <= Float128;
2548 }
2549
2550 /// Determines whether the given kind corresponds to a placeholder type.
2551 static bool isPlaceholderTypeKind(Kind K) {
2552 return K >= Overload;
2553 }
2554
2555 /// Determines whether this type is a placeholder type, i.e. a type
2556 /// which cannot appear in arbitrary positions in a fully-formed
2557 /// expression.
2558 bool isPlaceholderType() const {
2559 return isPlaceholderTypeKind(getKind());
2560 }
2561
2562 /// Determines whether this type is a placeholder type other than
2563 /// Overload. Most placeholder types require only syntactic
2564 /// information about their context in order to be resolved (e.g.
2565 /// whether it is a call expression), which means they can (and
2566 /// should) be resolved in an earlier "phase" of analysis.
2567 /// Overload expressions sometimes pick up further information
2568 /// from their context, like whether the context expects a
2569 /// specific function-pointer type, and so frequently need
2570 /// special treatment.
2571 bool isNonOverloadPlaceholderType() const {
2572 return getKind() > Overload;
2573 }
2574
2575 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2576};
2577
2578/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2579/// types (_Complex float etc) as well as the GCC integer complex extensions.
2580class ComplexType : public Type, public llvm::FoldingSetNode {
2581 friend class ASTContext; // ASTContext creates these.
2582
2583 QualType ElementType;
2584
2585 ComplexType(QualType Element, QualType CanonicalPtr)
2586 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2587 Element->isInstantiationDependentType(),
2588 Element->isVariablyModifiedType(),
2589 Element->containsUnexpandedParameterPack()),
2590 ElementType(Element) {}
2591
2592public:
2593 QualType getElementType() const { return ElementType; }
2594
2595 bool isSugared() const { return false; }
2596 QualType desugar() const { return QualType(this, 0); }
2597
2598 void Profile(llvm::FoldingSetNodeID &ID) {
2599 Profile(ID, getElementType());
2600 }
2601
2602 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2603 ID.AddPointer(Element.getAsOpaquePtr());
2604 }
2605
2606 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2607};
2608
2609/// Sugar for parentheses used when specifying types.
2610class ParenType : public Type, public llvm::FoldingSetNode {
2611 friend class ASTContext; // ASTContext creates these.
2612
2613 QualType Inner;
2614
2615 ParenType(QualType InnerType, QualType CanonType)
2616 : Type(Paren, CanonType, InnerType->isDependentType(),
2617 InnerType->isInstantiationDependentType(),
2618 InnerType->isVariablyModifiedType(),
2619 InnerType->containsUnexpandedParameterPack()),
2620 Inner(InnerType) {}
2621
2622public:
2623 QualType getInnerType() const { return Inner; }
2624
2625 bool isSugared() const { return true; }
2626 QualType desugar() const { return getInnerType(); }
2627
2628 void Profile(llvm::FoldingSetNodeID &ID) {
2629 Profile(ID, getInnerType());
2630 }
2631
2632 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2633 Inner.Profile(ID);
2634 }
2635
2636 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2637};
2638
2639/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2640class PointerType : public Type, public llvm::FoldingSetNode {
2641 friend class ASTContext; // ASTContext creates these.
2642
2643 QualType PointeeType;
2644
2645 PointerType(QualType Pointee, QualType CanonicalPtr)
2646 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2647 Pointee->isInstantiationDependentType(),
2648 Pointee->isVariablyModifiedType(),
2649 Pointee->containsUnexpandedParameterPack()),
2650 PointeeType(Pointee) {}
2651
2652public:
2653 QualType getPointeeType() const { return PointeeType; }
2654
2655 /// Returns true if address spaces of pointers overlap.
2656 /// OpenCL v2.0 defines conversion rules for pointers to different
2657 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2658 /// address spaces.
2659 /// CL1.1 or CL1.2:
2660 /// address spaces overlap iff they are they same.
2661 /// CL2.0 adds:
2662 /// __generic overlaps with any address space except for __constant.
2663 bool isAddressSpaceOverlapping(const PointerType &other) const {
2664 Qualifiers thisQuals = PointeeType.getQualifiers();
2665 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2666 // Address spaces overlap if at least one of them is a superset of another
2667 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2668 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2669 }
2670
2671 bool isSugared() const { return false; }
2672 QualType desugar() const { return QualType(this, 0); }
2673
2674 void Profile(llvm::FoldingSetNodeID &ID) {
2675 Profile(ID, getPointeeType());
2676 }
2677
2678 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2679 ID.AddPointer(Pointee.getAsOpaquePtr());
2680 }
2681
2682 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2683};
2684
2685/// Represents a type which was implicitly adjusted by the semantic
2686/// engine for arbitrary reasons. For example, array and function types can
2687/// decay, and function types can have their calling conventions adjusted.
2688class AdjustedType : public Type, public llvm::FoldingSetNode {
2689 QualType OriginalTy;
2690 QualType AdjustedTy;
2691
2692protected:
2693 friend class ASTContext; // ASTContext creates these.
2694
2695 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2696 QualType CanonicalPtr)
2697 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2698 OriginalTy->isInstantiationDependentType(),
2699 OriginalTy->isVariablyModifiedType(),
2700 OriginalTy->containsUnexpandedParameterPack()),
2701 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2702
2703public:
2704 QualType getOriginalType() const { return OriginalTy; }
2705 QualType getAdjustedType() const { return AdjustedTy; }
2706
2707 bool isSugared() const { return true; }
2708 QualType desugar() const { return AdjustedTy; }
2709
2710 void Profile(llvm::FoldingSetNodeID &ID) {
2711 Profile(ID, OriginalTy, AdjustedTy);
2712 }
2713
2714 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2715 ID.AddPointer(Orig.getAsOpaquePtr());
2716 ID.AddPointer(New.getAsOpaquePtr());
2717 }
2718
2719 static bool classof(const Type *T) {
2720 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2721 }
2722};
2723
2724/// Represents a pointer type decayed from an array or function type.
2725class DecayedType : public AdjustedType {
2726 friend class ASTContext; // ASTContext creates these.
2727
2728 inline
2729 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2730
2731public:
2732 QualType getDecayedType() const { return getAdjustedType(); }
2733
2734 inline QualType getPointeeType() const;
2735
2736 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2737};
2738
2739/// Pointer to a block type.
2740/// This type is to represent types syntactically represented as
2741/// "void (^)(int)", etc. Pointee is required to always be a function type.
2742class BlockPointerType : public Type, public llvm::FoldingSetNode {
2743 friend class ASTContext; // ASTContext creates these.
2744
2745 // Block is some kind of pointer type
2746 QualType PointeeType;
2747
2748 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2749 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2750 Pointee->isInstantiationDependentType(),
2751 Pointee->isVariablyModifiedType(),
2752 Pointee->containsUnexpandedParameterPack()),
2753 PointeeType(Pointee) {}
2754
2755public:
2756 // Get the pointee type. Pointee is required to always be a function type.
2757 QualType getPointeeType() const { return PointeeType; }
2758
2759 bool isSugared() const { return false; }
2760 QualType desugar() const { return QualType(this, 0); }
2761
2762 void Profile(llvm::FoldingSetNodeID &ID) {
2763 Profile(ID, getPointeeType());
2764 }
2765
2766 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2767 ID.AddPointer(Pointee.getAsOpaquePtr());
2768 }
2769
2770 static bool classof(const Type *T) {
2771 return T->getTypeClass() == BlockPointer;
2772 }
2773};
2774
2775/// Base for LValueReferenceType and RValueReferenceType
2776class ReferenceType : public Type, public llvm::FoldingSetNode {
2777 QualType PointeeType;
2778
2779protected:
2780 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2781 bool SpelledAsLValue)
2782 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2783 Referencee->isInstantiationDependentType(),
2784 Referencee->isVariablyModifiedType(),
2785 Referencee->containsUnexpandedParameterPack()),
2786 PointeeType(Referencee) {
2787 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2788 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2789 }
2790
2791public:
2792 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2793 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2794
2795 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2796
2797 QualType getPointeeType() const {
2798 // FIXME: this might strip inner qualifiers; okay?
2799 const ReferenceType *T = this;
2800 while (T->isInnerRef())
2801 T = T->PointeeType->castAs<ReferenceType>();
2802 return T->PointeeType;
2803 }
2804
2805 void Profile(llvm::FoldingSetNodeID &ID) {
2806 Profile(ID, PointeeType, isSpelledAsLValue());
2807 }
2808
2809 static void Profile(llvm::FoldingSetNodeID &ID,
2810 QualType Referencee,
2811 bool SpelledAsLValue) {
2812 ID.AddPointer(Referencee.getAsOpaquePtr());
2813 ID.AddBoolean(SpelledAsLValue);
2814 }
2815
2816 static bool classof(const Type *T) {
2817 return T->getTypeClass() == LValueReference ||
2818 T->getTypeClass() == RValueReference;
2819 }
2820};
2821
2822/// An lvalue reference type, per C++11 [dcl.ref].
2823class LValueReferenceType : public ReferenceType {
2824 friend class ASTContext; // ASTContext creates these
2825
2826 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2827 bool SpelledAsLValue)
2828 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2829 SpelledAsLValue) {}
2830
2831public:
2832 bool isSugared() const { return false; }
2833 QualType desugar() const { return QualType(this, 0); }
2834
2835 static bool classof(const Type *T) {
2836 return T->getTypeClass() == LValueReference;
2837 }
2838};
2839
2840/// An rvalue reference type, per C++11 [dcl.ref].
2841class RValueReferenceType : public ReferenceType {
2842 friend class ASTContext; // ASTContext creates these
2843
2844 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2845 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2846
2847public:
2848 bool isSugared() const { return false; }
2849 QualType desugar() const { return QualType(this, 0); }
2850
2851 static bool classof(const Type *T) {
2852 return T->getTypeClass() == RValueReference;
2853 }
2854};
2855
2856/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2857///
2858/// This includes both pointers to data members and pointer to member functions.
2859class MemberPointerType : public Type, public llvm::FoldingSetNode {
2860 friend class ASTContext; // ASTContext creates these.
2861
2862 QualType PointeeType;
2863
2864 /// The class of which the pointee is a member. Must ultimately be a
2865 /// RecordType, but could be a typedef or a template parameter too.
2866 const Type *Class;
2867
2868 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2869 : Type(MemberPointer, CanonicalPtr,
2870 Cls->isDependentType() || Pointee->isDependentType(),
2871 (Cls->isInstantiationDependentType() ||
2872 Pointee->isInstantiationDependentType()),
2873 Pointee->isVariablyModifiedType(),
2874 (Cls->containsUnexpandedParameterPack() ||
2875 Pointee->containsUnexpandedParameterPack())),
2876 PointeeType(Pointee), Class(Cls) {}
2877
2878public:
2879 QualType getPointeeType() const { return PointeeType; }
2880
2881 /// Returns true if the member type (i.e. the pointee type) is a
2882 /// function type rather than a data-member type.
2883 bool isMemberFunctionPointer() const {
2884 return PointeeType->isFunctionProtoType();
2885 }
2886
2887 /// Returns true if the member type (i.e. the pointee type) is a
2888 /// data type rather than a function type.
2889 bool isMemberDataPointer() const {
2890 return !PointeeType->isFunctionProtoType();
2891 }
2892
2893 const Type *getClass() const { return Class; }
2894 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2895
2896 bool isSugared() const { return false; }
2897 QualType desugar() const { return QualType(this, 0); }
2898
2899 void Profile(llvm::FoldingSetNodeID &ID) {
2900 Profile(ID, getPointeeType(), getClass());
2901 }
2902
2903 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2904 const Type *Class) {
2905 ID.AddPointer(Pointee.getAsOpaquePtr());
2906 ID.AddPointer(Class);
2907 }
2908
2909 static bool classof(const Type *T) {
2910 return T->getTypeClass() == MemberPointer;
2911 }
2912};
2913
2914/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2915class ArrayType : public Type, public llvm::FoldingSetNode {
2916public:
2917 /// Capture whether this is a normal array (e.g. int X[4])
2918 /// an array with a static size (e.g. int X[static 4]), or an array
2919 /// with a star size (e.g. int X[*]).
2920 /// 'static' is only allowed on function parameters.
2921 enum ArraySizeModifier {
2922 Normal, Static, Star
2923 };
2924
2925private:
2926 /// The element type of the array.
2927 QualType ElementType;
2928
2929protected:
2930 friend class ASTContext; // ASTContext creates these.
2931
2932 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2933 unsigned tq, const Expr *sz = nullptr);
2934
2935public:
2936 QualType getElementType() const { return ElementType; }
2937
2938 ArraySizeModifier getSizeModifier() const {
2939 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2940 }
2941
2942 Qualifiers getIndexTypeQualifiers() const {
2943 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2944 }
2945
2946 unsigned getIndexTypeCVRQualifiers() const {
2947 return ArrayTypeBits.IndexTypeQuals;
2948 }
2949
2950 static bool classof(const Type *T) {
2951 return T->getTypeClass() == ConstantArray ||
2952 T->getTypeClass() == VariableArray ||
2953 T->getTypeClass() == IncompleteArray ||
2954 T->getTypeClass() == DependentSizedArray;
2955 }
2956};
2957
2958/// Represents the canonical version of C arrays with a specified constant size.
2959/// For example, the canonical type for 'int A[4 + 4*100]' is a
2960/// ConstantArrayType where the element type is 'int' and the size is 404.
2961class ConstantArrayType final
2962 : public ArrayType,
2963 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2964 friend class ASTContext; // ASTContext creates these.
2965 friend TrailingObjects;
2966
2967 llvm::APInt Size; // Allows us to unique the type.
2968
2969 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2970 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2971 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2972 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2973 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2974 assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size"
) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 2974, __PRETTY_FUNCTION__))
;
2975 *getTrailingObjects<const Expr*>() = sz;
2976 }
2977 }
2978
2979 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2980 return ConstantArrayTypeBits.HasStoredSizeExpr;
2981 }
2982
2983public:
2984 const llvm::APInt &getSize() const { return Size; }
2985 const Expr *getSizeExpr() const {
2986 return ConstantArrayTypeBits.HasStoredSizeExpr
2987 ? *getTrailingObjects<const Expr *>()
2988 : nullptr;
2989 }
2990 bool isSugared() const { return false; }
2991 QualType desugar() const { return QualType(this, 0); }
2992
2993 /// Determine the number of bits required to address a member of
2994 // an array with the given element type and number of elements.
2995 static unsigned getNumAddressingBits(const ASTContext &Context,
2996 QualType ElementType,
2997 const llvm::APInt &NumElements);
2998
2999 /// Determine the maximum number of active bits that an array's size
3000 /// can require, which limits the maximum size of the array.
3001 static unsigned getMaxSizeBits(const ASTContext &Context);
3002
3003 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3004 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
3005 getSizeModifier(), getIndexTypeCVRQualifiers());
3006 }
3007
3008 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
3009 QualType ET, const llvm::APInt &ArraySize,
3010 const Expr *SizeExpr, ArraySizeModifier SizeMod,
3011 unsigned TypeQuals);
3012
3013 static bool classof(const Type *T) {
3014 return T->getTypeClass() == ConstantArray;
3015 }
3016};
3017
3018/// Represents a C array with an unspecified size. For example 'int A[]' has
3019/// an IncompleteArrayType where the element type is 'int' and the size is
3020/// unspecified.
3021class IncompleteArrayType : public ArrayType {
3022 friend class ASTContext; // ASTContext creates these.
3023
3024 IncompleteArrayType(QualType et, QualType can,
3025 ArraySizeModifier sm, unsigned tq)
3026 : ArrayType(IncompleteArray, et, can, sm, tq) {}
3027
3028public:
3029 friend class StmtIteratorBase;
3030
3031 bool isSugared() const { return false; }
3032 QualType desugar() const { return QualType(this, 0); }
3033
3034 static bool classof(const Type *T) {
3035 return T->getTypeClass() == IncompleteArray;
3036 }
3037
3038 void Profile(llvm::FoldingSetNodeID &ID) {
3039 Profile(ID, getElementType(), getSizeModifier(),
3040 getIndexTypeCVRQualifiers());
3041 }
3042
3043 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3044 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3045 ID.AddPointer(ET.getAsOpaquePtr());
3046 ID.AddInteger(SizeMod);
3047 ID.AddInteger(TypeQuals);
3048 }
3049};
3050
3051/// Represents a C array with a specified size that is not an
3052/// integer-constant-expression. For example, 'int s[x+foo()]'.
3053/// Since the size expression is an arbitrary expression, we store it as such.
3054///
3055/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3056/// should not be: two lexically equivalent variable array types could mean
3057/// different things, for example, these variables do not have the same type
3058/// dynamically:
3059///
3060/// void foo(int x) {
3061/// int Y[x];
3062/// ++x;
3063/// int Z[x];
3064/// }
3065class VariableArrayType : public ArrayType {
3066 friend class ASTContext; // ASTContext creates these.
3067
3068 /// An assignment-expression. VLA's are only permitted within
3069 /// a function block.
3070 Stmt *SizeExpr;
3071
3072 /// The range spanned by the left and right array brackets.
3073 SourceRange Brackets;
3074
3075 VariableArrayType(QualType et, QualType can, Expr *e,
3076 ArraySizeModifier sm, unsigned tq,
3077 SourceRange brackets)
3078 : ArrayType(VariableArray, et, can, sm, tq, e),
3079 SizeExpr((Stmt*) e), Brackets(brackets) {}
3080
3081public:
3082 friend class StmtIteratorBase;
3083
3084 Expr *getSizeExpr() const {
3085 // We use C-style casts instead of cast<> here because we do not wish
3086 // to have a dependency of Type.h on Stmt.h/Expr.h.
3087 return (Expr*) SizeExpr;
3088 }
3089
3090 SourceRange getBracketsRange() const { return Brackets; }
3091 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3092 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3093
3094 bool isSugared() const { return false; }
3095 QualType desugar() const { return QualType(this, 0); }
3096
3097 static bool classof(const Type *T) {
3098 return T->getTypeClass() == VariableArray;
3099 }
3100
3101 void Profile(llvm::FoldingSetNodeID &ID) {
3102 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3102)
;
3103 }
3104};
3105
3106/// Represents an array type in C++ whose size is a value-dependent expression.
3107///
3108/// For example:
3109/// \code
3110/// template<typename T, int Size>
3111/// class array {
3112/// T data[Size];
3113/// };
3114/// \endcode
3115///
3116/// For these types, we won't actually know what the array bound is
3117/// until template instantiation occurs, at which point this will
3118/// become either a ConstantArrayType or a VariableArrayType.
3119class DependentSizedArrayType : public ArrayType {
3120 friend class ASTContext; // ASTContext creates these.
3121
3122 const ASTContext &Context;
3123
3124 /// An assignment expression that will instantiate to the
3125 /// size of the array.
3126 ///
3127 /// The expression itself might be null, in which case the array
3128 /// type will have its size deduced from an initializer.
3129 Stmt *SizeExpr;
3130
3131 /// The range spanned by the left and right array brackets.
3132 SourceRange Brackets;
3133
3134 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3135 Expr *e, ArraySizeModifier sm, unsigned tq,
3136 SourceRange brackets);
3137
3138public:
3139 friend class StmtIteratorBase;
3140
3141 Expr *getSizeExpr() const {
3142 // We use C-style casts instead of cast<> here because we do not wish
3143 // to have a dependency of Type.h on Stmt.h/Expr.h.
3144 return (Expr*) SizeExpr;
3145 }
3146
3147 SourceRange getBracketsRange() const { return Brackets; }
3148 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3149 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3150
3151 bool isSugared() const { return false; }
3152 QualType desugar() const { return QualType(this, 0); }
3153
3154 static bool classof(const Type *T) {
3155 return T->getTypeClass() == DependentSizedArray;
3156 }
3157
3158 void Profile(llvm::FoldingSetNodeID &ID) {
3159 Profile(ID, Context, getElementType(),
3160 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3161 }
3162
3163 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3164 QualType ET, ArraySizeModifier SizeMod,
3165 unsigned TypeQuals, Expr *E);
3166};
3167
3168/// Represents an extended address space qualifier where the input address space
3169/// value is dependent. Non-dependent address spaces are not represented with a
3170/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3171///
3172/// For example:
3173/// \code
3174/// template<typename T, int AddrSpace>
3175/// class AddressSpace {
3176/// typedef T __attribute__((address_space(AddrSpace))) type;
3177/// }
3178/// \endcode
3179class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3180 friend class ASTContext;
3181
3182 const ASTContext &Context;
3183 Expr *AddrSpaceExpr;
3184 QualType PointeeType;
3185 SourceLocation loc;
3186
3187 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3188 QualType can, Expr *AddrSpaceExpr,
3189 SourceLocation loc);
3190
3191public:
3192 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3193 QualType getPointeeType() const { return PointeeType; }
3194 SourceLocation getAttributeLoc() const { return loc; }
3195
3196 bool isSugared() const { return false; }
3197 QualType desugar() const { return QualType(this, 0); }
3198
3199 static bool classof(const Type *T) {
3200 return T->getTypeClass() == DependentAddressSpace;
3201 }
3202
3203 void Profile(llvm::FoldingSetNodeID &ID) {
3204 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3205 }
3206
3207 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3208 QualType PointeeType, Expr *AddrSpaceExpr);
3209};
3210
3211/// Represents an extended vector type where either the type or size is
3212/// dependent.
3213///
3214/// For example:
3215/// \code
3216/// template<typename T, int Size>
3217/// class vector {
3218/// typedef T __attribute__((ext_vector_type(Size))) type;
3219/// }
3220/// \endcode
3221class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3222 friend class ASTContext;
3223
3224 const ASTContext &Context;
3225 Expr *SizeExpr;
3226
3227 /// The element type of the array.
3228 QualType ElementType;
3229
3230 SourceLocation loc;
3231
3232 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3233 QualType can, Expr *SizeExpr, SourceLocation loc);
3234
3235public:
3236 Expr *getSizeExpr() const { return SizeExpr; }
3237 QualType getElementType() const { return ElementType; }
3238 SourceLocation getAttributeLoc() const { return loc; }
3239
3240 bool isSugared() const { return false; }
3241 QualType desugar() const { return QualType(this, 0); }
3242
3243 static bool classof(const Type *T) {
3244 return T->getTypeClass() == DependentSizedExtVector;
3245 }
3246
3247 void Profile(llvm::FoldingSetNodeID &ID) {
3248 Profile(ID, Context, getElementType(), getSizeExpr());
3249 }
3250
3251 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3252 QualType ElementType, Expr *SizeExpr);
3253};
3254
3255
3256/// Represents a GCC generic vector type. This type is created using
3257/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3258/// bytes; or from an Altivec __vector or vector declaration.
3259/// Since the constructor takes the number of vector elements, the
3260/// client is responsible for converting the size into the number of elements.
3261class VectorType : public Type, public llvm::FoldingSetNode {
3262public:
3263 enum VectorKind {
3264 /// not a target-specific vector type
3265 GenericVector,
3266
3267 /// is AltiVec vector
3268 AltiVecVector,
3269
3270 /// is AltiVec 'vector Pixel'
3271 AltiVecPixel,
3272
3273 /// is AltiVec 'vector bool ...'
3274 AltiVecBool,
3275
3276 /// is ARM Neon vector
3277 NeonVector,
3278
3279 /// is ARM Neon polynomial vector
3280 NeonPolyVector
3281 };
3282
3283protected:
3284 friend class ASTContext; // ASTContext creates these.
3285
3286 /// The element type of the vector.
3287 QualType ElementType;
3288
3289 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3290 VectorKind vecKind);
3291
3292 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3293 QualType canonType, VectorKind vecKind);
3294
3295public:
3296 QualType getElementType() const { return ElementType; }
3297 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3298
3299 static bool isVectorSizeTooLarge(unsigned NumElements) {
3300 return NumElements > VectorTypeBitfields::MaxNumElements;
3301 }
3302
3303 bool isSugared() const { return false; }
3304 QualType desugar() const { return QualType(this, 0); }
3305
3306 VectorKind getVectorKind() const {
3307 return VectorKind(VectorTypeBits.VecKind);
3308 }
3309
3310 void Profile(llvm::FoldingSetNodeID &ID) {
3311 Profile(ID, getElementType(), getNumElements(),
3312 getTypeClass(), getVectorKind());
3313 }
3314
3315 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3316 unsigned NumElements, TypeClass TypeClass,
3317 VectorKind VecKind) {
3318 ID.AddPointer(ElementType.getAsOpaquePtr());
3319 ID.AddInteger(NumElements);
3320 ID.AddInteger(TypeClass);
3321 ID.AddInteger(VecKind);
3322 }
3323
3324 static bool classof(const Type *T) {
3325 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3326 }
3327};
3328
3329/// Represents a vector type where either the type or size is dependent.
3330////
3331/// For example:
3332/// \code
3333/// template<typename T, int Size>
3334/// class vector {
3335/// typedef T __attribute__((vector_size(Size))) type;
3336/// }
3337/// \endcode
3338class DependentVectorType : public Type, public llvm::FoldingSetNode {
3339 friend class ASTContext;
3340
3341 const ASTContext &Context;
3342 QualType ElementType;
3343 Expr *SizeExpr;
3344 SourceLocation Loc;
3345
3346 DependentVectorType(const ASTContext &Context, QualType ElementType,
3347 QualType CanonType, Expr *SizeExpr,
3348 SourceLocation Loc, VectorType::VectorKind vecKind);
3349
3350public:
3351 Expr *getSizeExpr() const { return SizeExpr; }
3352 QualType getElementType() const { return ElementType; }
3353 SourceLocation getAttributeLoc() const { return Loc; }
3354 VectorType::VectorKind getVectorKind() const {
3355 return VectorType::VectorKind(VectorTypeBits.VecKind);
3356 }
3357
3358 bool isSugared() const { return false; }
3359 QualType desugar() const { return QualType(this, 0); }
3360
3361 static bool classof(const Type *T) {
3362 return T->getTypeClass() == DependentVector;
3363 }
3364
3365 void Profile(llvm::FoldingSetNodeID &ID) {
3366 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3367 }
3368
3369 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3370 QualType ElementType, const Expr *SizeExpr,
3371 VectorType::VectorKind VecKind);
3372};
3373
3374/// ExtVectorType - Extended vector type. This type is created using
3375/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3376/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3377/// class enables syntactic extensions, like Vector Components for accessing
3378/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3379/// Shading Language).
3380class ExtVectorType : public VectorType {
3381 friend class ASTContext; // ASTContext creates these.
3382
3383 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3384 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3385
3386public:
3387 static int getPointAccessorIdx(char c) {
3388 switch (c) {
3389 default: return -1;
3390 case 'x': case 'r': return 0;
3391 case 'y': case 'g': return 1;
3392 case 'z': case 'b': return 2;
3393 case 'w': case 'a': return 3;
3394 }
3395 }
3396
3397 static int getNumericAccessorIdx(char c) {
3398 switch (c) {
3399 default: return -1;
3400 case '0': return 0;
3401 case '1': return 1;
3402 case '2': return 2;
3403 case '3': return 3;
3404 case '4': return 4;
3405 case '5': return 5;
3406 case '6': return 6;
3407 case '7': return 7;
3408 case '8': return 8;
3409 case '9': return 9;
3410 case 'A':
3411 case 'a': return 10;
3412 case 'B':
3413 case 'b': return 11;
3414 case 'C':
3415 case 'c': return 12;
3416 case 'D':
3417 case 'd': return 13;
3418 case 'E':
3419 case 'e': return 14;
3420 case 'F':
3421 case 'f': return 15;
3422 }
3423 }
3424
3425 static int getAccessorIdx(char c, bool isNumericAccessor) {
3426 if (isNumericAccessor)
3427 return getNumericAccessorIdx(c);
3428 else
3429 return getPointAccessorIdx(c);
3430 }
3431
3432 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3433 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3434 return unsigned(idx-1) < getNumElements();
3435 return false;
3436 }
3437
3438 bool isSugared() const { return false; }
3439 QualType desugar() const { return QualType(this, 0); }
3440
3441 static bool classof(const Type *T) {
3442 return T->getTypeClass() == ExtVector;
3443 }
3444};
3445
3446/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3447/// class of FunctionNoProtoType and FunctionProtoType.
3448class FunctionType : public Type {
3449 // The type returned by the function.
3450 QualType ResultType;
3451
3452public:
3453 /// Interesting information about a specific parameter that can't simply
3454 /// be reflected in parameter's type. This is only used by FunctionProtoType
3455 /// but is in FunctionType to make this class available during the
3456 /// specification of the bases of FunctionProtoType.
3457 ///
3458 /// It makes sense to model language features this way when there's some
3459 /// sort of parameter-specific override (such as an attribute) that
3460 /// affects how the function is called. For example, the ARC ns_consumed
3461 /// attribute changes whether a parameter is passed at +0 (the default)
3462 /// or +1 (ns_consumed). This must be reflected in the function type,
3463 /// but isn't really a change to the parameter type.
3464 ///
3465 /// One serious disadvantage of modelling language features this way is
3466 /// that they generally do not work with language features that attempt
3467 /// to destructure types. For example, template argument deduction will
3468 /// not be able to match a parameter declared as
3469 /// T (*)(U)
3470 /// against an argument of type
3471 /// void (*)(__attribute__((ns_consumed)) id)
3472 /// because the substitution of T=void, U=id into the former will
3473 /// not produce the latter.
3474 class ExtParameterInfo {
3475 enum {
3476 ABIMask = 0x0F,
3477 IsConsumed = 0x10,
3478 HasPassObjSize = 0x20,
3479 IsNoEscape = 0x40,
3480 };
3481 unsigned char Data = 0;
3482
3483 public:
3484 ExtParameterInfo() = default;
3485
3486 /// Return the ABI treatment of this parameter.
3487 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3488 ExtParameterInfo withABI(ParameterABI kind) const {
3489 ExtParameterInfo copy = *this;
3490 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3491 return copy;
3492 }
3493
3494 /// Is this parameter considered "consumed" by Objective-C ARC?
3495 /// Consumed parameters must have retainable object type.
3496 bool isConsumed() const { return (Data & IsConsumed); }
3497 ExtParameterInfo withIsConsumed(bool consumed) const {
3498 ExtParameterInfo copy = *this;
3499 if (consumed)
3500 copy.Data |= IsConsumed;
3501 else
3502 copy.Data &= ~IsConsumed;
3503 return copy;
3504 }
3505
3506 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3507 ExtParameterInfo withHasPassObjectSize() const {
3508 ExtParameterInfo Copy = *this;
3509 Copy.Data |= HasPassObjSize;
3510 return Copy;
3511 }
3512
3513 bool isNoEscape() const { return Data & IsNoEscape; }
3514 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3515 ExtParameterInfo Copy = *this;
3516 if (NoEscape)
3517 Copy.Data |= IsNoEscape;
3518 else
3519 Copy.Data &= ~IsNoEscape;
3520 return Copy;
3521 }
3522
3523 unsigned char getOpaqueValue() const { return Data; }
3524 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3525 ExtParameterInfo result;
3526 result.Data = data;
3527 return result;
3528 }
3529
3530 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3531 return lhs.Data == rhs.Data;
3532 }
3533
3534 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3535 return lhs.Data != rhs.Data;
3536 }
3537 };
3538
3539 /// A class which abstracts out some details necessary for
3540 /// making a call.
3541 ///
3542 /// It is not actually used directly for storing this information in
3543 /// a FunctionType, although FunctionType does currently use the
3544 /// same bit-pattern.
3545 ///
3546 // If you add a field (say Foo), other than the obvious places (both,
3547 // constructors, compile failures), what you need to update is
3548 // * Operator==
3549 // * getFoo
3550 // * withFoo
3551 // * functionType. Add Foo, getFoo.
3552 // * ASTContext::getFooType
3553 // * ASTContext::mergeFunctionTypes
3554 // * FunctionNoProtoType::Profile
3555 // * FunctionProtoType::Profile
3556 // * TypePrinter::PrintFunctionProto
3557 // * AST read and write
3558 // * Codegen
3559 class ExtInfo {
3560 friend class FunctionType;
3561
3562 // Feel free to rearrange or add bits, but if you go over 12,
3563 // you'll need to adjust both the Bits field below and
3564 // Type::FunctionTypeBitfields.
3565
3566 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3567 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3568 //
3569 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3570 enum { CallConvMask = 0x1F };
3571 enum { NoReturnMask = 0x20 };
3572 enum { ProducesResultMask = 0x40 };
3573 enum { NoCallerSavedRegsMask = 0x80 };
3574 enum { NoCfCheckMask = 0x800 };
3575 enum {
3576 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3577 NoCallerSavedRegsMask | NoCfCheckMask),
3578 RegParmOffset = 8
3579 }; // Assumed to be the last field
3580 uint16_t Bits = CC_C;
3581
3582 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3583
3584 public:
3585 // Constructor with no defaults. Use this when you know that you
3586 // have all the elements (when reading an AST file for example).
3587 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3588 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3589 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3589, __PRETTY_FUNCTION__))
;
3590 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3591 (producesResult ? ProducesResultMask : 0) |
3592 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3593 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3594 (NoCfCheck ? NoCfCheckMask : 0);
3595 }
3596
3597 // Constructor with all defaults. Use when for example creating a
3598 // function known to use defaults.
3599 ExtInfo() = default;
3600
3601 // Constructor with just the calling convention, which is an important part
3602 // of the canonical type.
3603 ExtInfo(CallingConv CC) : Bits(CC) {}
3604
3605 bool getNoReturn() const { return Bits & NoReturnMask; }
3606 bool getProducesResult() const { return Bits & ProducesResultMask; }
3607 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3608 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3609 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3610
3611 unsigned getRegParm() const {
3612 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3613 if (RegParm > 0)
3614 --RegParm;
3615 return RegParm;
3616 }
3617
3618 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3619
3620 bool operator==(ExtInfo Other) const {
3621 return Bits == Other.Bits;
3622 }
3623 bool operator!=(ExtInfo Other) const {
3624 return Bits != Other.Bits;
3625 }
3626
3627 // Note that we don't have setters. That is by design, use
3628 // the following with methods instead of mutating these objects.
3629
3630 ExtInfo withNoReturn(bool noReturn) const {
3631 if (noReturn)
3632 return ExtInfo(Bits | NoReturnMask);
3633 else
3634 return ExtInfo(Bits & ~NoReturnMask);
3635 }
3636
3637 ExtInfo withProducesResult(bool producesResult) const {
3638 if (producesResult)
3639 return ExtInfo(Bits | ProducesResultMask);
3640 else
3641 return ExtInfo(Bits & ~ProducesResultMask);
3642 }
3643
3644 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3645 if (noCallerSavedRegs)
3646 return ExtInfo(Bits | NoCallerSavedRegsMask);
3647 else
3648 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3649 }
3650
3651 ExtInfo withNoCfCheck(bool noCfCheck) const {
3652 if (noCfCheck)
3653 return ExtInfo(Bits | NoCfCheckMask);
3654 else
3655 return ExtInfo(Bits & ~NoCfCheckMask);
3656 }
3657
3658 ExtInfo withRegParm(unsigned RegParm) const {
3659 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3659, __PRETTY_FUNCTION__))
;
3660 return ExtInfo((Bits & ~RegParmMask) |
3661 ((RegParm + 1) << RegParmOffset));
3662 }
3663
3664 ExtInfo withCallingConv(CallingConv cc) const {
3665 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3666 }
3667
3668 void Profile(llvm::FoldingSetNodeID &ID) const {
3669 ID.AddInteger(Bits);
3670 }
3671 };
3672
3673 /// A simple holder for a QualType representing a type in an
3674 /// exception specification. Unfortunately needed by FunctionProtoType
3675 /// because TrailingObjects cannot handle repeated types.
3676 struct ExceptionType { QualType Type; };
3677
3678 /// A simple holder for various uncommon bits which do not fit in
3679 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3680 /// alignment of subsequent objects in TrailingObjects. You must update
3681 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3682 struct alignas(void *) FunctionTypeExtraBitfields {
3683 /// The number of types in the exception specification.
3684 /// A whole unsigned is not needed here and according to
3685 /// [implimits] 8 bits would be enough here.
3686 unsigned NumExceptionType;
3687 };
3688
3689protected:
3690 FunctionType(TypeClass tc, QualType res,
3691 QualType Canonical, bool Dependent,
3692 bool InstantiationDependent,
3693 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3694 ExtInfo Info)
3695 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3696 ContainsUnexpandedParameterPack),
3697 ResultType(res) {
3698 FunctionTypeBits.ExtInfo = Info.Bits;
3699 }
3700
3701 Qualifiers getFastTypeQuals() const {
3702 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3703 }
3704
3705public:
3706 QualType getReturnType() const { return ResultType; }
3707
3708 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3709 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3710
3711 /// Determine whether this function type includes the GNU noreturn
3712 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3713 /// type.
3714 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3715
3716 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3717 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3718
3719 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3720 "Const, volatile and restrict are assumed to be a subset of "
3721 "the fast qualifiers.");
3722
3723 bool isConst() const { return getFastTypeQuals().hasConst(); }
3724 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3725 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3726
3727 /// Determine the type of an expression that calls a function of
3728 /// this type.
3729 QualType getCallResultType(const ASTContext &Context) const {
3730 return getReturnType().getNonLValueExprType(Context);
3731 }
3732
3733 static StringRef getNameForCallConv(CallingConv CC);
3734
3735 static bool classof(const Type *T) {
3736 return T->getTypeClass() == FunctionNoProto ||
3737 T->getTypeClass() == FunctionProto;
3738 }
3739};
3740
3741/// Represents a K&R-style 'int foo()' function, which has
3742/// no information available about its arguments.
3743class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3744 friend class ASTContext; // ASTContext creates these.
3745
3746 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3747 : FunctionType(FunctionNoProto, Result, Canonical,
3748 /*Dependent=*/false, /*InstantiationDependent=*/false,
3749 Result->isVariablyModifiedType(),
3750 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3751
3752public:
3753 // No additional state past what FunctionType provides.
3754
3755 bool isSugared() const { return false; }
3756 QualType desugar() const { return QualType(this, 0); }
3757
3758 void Profile(llvm::FoldingSetNodeID &ID) {
3759 Profile(ID, getReturnType(), getExtInfo());
3760 }
3761
3762 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3763 ExtInfo Info) {
3764 Info.Profile(ID);
3765 ID.AddPointer(ResultType.getAsOpaquePtr());
3766 }
3767
3768 static bool classof(const Type *T) {
3769 return T->getTypeClass() == FunctionNoProto;
3770 }
3771};
3772
3773/// Represents a prototype with parameter type info, e.g.
3774/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3775/// parameters, not as having a single void parameter. Such a type can have
3776/// an exception specification, but this specification is not part of the
3777/// canonical type. FunctionProtoType has several trailing objects, some of
3778/// which optional. For more information about the trailing objects see
3779/// the first comment inside FunctionProtoType.
3780class FunctionProtoType final
3781 : public FunctionType,
3782 public llvm::FoldingSetNode,
3783 private llvm::TrailingObjects<
3784 FunctionProtoType, QualType, SourceLocation,
3785 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3786 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3787 friend class ASTContext; // ASTContext creates these.
3788 friend TrailingObjects;
3789
3790 // FunctionProtoType is followed by several trailing objects, some of
3791 // which optional. They are in order:
3792 //
3793 // * An array of getNumParams() QualType holding the parameter types.
3794 // Always present. Note that for the vast majority of FunctionProtoType,
3795 // these will be the only trailing objects.
3796 //
3797 // * Optionally if the function is variadic, the SourceLocation of the
3798 // ellipsis.
3799 //
3800 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3801 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3802 // a single FunctionTypeExtraBitfields. Present if and only if
3803 // hasExtraBitfields() is true.
3804 //
3805 // * Optionally exactly one of:
3806 // * an array of getNumExceptions() ExceptionType,
3807 // * a single Expr *,
3808 // * a pair of FunctionDecl *,
3809 // * a single FunctionDecl *
3810 // used to store information about the various types of exception
3811 // specification. See getExceptionSpecSize for the details.
3812 //
3813 // * Optionally an array of getNumParams() ExtParameterInfo holding
3814 // an ExtParameterInfo for each of the parameters. Present if and
3815 // only if hasExtParameterInfos() is true.
3816 //
3817 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3818 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3819 // if hasExtQualifiers() is true.
3820 //
3821 // The optional FunctionTypeExtraBitfields has to be before the data
3822 // related to the exception specification since it contains the number
3823 // of exception types.
3824 //
3825 // We put the ExtParameterInfos last. If all were equal, it would make
3826 // more sense to put these before the exception specification, because
3827 // it's much easier to skip past them compared to the elaborate switch
3828 // required to skip the exception specification. However, all is not
3829 // equal; ExtParameterInfos are used to model very uncommon features,
3830 // and it's better not to burden the more common paths.
3831
3832public:
3833 /// Holds information about the various types of exception specification.
3834 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3835 /// used to group together the various bits of information about the
3836 /// exception specification.
3837 struct ExceptionSpecInfo {
3838 /// The kind of exception specification this is.
3839 ExceptionSpecificationType Type = EST_None;
3840
3841 /// Explicitly-specified list of exception types.
3842 ArrayRef<QualType> Exceptions;
3843
3844 /// Noexcept expression, if this is a computed noexcept specification.
3845 Expr *NoexceptExpr = nullptr;
3846
3847 /// The function whose exception specification this is, for
3848 /// EST_Unevaluated and EST_Uninstantiated.
3849 FunctionDecl *SourceDecl = nullptr;
3850
3851 /// The function template whose exception specification this is instantiated
3852 /// from, for EST_Uninstantiated.
3853 FunctionDecl *SourceTemplate = nullptr;
3854
3855 ExceptionSpecInfo() = default;
3856
3857 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3858 };
3859
3860 /// Extra information about a function prototype. ExtProtoInfo is not
3861 /// stored as such in FunctionProtoType but is used to group together
3862 /// the various bits of extra information about a function prototype.
3863 struct ExtProtoInfo {
3864 FunctionType::ExtInfo ExtInfo;
3865 bool Variadic : 1;
3866 bool HasTrailingReturn : 1;
3867 Qualifiers TypeQuals;
3868 RefQualifierKind RefQualifier = RQ_None;
3869 ExceptionSpecInfo ExceptionSpec;
3870 const ExtParameterInfo *ExtParameterInfos = nullptr;
3871 SourceLocation EllipsisLoc;
3872
3873 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3874
3875 ExtProtoInfo(CallingConv CC)
3876 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3877
3878 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3879 ExtProtoInfo Result(*this);
3880 Result.ExceptionSpec = ESI;
3881 return Result;
3882 }
3883 };
3884
3885private:
3886 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3887 return getNumParams();
3888 }
3889
3890 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3891 return isVariadic();
3892 }
3893
3894 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3895 return hasExtraBitfields();
3896 }
3897
3898 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3899 return getExceptionSpecSize().NumExceptionType;
3900 }
3901
3902 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3903 return getExceptionSpecSize().NumExprPtr;
3904 }
3905
3906 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3907 return getExceptionSpecSize().NumFunctionDeclPtr;
3908 }
3909
3910 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3911 return hasExtParameterInfos() ? getNumParams() : 0;
3912 }
3913
3914 /// Determine whether there are any argument types that
3915 /// contain an unexpanded parameter pack.
3916 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3917 unsigned numArgs) {
3918 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3919 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3920 return true;
3921
3922 return false;
3923 }
3924
3925 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3926 QualType canonical, const ExtProtoInfo &epi);
3927
3928 /// This struct is returned by getExceptionSpecSize and is used to
3929 /// translate an ExceptionSpecificationType to the number and kind
3930 /// of trailing objects related to the exception specification.
3931 struct ExceptionSpecSizeHolder {
3932 unsigned NumExceptionType;
3933 unsigned NumExprPtr;
3934 unsigned NumFunctionDeclPtr;
3935 };
3936
3937 /// Return the number and kind of trailing objects
3938 /// related to the exception specification.
3939 static ExceptionSpecSizeHolder
3940 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3941 switch (EST) {
3942 case EST_None:
3943 case EST_DynamicNone:
3944 case EST_MSAny:
3945 case EST_BasicNoexcept:
3946 case EST_Unparsed:
3947 case EST_NoThrow:
3948 return {0, 0, 0};
3949
3950 case EST_Dynamic:
3951 return {NumExceptions, 0, 0};
3952
3953 case EST_DependentNoexcept:
3954 case EST_NoexceptFalse:
3955 case EST_NoexceptTrue:
3956 return {0, 1, 0};
3957
3958 case EST_Uninstantiated:
3959 return {0, 0, 2};
3960
3961 case EST_Unevaluated:
3962 return {0, 0, 1};
3963 }
3964 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3964)
;
3965 }
3966
3967 /// Return the number and kind of trailing objects
3968 /// related to the exception specification.
3969 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3970 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3971 }
3972
3973 /// Whether the trailing FunctionTypeExtraBitfields is present.
3974 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3975 // If the exception spec type is EST_Dynamic then we have > 0 exception
3976 // types and the exact number is stored in FunctionTypeExtraBitfields.
3977 return EST == EST_Dynamic;
3978 }
3979
3980 /// Whether the trailing FunctionTypeExtraBitfields is present.
3981 bool hasExtraBitfields() const {
3982 return hasExtraBitfields(getExceptionSpecType());
3983 }
3984
3985 bool hasExtQualifiers() const {
3986 return FunctionTypeBits.HasExtQuals;
3987 }
3988
3989public:
3990 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3991
3992 QualType getParamType(unsigned i) const {
3993 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 3993, __PRETTY_FUNCTION__))
;
3994 return param_type_begin()[i];
3995 }
3996
3997 ArrayRef<QualType> getParamTypes() const {
3998 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3999 }
4000
4001 ExtProtoInfo getExtProtoInfo() const {
4002 ExtProtoInfo EPI;
4003 EPI.ExtInfo = getExtInfo();
4004 EPI.Variadic = isVariadic();
4005 EPI.EllipsisLoc = getEllipsisLoc();
4006 EPI.HasTrailingReturn = hasTrailingReturn();
4007 EPI.ExceptionSpec = getExceptionSpecInfo();
4008 EPI.TypeQuals = getMethodQuals();
4009 EPI.RefQualifier = getRefQualifier();
4010 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4011 return EPI;
4012 }
4013
4014 /// Get the kind of exception specification on this function.
4015 ExceptionSpecificationType getExceptionSpecType() const {
4016 return static_cast<ExceptionSpecificationType>(
4017 FunctionTypeBits.ExceptionSpecType);
4018 }
4019
4020 /// Return whether this function has any kind of exception spec.
4021 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4022
4023 /// Return whether this function has a dynamic (throw) exception spec.
4024 bool hasDynamicExceptionSpec() const {
4025 return isDynamicExceptionSpec(getExceptionSpecType());
4026 }
4027
4028 /// Return whether this function has a noexcept exception spec.
4029 bool hasNoexceptExceptionSpec() const {
4030 return isNoexceptExceptionSpec(getExceptionSpecType());
4031 }
4032
4033 /// Return whether this function has a dependent exception spec.
4034 bool hasDependentExceptionSpec() const;
4035
4036 /// Return whether this function has an instantiation-dependent exception
4037 /// spec.
4038 bool hasInstantiationDependentExceptionSpec() const;
4039
4040 /// Return all the available information about this type's exception spec.
4041 ExceptionSpecInfo getExceptionSpecInfo() const {
4042 ExceptionSpecInfo Result;
4043 Result.Type = getExceptionSpecType();
4044 if (Result.Type == EST_Dynamic) {
4045 Result.Exceptions = exceptions();
4046 } else if (isComputedNoexcept(Result.Type)) {
4047 Result.NoexceptExpr = getNoexceptExpr();
4048 } else if (Result.Type == EST_Uninstantiated) {
4049 Result.SourceDecl = getExceptionSpecDecl();
4050 Result.SourceTemplate = getExceptionSpecTemplate();
4051 } else if (Result.Type == EST_Unevaluated) {
4052 Result.SourceDecl = getExceptionSpecDecl();
4053 }
4054 return Result;
4055 }
4056
4057 /// Return the number of types in the exception specification.
4058 unsigned getNumExceptions() const {
4059 return getExceptionSpecType() == EST_Dynamic
4060 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4061 ->NumExceptionType
4062 : 0;
4063 }
4064
4065 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4066 QualType getExceptionType(unsigned i) const {
4067 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4067, __PRETTY_FUNCTION__))
;
4068 return exception_begin()[i];
4069 }
4070
4071 /// Return the expression inside noexcept(expression), or a null pointer
4072 /// if there is none (because the exception spec is not of this form).
4073 Expr *getNoexceptExpr() const {
4074 if (!isComputedNoexcept(getExceptionSpecType()))
4075 return nullptr;
4076 return *getTrailingObjects<Expr *>();
4077 }
4078
4079 /// If this function type has an exception specification which hasn't
4080 /// been determined yet (either because it has not been evaluated or because
4081 /// it has not been instantiated), this is the function whose exception
4082 /// specification is represented by this type.
4083 FunctionDecl *getExceptionSpecDecl() const {
4084 if (getExceptionSpecType() != EST_Uninstantiated &&
4085 getExceptionSpecType() != EST_Unevaluated)
4086 return nullptr;
4087 return getTrailingObjects<FunctionDecl *>()[0];
4088 }
4089
4090 /// If this function type has an uninstantiated exception
4091 /// specification, this is the function whose exception specification
4092 /// should be instantiated to find the exception specification for
4093 /// this type.
4094 FunctionDecl *getExceptionSpecTemplate() const {
4095 if (getExceptionSpecType() != EST_Uninstantiated)
4096 return nullptr;
4097 return getTrailingObjects<FunctionDecl *>()[1];
4098 }
4099
4100 /// Determine whether this function type has a non-throwing exception
4101 /// specification.
4102 CanThrowResult canThrow() const;
4103
4104 /// Determine whether this function type has a non-throwing exception
4105 /// specification. If this depends on template arguments, returns
4106 /// \c ResultIfDependent.
4107 bool isNothrow(bool ResultIfDependent = false) const {
4108 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4109 }
4110
4111 /// Whether this function prototype is variadic.
4112 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4113
4114 SourceLocation getEllipsisLoc() const {
4115 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4116 : SourceLocation();
4117 }
4118
4119 /// Determines whether this function prototype contains a
4120 /// parameter pack at the end.
4121 ///
4122 /// A function template whose last parameter is a parameter pack can be
4123 /// called with an arbitrary number of arguments, much like a variadic
4124 /// function.
4125 bool isTemplateVariadic() const;
4126
4127 /// Whether this function prototype has a trailing return type.
4128 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4129
4130 Qualifiers getMethodQuals() const {
4131 if (hasExtQualifiers())
4132 return *getTrailingObjects<Qualifiers>();
4133 else
4134 return getFastTypeQuals();
4135 }
4136
4137 /// Retrieve the ref-qualifier associated with this function type.
4138 RefQualifierKind getRefQualifier() const {
4139 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4140 }
4141
4142 using param_type_iterator = const QualType *;
4143 using param_type_range = llvm::iterator_range<param_type_iterator>;
4144
4145 param_type_range param_types() const {
4146 return param_type_range(param_type_begin(), param_type_end());
4147 }
4148
4149 param_type_iterator param_type_begin() const {
4150 return getTrailingObjects<QualType>();
4151 }
4152
4153 param_type_iterator param_type_end() const {
4154 return param_type_begin() + getNumParams();
4155 }
4156
4157 using exception_iterator = const QualType *;
4158
4159 ArrayRef<QualType> exceptions() const {
4160 return llvm::makeArrayRef(exception_begin(), exception_end());
4161 }
4162
4163 exception_iterator exception_begin() const {
4164 return reinterpret_cast<exception_iterator>(
4165 getTrailingObjects<ExceptionType>());
4166 }
4167
4168 exception_iterator exception_end() const {
4169 return exception_begin() + getNumExceptions();
4170 }
4171
4172 /// Is there any interesting extra information for any of the parameters
4173 /// of this function type?
4174 bool hasExtParameterInfos() const {
4175 return FunctionTypeBits.HasExtParameterInfos;
4176 }
4177
4178 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4179 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4179, __PRETTY_FUNCTION__))
;
4180 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4181 getNumParams());
4182 }
4183
4184 /// Return a pointer to the beginning of the array of extra parameter
4185 /// information, if present, or else null if none of the parameters
4186 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4187 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4188 if (!hasExtParameterInfos())
4189 return nullptr;
4190 return getTrailingObjects<ExtParameterInfo>();
4191 }
4192
4193 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4194 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4194, __PRETTY_FUNCTION__))
;
4195 if (hasExtParameterInfos())
4196 return getTrailingObjects<ExtParameterInfo>()[I];
4197 return ExtParameterInfo();
4198 }
4199
4200 ParameterABI getParameterABI(unsigned I) const {
4201 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4201, __PRETTY_FUNCTION__))
;
4202 if (hasExtParameterInfos())
4203 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4204 return ParameterABI::Ordinary;
4205 }
4206
4207 bool isParamConsumed(unsigned I) const {
4208 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4208, __PRETTY_FUNCTION__))
;
4209 if (hasExtParameterInfos())
4210 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4211 return false;
4212 }
4213
4214 bool isSugared() const { return false; }
4215 QualType desugar() const { return QualType(this, 0); }
4216
4217 void printExceptionSpecification(raw_ostream &OS,
4218 const PrintingPolicy &Policy) const;
4219
4220 static bool classof(const Type *T) {
4221 return T->getTypeClass() == FunctionProto;
4222 }
4223
4224 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4225 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4226 param_type_iterator ArgTys, unsigned NumArgs,
4227 const ExtProtoInfo &EPI, const ASTContext &Context,
4228 bool Canonical);
4229};
4230
4231/// Represents the dependent type named by a dependently-scoped
4232/// typename using declaration, e.g.
4233/// using typename Base<T>::foo;
4234///
4235/// Template instantiation turns these into the underlying type.
4236class UnresolvedUsingType : public Type {
4237 friend class ASTContext; // ASTContext creates these.
4238
4239 UnresolvedUsingTypenameDecl *Decl;
4240
4241 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4242 : Type(UnresolvedUsing, QualType(), true, true, false,
4243 /*ContainsUnexpandedParameterPack=*/false),
4244 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4245
4246public:
4247 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4248
4249 bool isSugared() const { return false; }
4250 QualType desugar() const { return QualType(this, 0); }
4251
4252 static bool classof(const Type *T) {
4253 return T->getTypeClass() == UnresolvedUsing;
4254 }
4255
4256 void Profile(llvm::FoldingSetNodeID &ID) {
4257 return Profile(ID, Decl);
4258 }
4259
4260 static void Profile(llvm::FoldingSetNodeID &ID,
4261 UnresolvedUsingTypenameDecl *D) {
4262 ID.AddPointer(D);
4263 }
4264};
4265
4266class TypedefType : public Type {
4267 TypedefNameDecl *Decl;
4268
4269protected:
4270 friend class ASTContext; // ASTContext creates these.
4271
4272 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4273 : Type(tc, can, can->isDependentType(),
4274 can->isInstantiationDependentType(),
4275 can->isVariablyModifiedType(),
4276 /*ContainsUnexpandedParameterPack=*/false),
4277 Decl(const_cast<TypedefNameDecl*>(D)) {
4278 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4278, __PRETTY_FUNCTION__))
;
4279 }
4280
4281public:
4282 TypedefNameDecl *getDecl() const { return Decl; }
4283
4284 bool isSugared() const { return true; }
4285 QualType desugar() const;
4286
4287 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4288};
4289
4290/// Sugar type that represents a type that was qualified by a qualifier written
4291/// as a macro invocation.
4292class MacroQualifiedType : public Type {
4293 friend class ASTContext; // ASTContext creates these.
4294
4295 QualType UnderlyingTy;
4296 const IdentifierInfo *MacroII;
4297
4298 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4299 const IdentifierInfo *MacroII)
4300 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4301 UnderlyingTy->isInstantiationDependentType(),
4302 UnderlyingTy->isVariablyModifiedType(),
4303 UnderlyingTy->containsUnexpandedParameterPack()),
4304 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4305 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4306, __PRETTY_FUNCTION__))
4306 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4306, __PRETTY_FUNCTION__))
;
4307 }
4308
4309public:
4310 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4311 QualType getUnderlyingType() const { return UnderlyingTy; }
4312
4313 /// Return this attributed type's modified type with no qualifiers attached to
4314 /// it.
4315 QualType getModifiedType() const;
4316
4317 bool isSugared() const { return true; }
4318 QualType desugar() const;
4319
4320 static bool classof(const Type *T) {
4321 return T->getTypeClass() == MacroQualified;
4322 }
4323};
4324
4325/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4326class TypeOfExprType : public Type {
4327 Expr *TOExpr;
4328
4329protected:
4330 friend class ASTContext; // ASTContext creates these.
4331
4332 TypeOfExprType(Expr *E, QualType can = QualType());
4333
4334public:
4335 Expr *getUnderlyingExpr() const { return TOExpr; }
4336
4337 /// Remove a single level of sugar.
4338 QualType desugar() const;
4339
4340 /// Returns whether this type directly provides sugar.
4341 bool isSugared() const;
4342
4343 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4344};
4345
4346/// Internal representation of canonical, dependent
4347/// `typeof(expr)` types.
4348///
4349/// This class is used internally by the ASTContext to manage
4350/// canonical, dependent types, only. Clients will only see instances
4351/// of this class via TypeOfExprType nodes.
4352class DependentTypeOfExprType
4353 : public TypeOfExprType, public llvm::FoldingSetNode {
4354 const ASTContext &Context;
4355
4356public:
4357 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4358 : TypeOfExprType(E), Context(Context) {}
4359
4360 void Profile(llvm::FoldingSetNodeID &ID) {
4361 Profile(ID, Context, getUnderlyingExpr());
4362 }
4363
4364 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4365 Expr *E);
4366};
4367
4368/// Represents `typeof(type)`, a GCC extension.
4369class TypeOfType : public Type {
4370 friend class ASTContext; // ASTContext creates these.
4371
4372 QualType TOType;
4373
4374 TypeOfType(QualType T, QualType can)
4375 : Type(TypeOf, can, T->isDependentType(),
4376 T->isInstantiationDependentType(),
4377 T->isVariablyModifiedType(),
4378 T->containsUnexpandedParameterPack()),
4379 TOType(T) {
4380 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4380, __PRETTY_FUNCTION__))
;
4381 }
4382
4383public:
4384 QualType getUnderlyingType() const { return TOType; }
4385
4386 /// Remove a single level of sugar.
4387 QualType desugar() const { return getUnderlyingType(); }
4388
4389 /// Returns whether this type directly provides sugar.
4390 bool isSugared() const { return true; }
4391
4392 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4393};
4394
4395/// Represents the type `decltype(expr)` (C++11).
4396class DecltypeType : public Type {
4397 Expr *E;
4398 QualType UnderlyingType;
4399
4400protected:
4401 friend class ASTContext; // ASTContext creates these.
4402
4403 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4404
4405public:
4406 Expr *getUnderlyingExpr() const { return E; }
4407 QualType getUnderlyingType() const { return UnderlyingType; }
4408
4409 /// Remove a single level of sugar.
4410 QualType desugar() const;
4411
4412 /// Returns whether this type directly provides sugar.
4413 bool isSugared() const;
4414
4415 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4416};
4417
4418/// Internal representation of canonical, dependent
4419/// decltype(expr) types.
4420///
4421/// This class is used internally by the ASTContext to manage
4422/// canonical, dependent types, only. Clients will only see instances
4423/// of this class via DecltypeType nodes.
4424class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4425 const ASTContext &Context;
4426
4427public:
4428 DependentDecltypeType(const ASTContext &Context, Expr *E);
4429
4430 void Profile(llvm::FoldingSetNodeID &ID) {
4431 Profile(ID, Context, getUnderlyingExpr());
4432 }
4433
4434 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4435 Expr *E);
4436};
4437
4438/// A unary type transform, which is a type constructed from another.
4439class UnaryTransformType : public Type {
4440public:
4441 enum UTTKind {
4442 EnumUnderlyingType
4443 };
4444
4445private:
4446 /// The untransformed type.
4447 QualType BaseType;
4448
4449 /// The transformed type if not dependent, otherwise the same as BaseType.
4450 QualType UnderlyingType;
4451
4452 UTTKind UKind;
4453
4454protected:
4455 friend class ASTContext;
4456
4457 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4458 QualType CanonicalTy);
4459
4460public:
4461 bool isSugared() const { return !isDependentType(); }
4462 QualType desugar() const { return UnderlyingType; }
4463
4464 QualType getUnderlyingType() const { return UnderlyingType; }
4465 QualType getBaseType() const { return BaseType; }
4466
4467 UTTKind getUTTKind() const { return UKind; }
4468
4469 static bool classof(const Type *T) {
4470 return T->getTypeClass() == UnaryTransform;
4471 }
4472};
4473
4474/// Internal representation of canonical, dependent
4475/// __underlying_type(type) types.
4476///
4477/// This class is used internally by the ASTContext to manage
4478/// canonical, dependent types, only. Clients will only see instances
4479/// of this class via UnaryTransformType nodes.
4480class DependentUnaryTransformType : public UnaryTransformType,
4481 public llvm::FoldingSetNode {
4482public:
4483 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4484 UTTKind UKind);
4485
4486 void Profile(llvm::FoldingSetNodeID &ID) {
4487 Profile(ID, getBaseType(), getUTTKind());
4488 }
4489
4490 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4491 UTTKind UKind) {
4492 ID.AddPointer(BaseType.getAsOpaquePtr());
4493 ID.AddInteger((unsigned)UKind);
4494 }
4495};
4496
4497class TagType : public Type {
4498 friend class ASTReader;
4499 template <class T> friend class serialization::AbstractTypeReader;
4500
4501 /// Stores the TagDecl associated with this type. The decl may point to any
4502 /// TagDecl that declares the entity.
4503 TagDecl *decl;
4504
4505protected:
4506 TagType(TypeClass TC, const TagDecl *D, QualType can);
4507
4508public:
4509 TagDecl *getDecl() const;
4510
4511 /// Determines whether this type is in the process of being defined.
4512 bool isBeingDefined() const;
4513
4514 static bool classof(const Type *T) {
4515 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4516 }
4517};
4518
4519/// A helper class that allows the use of isa/cast/dyncast
4520/// to detect TagType objects of structs/unions/classes.
4521class RecordType : public TagType {
4522protected:
4523 friend class ASTContext; // ASTContext creates these.
4524
4525 explicit RecordType(const RecordDecl *D)
4526 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4527 explicit RecordType(TypeClass TC, RecordDecl *D)
4528 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4529
4530public:
4531 RecordDecl *getDecl() const {
4532 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4533 }
4534
4535 /// Recursively check all fields in the record for const-ness. If any field
4536 /// is declared const, return true. Otherwise, return false.
4537 bool hasConstFields() const;
4538
4539 bool isSugared() const { return false; }
4540 QualType desugar() const { return QualType(this, 0); }
4541
4542 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4543};
4544
4545/// A helper class that allows the use of isa/cast/dyncast
4546/// to detect TagType objects of enums.
4547class EnumType : public TagType {
4548 friend class ASTContext; // ASTContext creates these.
4549
4550 explicit EnumType(const EnumDecl *D)
4551 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4552
4553public:
4554 EnumDecl *getDecl() const {
4555 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4556 }
4557
4558 bool isSugared() const { return false; }
4559 QualType desugar() const { return QualType(this, 0); }
4560
4561 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4562};
4563
4564/// An attributed type is a type to which a type attribute has been applied.
4565///
4566/// The "modified type" is the fully-sugared type to which the attributed
4567/// type was applied; generally it is not canonically equivalent to the
4568/// attributed type. The "equivalent type" is the minimally-desugared type
4569/// which the type is canonically equivalent to.
4570///
4571/// For example, in the following attributed type:
4572/// int32_t __attribute__((vector_size(16)))
4573/// - the modified type is the TypedefType for int32_t
4574/// - the equivalent type is VectorType(16, int32_t)
4575/// - the canonical type is VectorType(16, int)
4576class AttributedType : public Type, public llvm::FoldingSetNode {
4577public:
4578 using Kind = attr::Kind;
4579
4580private:
4581 friend class ASTContext; // ASTContext creates these
4582
4583 QualType ModifiedType;
4584 QualType EquivalentType;
4585
4586 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4587 QualType equivalent)
4588 : Type(Attributed, canon, equivalent->isDependentType(),
4589 equivalent->isInstantiationDependentType(),
4590 equivalent->isVariablyModifiedType(),
4591 equivalent->containsUnexpandedParameterPack()),
4592 ModifiedType(modified), EquivalentType(equivalent) {
4593 AttributedTypeBits.AttrKind = attrKind;
4594 }
4595
4596public:
4597 Kind getAttrKind() const {
4598 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4599 }
4600
4601 QualType getModifiedType() const { return ModifiedType; }
4602 QualType getEquivalentType() const { return EquivalentType; }
4603
4604 bool isSugared() const { return true; }
4605 QualType desugar() const { return getEquivalentType(); }
4606
4607 /// Does this attribute behave like a type qualifier?
4608 ///
4609 /// A type qualifier adjusts a type to provide specialized rules for
4610 /// a specific object, like the standard const and volatile qualifiers.
4611 /// This includes attributes controlling things like nullability,
4612 /// address spaces, and ARC ownership. The value of the object is still
4613 /// largely described by the modified type.
4614 ///
4615 /// In contrast, many type attributes "rewrite" their modified type to
4616 /// produce a fundamentally different type, not necessarily related in any
4617 /// formalizable way to the original type. For example, calling convention
4618 /// and vector attributes are not simple type qualifiers.
4619 ///
4620 /// Type qualifiers are often, but not always, reflected in the canonical
4621 /// type.
4622 bool isQualifier() const;
4623
4624 bool isMSTypeSpec() const;
4625
4626 bool isCallingConv() const;
4627
4628 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4629
4630 /// Retrieve the attribute kind corresponding to the given
4631 /// nullability kind.
4632 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4633 switch (kind) {
4634 case NullabilityKind::NonNull:
4635 return attr::TypeNonNull;
4636
4637 case NullabilityKind::Nullable:
4638 return attr::TypeNullable;
4639
4640 case NullabilityKind::Unspecified:
4641 return attr::TypeNullUnspecified;
4642 }
4643 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 4643)
;
4644 }
4645
4646 /// Strip off the top-level nullability annotation on the given
4647 /// type, if it's there.
4648 ///
4649 /// \param T The type to strip. If the type is exactly an
4650 /// AttributedType specifying nullability (without looking through
4651 /// type sugar), the nullability is returned and this type changed
4652 /// to the underlying modified type.
4653 ///
4654 /// \returns the top-level nullability, if present.
4655 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4656
4657 void Profile(llvm::FoldingSetNodeID &ID) {
4658 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4659 }
4660
4661 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4662 QualType modified, QualType equivalent) {
4663 ID.AddInteger(attrKind);
4664 ID.AddPointer(modified.getAsOpaquePtr());
4665 ID.AddPointer(equivalent.getAsOpaquePtr());
4666 }
4667
4668 static bool classof(const Type *T) {
4669 return T->getTypeClass() == Attributed;
4670 }
4671};
4672
4673class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4674 friend class ASTContext; // ASTContext creates these
4675
4676 // Helper data collector for canonical types.
4677 struct CanonicalTTPTInfo {
4678 unsigned Depth : 15;
4679 unsigned ParameterPack : 1;
4680 unsigned Index : 16;
4681 };
4682
4683 union {
4684 // Info for the canonical type.
4685 CanonicalTTPTInfo CanTTPTInfo;
4686
4687 // Info for the non-canonical type.
4688 TemplateTypeParmDecl *TTPDecl;
4689 };
4690
4691 /// Build a non-canonical type.
4692 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4693 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4694 /*InstantiationDependent=*/true,
4695 /*VariablyModified=*/false,
4696 Canon->containsUnexpandedParameterPack()),
4697 TTPDecl(TTPDecl) {}
4698
4699 /// Build the canonical type.
4700 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4701 : Type(TemplateTypeParm, QualType(this, 0),
4702 /*Dependent=*/true,
4703 /*InstantiationDependent=*/true,
4704 /*VariablyModified=*/false, PP) {
4705 CanTTPTInfo.Depth = D;
4706 CanTTPTInfo.Index = I;
4707 CanTTPTInfo.ParameterPack = PP;
4708 }
4709
4710 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4711 QualType Can = getCanonicalTypeInternal();
4712 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4713 }
4714
4715public:
4716 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4717 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4718 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4719
4720 TemplateTypeParmDecl *getDecl() const {
4721 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4722 }
4723
4724 IdentifierInfo *getIdentifier() const;
4725
4726 bool isSugared() const { return false; }
4727 QualType desugar() const { return QualType(this, 0); }
4728
4729 void Profile(llvm::FoldingSetNodeID &ID) {
4730 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4731 }
4732
4733 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4734 unsigned Index, bool ParameterPack,
4735 TemplateTypeParmDecl *TTPDecl) {
4736 ID.AddInteger(Depth);
4737 ID.AddInteger(Index);
4738 ID.AddBoolean(ParameterPack);
4739 ID.AddPointer(TTPDecl);
4740 }
4741
4742 static bool classof(const Type *T) {
4743 return T->getTypeClass() == TemplateTypeParm;
4744 }
4745};
4746
4747/// Represents the result of substituting a type for a template
4748/// type parameter.
4749///
4750/// Within an instantiated template, all template type parameters have
4751/// been replaced with these. They are used solely to record that a
4752/// type was originally written as a template type parameter;
4753/// therefore they are never canonical.
4754class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4755 friend class ASTContext;
4756
4757 // The original type parameter.
4758 const TemplateTypeParmType *Replaced;
4759
4760 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4761 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4762 Canon->isInstantiationDependentType(),
4763 Canon->isVariablyModifiedType(),
4764 Canon->containsUnexpandedParameterPack()),
4765 Replaced(Param) {}
4766
4767public:
4768 /// Gets the template parameter that was substituted for.
4769 const TemplateTypeParmType *getReplacedParameter() const {
4770 return Replaced;
4771 }
4772
4773 /// Gets the type that was substituted for the template
4774 /// parameter.
4775 QualType getReplacementType() const {
4776 return getCanonicalTypeInternal();
4777 }
4778
4779 bool isSugared() const { return true; }
4780 QualType desugar() const { return getReplacementType(); }
4781
4782 void Profile(llvm::FoldingSetNodeID &ID) {
4783 Profile(ID, getReplacedParameter(), getReplacementType());
4784 }
4785
4786 static void Profile(llvm::FoldingSetNodeID &ID,
4787 const TemplateTypeParmType *Replaced,
4788 QualType Replacement) {
4789 ID.AddPointer(Replaced);
4790 ID.AddPointer(Replacement.getAsOpaquePtr());
4791 }
4792
4793 static bool classof(const Type *T) {
4794 return T->getTypeClass() == SubstTemplateTypeParm;
4795 }
4796};
4797
4798/// Represents the result of substituting a set of types for a template
4799/// type parameter pack.
4800///
4801/// When a pack expansion in the source code contains multiple parameter packs
4802/// and those parameter packs correspond to different levels of template
4803/// parameter lists, this type node is used to represent a template type
4804/// parameter pack from an outer level, which has already had its argument pack
4805/// substituted but that still lives within a pack expansion that itself
4806/// could not be instantiated. When actually performing a substitution into
4807/// that pack expansion (e.g., when all template parameters have corresponding
4808/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4809/// at the current pack substitution index.
4810class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4811 friend class ASTContext;
4812
4813 /// The original type parameter.
4814 const TemplateTypeParmType *Replaced;
4815
4816 /// A pointer to the set of template arguments that this
4817 /// parameter pack is instantiated with.
4818 const TemplateArgument *Arguments;
4819
4820 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4821 QualType Canon,
4822 const TemplateArgument &ArgPack);
4823
4824public:
4825 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4826
4827 /// Gets the template parameter that was substituted for.
4828 const TemplateTypeParmType *getReplacedParameter() const {
4829 return Replaced;
4830 }
4831
4832 unsigned getNumArgs() const {
4833 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4834 }
4835
4836 bool isSugared() const { return false; }
4837 QualType desugar() const { return QualType(this, 0); }
4838
4839 TemplateArgument getArgumentPack() const;
4840
4841 void Profile(llvm::FoldingSetNodeID &ID);
4842 static void Profile(llvm::FoldingSetNodeID &ID,
4843 const TemplateTypeParmType *Replaced,
4844 const TemplateArgument &ArgPack);
4845
4846 static bool classof(const Type *T) {
4847 return T->getTypeClass() == SubstTemplateTypeParmPack;
4848 }
4849};
4850
4851/// Common base class for placeholders for types that get replaced by
4852/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4853/// class template types, and constrained type names.
4854///
4855/// These types are usually a placeholder for a deduced type. However, before
4856/// the initializer is attached, or (usually) if the initializer is
4857/// type-dependent, there is no deduced type and the type is canonical. In
4858/// the latter case, it is also a dependent type.
4859class DeducedType : public Type {
4860protected:
4861 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4862 bool IsInstantiationDependent, bool ContainsParameterPack)
4863 : Type(TC,
4864 // FIXME: Retain the sugared deduced type?
4865 DeducedAsType.isNull() ? QualType(this, 0)
4866 : DeducedAsType.getCanonicalType(),
4867 IsDependent, IsInstantiationDependent,
4868 /*VariablyModified=*/false, ContainsParameterPack) {
4869 if (!DeducedAsType.isNull()) {
4870 if (DeducedAsType->isDependentType())
4871 setDependent();
4872 if (DeducedAsType->isInstantiationDependentType())
4873 setInstantiationDependent();
4874 if (DeducedAsType->containsUnexpandedParameterPack())
4875 setContainsUnexpandedParameterPack();
4876 }
4877 }
4878
4879public:
4880 bool isSugared() const { return !isCanonicalUnqualified(); }
4881 QualType desugar() const { return getCanonicalTypeInternal(); }
4882
4883 /// Get the type deduced for this placeholder type, or null if it's
4884 /// either not been deduced or was deduced to a dependent type.
4885 QualType getDeducedType() const {
4886 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4887 }
4888 bool isDeduced() const {
4889 return !isCanonicalUnqualified() || isDependentType();
4890 }
4891
4892 static bool classof(const Type *T) {
4893 return T->getTypeClass() == Auto ||
4894 T->getTypeClass() == DeducedTemplateSpecialization;
4895 }
4896};
4897
4898/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
4899/// by a type-constraint.
4900class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
4901 friend class ASTContext; // ASTContext creates these
4902
4903 ConceptDecl *TypeConstraintConcept;
4904
4905 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4906 bool IsDeducedAsDependent, bool IsDeducedAsPack, ConceptDecl *CD,
4907 ArrayRef<TemplateArgument> TypeConstraintArgs);
4908
4909 const TemplateArgument *getArgBuffer() const {
4910 return reinterpret_cast<const TemplateArgument*>(this+1);
4911 }
4912
4913 TemplateArgument *getArgBuffer() {
4914 return reinterpret_cast<TemplateArgument*>(this+1);
4915 }
4916
4917public:
4918 /// Retrieve the template arguments.
4919 const TemplateArgument *getArgs() const {
4920 return getArgBuffer();
4921 }
4922
4923 /// Retrieve the number of template arguments.
4924 unsigned getNumArgs() const {
4925 return AutoTypeBits.NumArgs;
4926 }
4927
4928 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4929
4930 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
4931 return {getArgs(), getNumArgs()};
4932 }
4933
4934 ConceptDecl *getTypeConstraintConcept() const {
4935 return TypeConstraintConcept;
4936 }
4937
4938 bool isConstrained() const {
4939 return TypeConstraintConcept != nullptr;
4940 }
4941
4942 bool isDecltypeAuto() const {
4943 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4944 }
4945
4946 AutoTypeKeyword getKeyword() const {
4947 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4948 }
4949
4950 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4951 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
4952 getTypeConstraintConcept(), getTypeConstraintArguments());
4953 }
4954
4955 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4956 QualType Deduced, AutoTypeKeyword Keyword,
4957 bool IsDependent, ConceptDecl *CD,
4958 ArrayRef<TemplateArgument> Arguments);
4959
4960 static bool classof(const Type *T) {
4961 return T->getTypeClass() == Auto;
4962 }
4963};
4964
4965/// Represents a C++17 deduced template specialization type.
4966class DeducedTemplateSpecializationType : public DeducedType,
4967 public llvm::FoldingSetNode {
4968 friend class ASTContext; // ASTContext creates these
4969
4970 /// The name of the template whose arguments will be deduced.
4971 TemplateName Template;
4972
4973 DeducedTemplateSpecializationType(TemplateName Template,
4974 QualType DeducedAsType,
4975 bool IsDeducedAsDependent)
4976 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4977 IsDeducedAsDependent || Template.isDependent(),
4978 IsDeducedAsDependent || Template.isInstantiationDependent(),
4979 Template.containsUnexpandedParameterPack()),
4980 Template(Template) {}
4981
4982public:
4983 /// Retrieve the name of the template that we are deducing.
4984 TemplateName getTemplateName() const { return Template;}
4985
4986 void Profile(llvm::FoldingSetNodeID &ID) {
4987 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4988 }
4989
4990 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4991 QualType Deduced, bool IsDependent) {
4992 Template.Profile(ID);
4993 ID.AddPointer(Deduced.getAsOpaquePtr());
4994 ID.AddBoolean(IsDependent);
4995 }
4996
4997 static bool classof(const Type *T) {
4998 return T->getTypeClass() == DeducedTemplateSpecialization;
4999 }
5000};
5001
5002/// Represents a type template specialization; the template
5003/// must be a class template, a type alias template, or a template
5004/// template parameter. A template which cannot be resolved to one of
5005/// these, e.g. because it is written with a dependent scope
5006/// specifier, is instead represented as a
5007/// @c DependentTemplateSpecializationType.
5008///
5009/// A non-dependent template specialization type is always "sugar",
5010/// typically for a \c RecordType. For example, a class template
5011/// specialization type of \c vector<int> will refer to a tag type for
5012/// the instantiation \c std::vector<int, std::allocator<int>>
5013///
5014/// Template specializations are dependent if either the template or
5015/// any of the template arguments are dependent, in which case the
5016/// type may also be canonical.
5017///
5018/// Instances of this type are allocated with a trailing array of
5019/// TemplateArguments, followed by a QualType representing the
5020/// non-canonical aliased type when the template is a type alias
5021/// template.
5022class alignas(8) TemplateSpecializationType
5023 : public Type,
5024 public llvm::FoldingSetNode {
5025 friend class ASTContext; // ASTContext creates these
5026
5027 /// The name of the template being specialized. This is
5028 /// either a TemplateName::Template (in which case it is a
5029 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5030 /// TypeAliasTemplateDecl*), a
5031 /// TemplateName::SubstTemplateTemplateParmPack, or a
5032 /// TemplateName::SubstTemplateTemplateParm (in which case the
5033 /// replacement must, recursively, be one of these).
5034 TemplateName Template;
5035
5036 TemplateSpecializationType(TemplateName T,
5037 ArrayRef<TemplateArgument> Args,
5038 QualType Canon,
5039 QualType Aliased);
5040
5041public:
5042 /// Determine whether any of the given template arguments are dependent.
5043 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5044 bool &InstantiationDependent);
5045
5046 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5047 bool &InstantiationDependent);
5048
5049 /// True if this template specialization type matches a current
5050 /// instantiation in the context in which it is found.
5051 bool isCurrentInstantiation() const {
5052 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5053 }
5054
5055 /// Determine if this template specialization type is for a type alias
5056 /// template that has been substituted.
5057 ///
5058 /// Nearly every template specialization type whose template is an alias
5059 /// template will be substituted. However, this is not the case when
5060 /// the specialization contains a pack expansion but the template alias
5061 /// does not have a corresponding parameter pack, e.g.,
5062 ///
5063 /// \code
5064 /// template<typename T, typename U, typename V> struct S;
5065 /// template<typename T, typename U> using A = S<T, int, U>;
5066 /// template<typename... Ts> struct X {
5067 /// typedef A<Ts...> type; // not a type alias
5068 /// };
5069 /// \endcode
5070 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5071
5072 /// Get the aliased type, if this is a specialization of a type alias
5073 /// template.
5074 QualType getAliasedType() const {
5075 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5075, __PRETTY_FUNCTION__))
;
5076 return *reinterpret_cast<const QualType*>(end());
5077 }
5078
5079 using iterator = const TemplateArgument *;
5080
5081 iterator begin() const { return getArgs(); }
5082 iterator end() const; // defined inline in TemplateBase.h
5083
5084 /// Retrieve the name of the template that we are specializing.
5085 TemplateName getTemplateName() const { return Template; }
5086
5087 /// Retrieve the template arguments.
5088 const TemplateArgument *getArgs() const {
5089 return reinterpret_cast<const TemplateArgument *>(this + 1);
5090 }
5091
5092 /// Retrieve the number of template arguments.
5093 unsigned getNumArgs() const {
5094 return TemplateSpecializationTypeBits.NumArgs;
5095 }
5096
5097 /// Retrieve a specific template argument as a type.
5098 /// \pre \c isArgType(Arg)
5099 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5100
5101 ArrayRef<TemplateArgument> template_arguments() const {
5102 return {getArgs(), getNumArgs()};
5103 }
5104
5105 bool isSugared() const {
5106 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5107 }
5108
5109 QualType desugar() const {
5110 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5111 }
5112
5113 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5114 Profile(ID, Template, template_arguments(), Ctx);
5115 if (isTypeAlias())
5116 getAliasedType().Profile(ID);
5117 }
5118
5119 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5120 ArrayRef<TemplateArgument> Args,
5121 const ASTContext &Context);
5122
5123 static bool classof(const Type *T) {
5124 return T->getTypeClass() == TemplateSpecialization;
5125 }
5126};
5127
5128/// Print a template argument list, including the '<' and '>'
5129/// enclosing the template arguments.
5130void printTemplateArgumentList(raw_ostream &OS,
5131 ArrayRef<TemplateArgument> Args,
5132 const PrintingPolicy &Policy);
5133
5134void printTemplateArgumentList(raw_ostream &OS,
5135 ArrayRef<TemplateArgumentLoc> Args,
5136 const PrintingPolicy &Policy);
5137
5138void printTemplateArgumentList(raw_ostream &OS,
5139 const TemplateArgumentListInfo &Args,
5140 const PrintingPolicy &Policy);
5141
5142/// The injected class name of a C++ class template or class
5143/// template partial specialization. Used to record that a type was
5144/// spelled with a bare identifier rather than as a template-id; the
5145/// equivalent for non-templated classes is just RecordType.
5146///
5147/// Injected class name types are always dependent. Template
5148/// instantiation turns these into RecordTypes.
5149///
5150/// Injected class name types are always canonical. This works
5151/// because it is impossible to compare an injected class name type
5152/// with the corresponding non-injected template type, for the same
5153/// reason that it is impossible to directly compare template
5154/// parameters from different dependent contexts: injected class name
5155/// types can only occur within the scope of a particular templated
5156/// declaration, and within that scope every template specialization
5157/// will canonicalize to the injected class name (when appropriate
5158/// according to the rules of the language).
5159class InjectedClassNameType : public Type {
5160 friend class ASTContext; // ASTContext creates these.
5161 friend class ASTNodeImporter;
5162 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5163 // currently suitable for AST reading, too much
5164 // interdependencies.
5165 template <class T> friend class serialization::AbstractTypeReader;
5166
5167 CXXRecordDecl *Decl;
5168
5169 /// The template specialization which this type represents.
5170 /// For example, in
5171 /// template <class T> class A { ... };
5172 /// this is A<T>, whereas in
5173 /// template <class X, class Y> class A<B<X,Y> > { ... };
5174 /// this is A<B<X,Y> >.
5175 ///
5176 /// It is always unqualified, always a template specialization type,
5177 /// and always dependent.
5178 QualType InjectedType;
5179
5180 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5181 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5182 /*InstantiationDependent=*/true,
5183 /*VariablyModified=*/false,
5184 /*ContainsUnexpandedParameterPack=*/false),
5185 Decl(D), InjectedType(TST) {
5186 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5186, __PRETTY_FUNCTION__))
;
5187 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5187, __PRETTY_FUNCTION__))
;
5188 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5188, __PRETTY_FUNCTION__))
;
5189 }
5190
5191public:
5192 QualType getInjectedSpecializationType() const { return InjectedType; }
5193
5194 const TemplateSpecializationType *getInjectedTST() const {
5195 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5196 }
5197
5198 TemplateName getTemplateName() const {
5199 return getInjectedTST()->getTemplateName();
5200 }
5201
5202 CXXRecordDecl *getDecl() const;
5203
5204 bool isSugared() const { return false; }
5205 QualType desugar() const { return QualType(this, 0); }
5206
5207 static bool classof(const Type *T) {
5208 return T->getTypeClass() == InjectedClassName;
5209 }
5210};
5211
5212/// The kind of a tag type.
5213enum TagTypeKind {
5214 /// The "struct" keyword.
5215 TTK_Struct,
5216
5217 /// The "__interface" keyword.
5218 TTK_Interface,
5219
5220 /// The "union" keyword.
5221 TTK_Union,
5222
5223 /// The "class" keyword.
5224 TTK_Class,
5225
5226 /// The "enum" keyword.
5227 TTK_Enum
5228};
5229
5230/// The elaboration keyword that precedes a qualified type name or
5231/// introduces an elaborated-type-specifier.
5232enum ElaboratedTypeKeyword {
5233 /// The "struct" keyword introduces the elaborated-type-specifier.
5234 ETK_Struct,
5235
5236 /// The "__interface" keyword introduces the elaborated-type-specifier.
5237 ETK_Interface,
5238
5239 /// The "union" keyword introduces the elaborated-type-specifier.
5240 ETK_Union,
5241
5242 /// The "class" keyword introduces the elaborated-type-specifier.
5243 ETK_Class,
5244
5245 /// The "enum" keyword introduces the elaborated-type-specifier.
5246 ETK_Enum,
5247
5248 /// The "typename" keyword precedes the qualified type name, e.g.,
5249 /// \c typename T::type.
5250 ETK_Typename,
5251
5252 /// No keyword precedes the qualified type name.
5253 ETK_None
5254};
5255
5256/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5257/// The keyword in stored in the free bits of the base class.
5258/// Also provides a few static helpers for converting and printing
5259/// elaborated type keyword and tag type kind enumerations.
5260class TypeWithKeyword : public Type {
5261protected:
5262 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5263 QualType Canonical, bool Dependent,
5264 bool InstantiationDependent, bool VariablyModified,
5265 bool ContainsUnexpandedParameterPack)
5266 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5267 ContainsUnexpandedParameterPack) {
5268 TypeWithKeywordBits.Keyword = Keyword;
5269 }
5270
5271public:
5272 ElaboratedTypeKeyword getKeyword() const {
5273 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5274 }
5275
5276 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5277 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5278
5279 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5280 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5281 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5282
5283 /// Converts a TagTypeKind into an elaborated type keyword.
5284 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5285
5286 /// Converts an elaborated type keyword into a TagTypeKind.
5287 /// It is an error to provide an elaborated type keyword
5288 /// which *isn't* a tag kind here.
5289 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5290
5291 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5292
5293 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5294
5295 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5296 return getKeywordName(getKeywordForTagTypeKind(Kind));
5297 }
5298
5299 class CannotCastToThisType {};
5300 static CannotCastToThisType classof(const Type *);
5301};
5302
5303/// Represents a type that was referred to using an elaborated type
5304/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5305/// or both.
5306///
5307/// This type is used to keep track of a type name as written in the
5308/// source code, including tag keywords and any nested-name-specifiers.
5309/// The type itself is always "sugar", used to express what was written
5310/// in the source code but containing no additional semantic information.
5311class ElaboratedType final
5312 : public TypeWithKeyword,
5313 public llvm::FoldingSetNode,
5314 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5315 friend class ASTContext; // ASTContext creates these
5316 friend TrailingObjects;
5317
5318 /// The nested name specifier containing the qualifier.
5319 NestedNameSpecifier *NNS;
5320
5321 /// The type that this qualified name refers to.
5322 QualType NamedType;
5323
5324 /// The (re)declaration of this tag type owned by this occurrence is stored
5325 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5326 /// it, or obtain a null pointer if there is none.
5327
5328 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5329 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5330 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5331 NamedType->isDependentType(),
5332 NamedType->isInstantiationDependentType(),
5333 NamedType->isVariablyModifiedType(),
5334 NamedType->containsUnexpandedParameterPack()),
5335 NNS(NNS), NamedType(NamedType) {
5336 ElaboratedTypeBits.HasOwnedTagDecl = false;
5337 if (OwnedTagDecl) {
5338 ElaboratedTypeBits.HasOwnedTagDecl = true;
5339 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5340 }
5341 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5343, __PRETTY_FUNCTION__))
5342 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5343, __PRETTY_FUNCTION__))
5343 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5343, __PRETTY_FUNCTION__))
;
5344 }
5345
5346public:
5347 /// Retrieve the qualification on this type.
5348 NestedNameSpecifier *getQualifier() const { return NNS; }
5349
5350 /// Retrieve the type named by the qualified-id.
5351 QualType getNamedType() const { return NamedType; }
5352
5353 /// Remove a single level of sugar.
5354 QualType desugar() const { return getNamedType(); }
5355
5356 /// Returns whether this type directly provides sugar.
5357 bool isSugared() const { return true; }
5358
5359 /// Return the (re)declaration of this type owned by this occurrence of this
5360 /// type, or nullptr if there is none.
5361 TagDecl *getOwnedTagDecl() const {
5362 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5363 : nullptr;
5364 }
5365
5366 void Profile(llvm::FoldingSetNodeID &ID) {
5367 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5368 }
5369
5370 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5371 NestedNameSpecifier *NNS, QualType NamedType,
5372 TagDecl *OwnedTagDecl) {
5373 ID.AddInteger(Keyword);
5374 ID.AddPointer(NNS);
5375 NamedType.Profile(ID);
5376 ID.AddPointer(OwnedTagDecl);
5377 }
5378
5379 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5380};
5381
5382/// Represents a qualified type name for which the type name is
5383/// dependent.
5384///
5385/// DependentNameType represents a class of dependent types that involve a
5386/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5387/// name of a type. The DependentNameType may start with a "typename" (for a
5388/// typename-specifier), "class", "struct", "union", or "enum" (for a
5389/// dependent elaborated-type-specifier), or nothing (in contexts where we
5390/// know that we must be referring to a type, e.g., in a base class specifier).
5391/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5392/// mode, this type is used with non-dependent names to delay name lookup until
5393/// instantiation.
5394class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5395 friend class ASTContext; // ASTContext creates these
5396
5397 /// The nested name specifier containing the qualifier.
5398 NestedNameSpecifier *NNS;
5399
5400 /// The type that this typename specifier refers to.
5401 const IdentifierInfo *Name;
5402
5403 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5404 const IdentifierInfo *Name, QualType CanonType)
5405 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5406 /*InstantiationDependent=*/true,
5407 /*VariablyModified=*/false,
5408 NNS->containsUnexpandedParameterPack()),
5409 NNS(NNS), Name(Name) {}
5410
5411public:
5412 /// Retrieve the qualification on this type.
5413 NestedNameSpecifier *getQualifier() const { return NNS; }
5414
5415 /// Retrieve the type named by the typename specifier as an identifier.
5416 ///
5417 /// This routine will return a non-NULL identifier pointer when the
5418 /// form of the original typename was terminated by an identifier,
5419 /// e.g., "typename T::type".
5420 const IdentifierInfo *getIdentifier() const {
5421 return Name;
5422 }
5423
5424 bool isSugared() const { return false; }
5425 QualType desugar() const { return QualType(this, 0); }
5426
5427 void Profile(llvm::FoldingSetNodeID &ID) {
5428 Profile(ID, getKeyword(), NNS, Name);
5429 }
5430
5431 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5432 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5433 ID.AddInteger(Keyword);
5434 ID.AddPointer(NNS);
5435 ID.AddPointer(Name);
5436 }
5437
5438 static bool classof(const Type *T) {
5439 return T->getTypeClass() == DependentName;
5440 }
5441};
5442
5443/// Represents a template specialization type whose template cannot be
5444/// resolved, e.g.
5445/// A<T>::template B<T>
5446class alignas(8) DependentTemplateSpecializationType
5447 : public TypeWithKeyword,
5448 public llvm::FoldingSetNode {
5449 friend class ASTContext; // ASTContext creates these
5450
5451 /// The nested name specifier containing the qualifier.
5452 NestedNameSpecifier *NNS;
5453
5454 /// The identifier of the template.
5455 const IdentifierInfo *Name;
5456
5457 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5458 NestedNameSpecifier *NNS,
5459 const IdentifierInfo *Name,
5460 ArrayRef<TemplateArgument> Args,
5461 QualType Canon);
5462
5463 const TemplateArgument *getArgBuffer() const {
5464 return reinterpret_cast<const TemplateArgument*>(this+1);
5465 }
5466
5467 TemplateArgument *getArgBuffer() {
5468 return reinterpret_cast<TemplateArgument*>(this+1);
5469 }
5470
5471public:
5472 NestedNameSpecifier *getQualifier() const { return NNS; }
5473 const IdentifierInfo *getIdentifier() const { return Name; }
5474
5475 /// Retrieve the template arguments.
5476 const TemplateArgument *getArgs() const {
5477 return getArgBuffer();
5478 }
5479
5480 /// Retrieve the number of template arguments.
5481 unsigned getNumArgs() const {
5482 return DependentTemplateSpecializationTypeBits.NumArgs;
5483 }
5484
5485 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5486
5487 ArrayRef<TemplateArgument> template_arguments() const {
5488 return {getArgs(), getNumArgs()};
5489 }
5490
5491 using iterator = const TemplateArgument *;
5492
5493 iterator begin() const { return getArgs(); }
5494 iterator end() const; // inline in TemplateBase.h
5495
5496 bool isSugared() const { return false; }
5497 QualType desugar() const { return QualType(this, 0); }
5498
5499 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5500 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5501 }
5502
5503 static void Profile(llvm::FoldingSetNodeID &ID,
5504 const ASTContext &Context,
5505 ElaboratedTypeKeyword Keyword,
5506 NestedNameSpecifier *Qualifier,
5507 const IdentifierInfo *Name,
5508 ArrayRef<TemplateArgument> Args);
5509
5510 static bool classof(const Type *T) {
5511 return T->getTypeClass() == DependentTemplateSpecialization;
5512 }
5513};
5514
5515/// Represents a pack expansion of types.
5516///
5517/// Pack expansions are part of C++11 variadic templates. A pack
5518/// expansion contains a pattern, which itself contains one or more
5519/// "unexpanded" parameter packs. When instantiated, a pack expansion
5520/// produces a series of types, each instantiated from the pattern of
5521/// the expansion, where the Ith instantiation of the pattern uses the
5522/// Ith arguments bound to each of the unexpanded parameter packs. The
5523/// pack expansion is considered to "expand" these unexpanded
5524/// parameter packs.
5525///
5526/// \code
5527/// template<typename ...Types> struct tuple;
5528///
5529/// template<typename ...Types>
5530/// struct tuple_of_references {
5531/// typedef tuple<Types&...> type;
5532/// };
5533/// \endcode
5534///
5535/// Here, the pack expansion \c Types&... is represented via a
5536/// PackExpansionType whose pattern is Types&.
5537class PackExpansionType : public Type, public llvm::FoldingSetNode {
5538 friend class ASTContext; // ASTContext creates these
5539
5540 /// The pattern of the pack expansion.
5541 QualType Pattern;
5542
5543 PackExpansionType(QualType Pattern, QualType Canon,
5544 Optional<unsigned> NumExpansions)
5545 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5546 /*InstantiationDependent=*/true,
5547 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5548 /*ContainsUnexpandedParameterPack=*/false),
5549 Pattern(Pattern) {
5550 PackExpansionTypeBits.NumExpansions =
5551 NumExpansions ? *NumExpansions + 1 : 0;
5552 }
5553
5554public:
5555 /// Retrieve the pattern of this pack expansion, which is the
5556 /// type that will be repeatedly instantiated when instantiating the
5557 /// pack expansion itself.
5558 QualType getPattern() const { return Pattern; }
5559
5560 /// Retrieve the number of expansions that this pack expansion will
5561 /// generate, if known.
5562 Optional<unsigned> getNumExpansions() const {
5563 if (PackExpansionTypeBits.NumExpansions)
5564 return PackExpansionTypeBits.NumExpansions - 1;
5565 return None;
5566 }
5567
5568 bool isSugared() const { return !Pattern->isDependentType(); }
5569 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5570
5571 void Profile(llvm::FoldingSetNodeID &ID) {
5572 Profile(ID, getPattern(), getNumExpansions());
5573 }
5574
5575 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5576 Optional<unsigned> NumExpansions) {
5577 ID.AddPointer(Pattern.getAsOpaquePtr());
5578 ID.AddBoolean(NumExpansions.hasValue());
5579 if (NumExpansions)
5580 ID.AddInteger(*NumExpansions);
5581 }
5582
5583 static bool classof(const Type *T) {
5584 return T->getTypeClass() == PackExpansion;
5585 }
5586};
5587
5588/// This class wraps the list of protocol qualifiers. For types that can
5589/// take ObjC protocol qualifers, they can subclass this class.
5590template <class T>
5591class ObjCProtocolQualifiers {
5592protected:
5593 ObjCProtocolQualifiers() = default;
5594
5595 ObjCProtocolDecl * const *getProtocolStorage() const {
5596 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5597 }
5598
5599 ObjCProtocolDecl **getProtocolStorage() {
5600 return static_cast<T*>(this)->getProtocolStorageImpl();
5601 }
5602
5603 void setNumProtocols(unsigned N) {
5604 static_cast<T*>(this)->setNumProtocolsImpl(N);
5605 }
5606
5607 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5608 setNumProtocols(protocols.size());
5609 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5610, __PRETTY_FUNCTION__))
5610 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5610, __PRETTY_FUNCTION__))
;
5611 if (!protocols.empty())
5612 memcpy(getProtocolStorage(), protocols.data(),
5613 protocols.size() * sizeof(ObjCProtocolDecl*));
5614 }
5615
5616public:
5617 using qual_iterator = ObjCProtocolDecl * const *;
5618 using qual_range = llvm::iterator_range<qual_iterator>;
5619
5620 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5621 qual_iterator qual_begin() const { return getProtocolStorage(); }
5622 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5623
5624 bool qual_empty() const { return getNumProtocols() == 0; }
5625
5626 /// Return the number of qualifying protocols in this type, or 0 if
5627 /// there are none.
5628 unsigned getNumProtocols() const {
5629 return static_cast<const T*>(this)->getNumProtocolsImpl();
5630 }
5631
5632 /// Fetch a protocol by index.
5633 ObjCProtocolDecl *getProtocol(unsigned I) const {
5634 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5634, __PRETTY_FUNCTION__))
;
5635 return qual_begin()[I];
5636 }
5637
5638 /// Retrieve all of the protocol qualifiers.
5639 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5640 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5641 }
5642};
5643
5644/// Represents a type parameter type in Objective C. It can take
5645/// a list of protocols.
5646class ObjCTypeParamType : public Type,
5647 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5648 public llvm::FoldingSetNode {
5649 friend class ASTContext;
5650 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5651
5652 /// The number of protocols stored on this type.
5653 unsigned NumProtocols : 6;
5654
5655 ObjCTypeParamDecl *OTPDecl;
5656
5657 /// The protocols are stored after the ObjCTypeParamType node. In the
5658 /// canonical type, the list of protocols are sorted alphabetically
5659 /// and uniqued.
5660 ObjCProtocolDecl **getProtocolStorageImpl();
5661
5662 /// Return the number of qualifying protocols in this interface type,
5663 /// or 0 if there are none.
5664 unsigned getNumProtocolsImpl() const {
5665 return NumProtocols;
5666 }
5667
5668 void setNumProtocolsImpl(unsigned N) {
5669 NumProtocols = N;
5670 }
5671
5672 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5673 QualType can,
5674 ArrayRef<ObjCProtocolDecl *> protocols);
5675
5676public:
5677 bool isSugared() const { return true; }
5678 QualType desugar() const { return getCanonicalTypeInternal(); }
5679
5680 static bool classof(const Type *T) {
5681 return T->getTypeClass() == ObjCTypeParam;
5682 }
5683
5684 void Profile(llvm::FoldingSetNodeID &ID);
5685 static void Profile(llvm::FoldingSetNodeID &ID,
5686 const ObjCTypeParamDecl *OTPDecl,
5687 ArrayRef<ObjCProtocolDecl *> protocols);
5688
5689 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5690};
5691
5692/// Represents a class type in Objective C.
5693///
5694/// Every Objective C type is a combination of a base type, a set of
5695/// type arguments (optional, for parameterized classes) and a list of
5696/// protocols.
5697///
5698/// Given the following declarations:
5699/// \code
5700/// \@class C<T>;
5701/// \@protocol P;
5702/// \endcode
5703///
5704/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5705/// with base C and no protocols.
5706///
5707/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5708/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5709/// protocol list.
5710/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5711/// and protocol list [P].
5712///
5713/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5714/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5715/// and no protocols.
5716///
5717/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5718/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5719/// this should get its own sugar class to better represent the source.
5720class ObjCObjectType : public Type,
5721 public ObjCProtocolQualifiers<ObjCObjectType> {
5722 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5723
5724 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5725 // after the ObjCObjectPointerType node.
5726 // ObjCObjectType.NumProtocols - the number of protocols stored
5727 // after the type arguments of ObjCObjectPointerType node.
5728 //
5729 // These protocols are those written directly on the type. If
5730 // protocol qualifiers ever become additive, the iterators will need
5731 // to get kindof complicated.
5732 //
5733 // In the canonical object type, these are sorted alphabetically
5734 // and uniqued.
5735
5736 /// Either a BuiltinType or an InterfaceType or sugar for either.
5737 QualType BaseType;
5738
5739 /// Cached superclass type.
5740 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5741 CachedSuperClassType;
5742
5743 QualType *getTypeArgStorage();
5744 const QualType *getTypeArgStorage() const {
5745 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5746 }
5747
5748 ObjCProtocolDecl **getProtocolStorageImpl();
5749 /// Return the number of qualifying protocols in this interface type,
5750 /// or 0 if there are none.
5751 unsigned getNumProtocolsImpl() const {
5752 return ObjCObjectTypeBits.NumProtocols;
5753 }
5754 void setNumProtocolsImpl(unsigned N) {
5755 ObjCObjectTypeBits.NumProtocols = N;
5756 }
5757
5758protected:
5759 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5760
5761 ObjCObjectType(QualType Canonical, QualType Base,
5762 ArrayRef<QualType> typeArgs,
5763 ArrayRef<ObjCProtocolDecl *> protocols,
5764 bool isKindOf);
5765
5766 ObjCObjectType(enum Nonce_ObjCInterface)
5767 : Type(ObjCInterface, QualType(), false, false, false, false),
5768 BaseType(QualType(this_(), 0)) {
5769 ObjCObjectTypeBits.NumProtocols = 0;
5770 ObjCObjectTypeBits.NumTypeArgs = 0;
5771 ObjCObjectTypeBits.IsKindOf = 0;
5772 }
5773
5774 void computeSuperClassTypeSlow() const;
5775
5776public:
5777 /// Gets the base type of this object type. This is always (possibly
5778 /// sugar for) one of:
5779 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5780 /// user, which is a typedef for an ObjCObjectPointerType)
5781 /// - the 'Class' builtin type (same caveat)
5782 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5783 QualType getBaseType() const { return BaseType; }
5784
5785 bool isObjCId() const {
5786 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5787 }
5788
5789 bool isObjCClass() const {
5790 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5791 }
5792
5793 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5794 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5795 bool isObjCUnqualifiedIdOrClass() const {
5796 if (!qual_empty()) return false;
5797 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5798 return T->getKind() == BuiltinType::ObjCId ||
5799 T->getKind() == BuiltinType::ObjCClass;
5800 return false;
5801 }
5802 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5803 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5804
5805 /// Gets the interface declaration for this object type, if the base type
5806 /// really is an interface.
5807 ObjCInterfaceDecl *getInterface() const;
5808
5809 /// Determine whether this object type is "specialized", meaning
5810 /// that it has type arguments.
5811 bool isSpecialized() const;
5812
5813 /// Determine whether this object type was written with type arguments.
5814 bool isSpecializedAsWritten() const {
5815 return ObjCObjectTypeBits.NumTypeArgs > 0;
5816 }
5817
5818 /// Determine whether this object type is "unspecialized", meaning
5819 /// that it has no type arguments.
5820 bool isUnspecialized() const { return !isSpecialized(); }
5821
5822 /// Determine whether this object type is "unspecialized" as
5823 /// written, meaning that it has no type arguments.
5824 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5825
5826 /// Retrieve the type arguments of this object type (semantically).
5827 ArrayRef<QualType> getTypeArgs() const;
5828
5829 /// Retrieve the type arguments of this object type as they were
5830 /// written.
5831 ArrayRef<QualType> getTypeArgsAsWritten() const {
5832 return llvm::makeArrayRef(getTypeArgStorage(),
5833 ObjCObjectTypeBits.NumTypeArgs);
5834 }
5835
5836 /// Whether this is a "__kindof" type as written.
5837 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5838
5839 /// Whether this ia a "__kindof" type (semantically).
5840 bool isKindOfType() const;
5841
5842 /// Retrieve the type of the superclass of this object type.
5843 ///
5844 /// This operation substitutes any type arguments into the
5845 /// superclass of the current class type, potentially producing a
5846 /// specialization of the superclass type. Produces a null type if
5847 /// there is no superclass.
5848 QualType getSuperClassType() const {
5849 if (!CachedSuperClassType.getInt())
5850 computeSuperClassTypeSlow();
5851
5852 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 5852, __PRETTY_FUNCTION__))
;
5853 return QualType(CachedSuperClassType.getPointer(), 0);
5854 }
5855
5856 /// Strip off the Objective-C "kindof" type and (with it) any
5857 /// protocol qualifiers.
5858 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5859
5860 bool isSugared() const { return false; }
5861 QualType desugar() const { return QualType(this, 0); }
5862
5863 static bool classof(const Type *T) {
5864 return T->getTypeClass() == ObjCObject ||
5865 T->getTypeClass() == ObjCInterface;
5866 }
5867};
5868
5869/// A class providing a concrete implementation
5870/// of ObjCObjectType, so as to not increase the footprint of
5871/// ObjCInterfaceType. Code outside of ASTContext and the core type
5872/// system should not reference this type.
5873class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5874 friend class ASTContext;
5875
5876 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5877 // will need to be modified.
5878
5879 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5880 ArrayRef<QualType> typeArgs,
5881 ArrayRef<ObjCProtocolDecl *> protocols,
5882 bool isKindOf)
5883 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5884
5885public:
5886 void Profile(llvm::FoldingSetNodeID &ID);
5887 static void Profile(llvm::FoldingSetNodeID &ID,
5888 QualType Base,
5889 ArrayRef<QualType> typeArgs,
5890 ArrayRef<ObjCProtocolDecl *> protocols,
5891 bool isKindOf);
5892};
5893
5894inline QualType *ObjCObjectType::getTypeArgStorage() {
5895 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5896}
5897
5898inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5899 return reinterpret_cast<ObjCProtocolDecl**>(
5900 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5901}
5902
5903inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5904 return reinterpret_cast<ObjCProtocolDecl**>(
5905 static_cast<ObjCTypeParamType*>(this)+1);
5906}
5907
5908/// Interfaces are the core concept in Objective-C for object oriented design.
5909/// They basically correspond to C++ classes. There are two kinds of interface
5910/// types: normal interfaces like `NSString`, and qualified interfaces, which
5911/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5912///
5913/// ObjCInterfaceType guarantees the following properties when considered
5914/// as a subtype of its superclass, ObjCObjectType:
5915/// - There are no protocol qualifiers. To reinforce this, code which
5916/// tries to invoke the protocol methods via an ObjCInterfaceType will
5917/// fail to compile.
5918/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5919/// T->getBaseType() == QualType(T, 0).
5920class ObjCInterfaceType : public ObjCObjectType {
5921 friend class ASTContext; // ASTContext creates these.
5922 friend class ASTReader;
5923 friend class ObjCInterfaceDecl;
5924 template <class T> friend class serialization::AbstractTypeReader;
5925
5926 mutable ObjCInterfaceDecl *Decl;
5927
5928 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5929 : ObjCObjectType(Nonce_ObjCInterface),
5930 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5931
5932public:
5933 /// Get the declaration of this interface.
5934 ObjCInterfaceDecl *getDecl() const { return Decl; }
5935
5936 bool isSugared() const { return false; }
5937 QualType desugar() const { return QualType(this, 0); }
5938
5939 static bool classof(const Type *T) {
5940 return T->getTypeClass() == ObjCInterface;
5941 }
5942
5943 // Nonsense to "hide" certain members of ObjCObjectType within this
5944 // class. People asking for protocols on an ObjCInterfaceType are
5945 // not going to get what they want: ObjCInterfaceTypes are
5946 // guaranteed to have no protocols.
5947 enum {
5948 qual_iterator,
5949 qual_begin,
5950 qual_end,
5951 getNumProtocols,
5952 getProtocol
5953 };
5954};
5955
5956inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5957 QualType baseType = getBaseType();
5958 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5959 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5960 return T->getDecl();
5961
5962 baseType = ObjT->getBaseType();
5963 }
5964
5965 return nullptr;
5966}
5967
5968/// Represents a pointer to an Objective C object.
5969///
5970/// These are constructed from pointer declarators when the pointee type is
5971/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5972/// types are typedefs for these, and the protocol-qualified types 'id<P>'
5973/// and 'Class<P>' are translated into these.
5974///
5975/// Pointers to pointers to Objective C objects are still PointerTypes;
5976/// only the first level of pointer gets it own type implementation.
5977class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5978 friend class ASTContext; // ASTContext creates these.
5979
5980 QualType PointeeType;
5981
5982 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5983 : Type(ObjCObjectPointer, Canonical,
5984 Pointee->isDependentType(),
5985 Pointee->isInstantiationDependentType(),
5986 Pointee->isVariablyModifiedType(),
5987 Pointee->containsUnexpandedParameterPack()),
5988 PointeeType(Pointee) {}
5989
5990public:
5991 /// Gets the type pointed to by this ObjC pointer.
5992 /// The result will always be an ObjCObjectType or sugar thereof.
5993 QualType getPointeeType() const { return PointeeType; }
5994
5995 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5996 ///
5997 /// This method is equivalent to getPointeeType() except that
5998 /// it discards any typedefs (or other sugar) between this
5999 /// type and the "outermost" object type. So for:
6000 /// \code
6001 /// \@class A; \@protocol P; \@protocol Q;
6002 /// typedef A<P> AP;
6003 /// typedef A A1;
6004 /// typedef A1<P> A1P;
6005 /// typedef A1P<Q> A1PQ;
6006 /// \endcode
6007 /// For 'A*', getObjectType() will return 'A'.
6008 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6009 /// For 'AP*', getObjectType() will return 'A<P>'.
6010 /// For 'A1*', getObjectType() will return 'A'.
6011 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6012 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6013 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6014 /// adding protocols to a protocol-qualified base discards the
6015 /// old qualifiers (for now). But if it didn't, getObjectType()
6016 /// would return 'A1P<Q>' (and we'd have to make iterating over
6017 /// qualifiers more complicated).
6018 const ObjCObjectType *getObjectType() const {
6019 return PointeeType->castAs<ObjCObjectType>();
6020 }
6021
6022 /// If this pointer points to an Objective C
6023 /// \@interface type, gets the type for that interface. Any protocol
6024 /// qualifiers on the interface are ignored.
6025 ///
6026 /// \return null if the base type for this pointer is 'id' or 'Class'
6027 const ObjCInterfaceType *getInterfaceType() const;
6028
6029 /// If this pointer points to an Objective \@interface
6030 /// type, gets the declaration for that interface.
6031 ///
6032 /// \return null if the base type for this pointer is 'id' or 'Class'
6033 ObjCInterfaceDecl *getInterfaceDecl() const {
6034 return getObjectType()->getInterface();
6035 }
6036
6037 /// True if this is equivalent to the 'id' type, i.e. if
6038 /// its object type is the primitive 'id' type with no protocols.
6039 bool isObjCIdType() const {
6040 return getObjectType()->isObjCUnqualifiedId();
6041 }
6042
6043 /// True if this is equivalent to the 'Class' type,
6044 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6045 bool isObjCClassType() const {
6046 return getObjectType()->isObjCUnqualifiedClass();
6047 }
6048
6049 /// True if this is equivalent to the 'id' or 'Class' type,
6050 bool isObjCIdOrClassType() const {
6051 return getObjectType()->isObjCUnqualifiedIdOrClass();
6052 }
6053
6054 /// True if this is equivalent to 'id<P>' for some non-empty set of
6055 /// protocols.
6056 bool isObjCQualifiedIdType() const {
6057 return getObjectType()->isObjCQualifiedId();
6058 }
6059
6060 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6061 /// protocols.
6062 bool isObjCQualifiedClassType() const {
6063 return getObjectType()->isObjCQualifiedClass();
6064 }
6065
6066 /// Whether this is a "__kindof" type.
6067 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6068
6069 /// Whether this type is specialized, meaning that it has type arguments.
6070 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6071
6072 /// Whether this type is specialized, meaning that it has type arguments.
6073 bool isSpecializedAsWritten() const {
6074 return getObjectType()->isSpecializedAsWritten();
6075 }
6076
6077 /// Whether this type is unspecialized, meaning that is has no type arguments.
6078 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6079
6080 /// Determine whether this object type is "unspecialized" as
6081 /// written, meaning that it has no type arguments.
6082 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6083
6084 /// Retrieve the type arguments for this type.
6085 ArrayRef<QualType> getTypeArgs() const {
6086 return getObjectType()->getTypeArgs();
6087 }
6088
6089 /// Retrieve the type arguments for this type.
6090 ArrayRef<QualType> getTypeArgsAsWritten() const {
6091 return getObjectType()->getTypeArgsAsWritten();
6092 }
6093
6094 /// An iterator over the qualifiers on the object type. Provided
6095 /// for convenience. This will always iterate over the full set of
6096 /// protocols on a type, not just those provided directly.
6097 using qual_iterator = ObjCObjectType::qual_iterator;
6098 using qual_range = llvm::iterator_range<qual_iterator>;
6099
6100 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6101
6102 qual_iterator qual_begin() const {
6103 return getObjectType()->qual_begin();
6104 }
6105
6106 qual_iterator qual_end() const {
6107 return getObjectType()->qual_end();
6108 }
6109
6110 bool qual_empty() const { return getObjectType()->qual_empty(); }
6111
6112 /// Return the number of qualifying protocols on the object type.
6113 unsigned getNumProtocols() const {
6114 return getObjectType()->getNumProtocols();
6115 }
6116
6117 /// Retrieve a qualifying protocol by index on the object type.
6118 ObjCProtocolDecl *getProtocol(unsigned I) const {
6119 return getObjectType()->getProtocol(I);
6120 }
6121
6122 bool isSugared() const { return false; }
6123 QualType desugar() const { return QualType(this, 0); }
6124
6125 /// Retrieve the type of the superclass of this object pointer type.
6126 ///
6127 /// This operation substitutes any type arguments into the
6128 /// superclass of the current class type, potentially producing a
6129 /// pointer to a specialization of the superclass type. Produces a
6130 /// null type if there is no superclass.
6131 QualType getSuperClassType() const;
6132
6133 /// Strip off the Objective-C "kindof" type and (with it) any
6134 /// protocol qualifiers.
6135 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6136 const ASTContext &ctx) const;
6137
6138 void Profile(llvm::FoldingSetNodeID &ID) {
6139 Profile(ID, getPointeeType());
6140 }
6141
6142 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6143 ID.AddPointer(T.getAsOpaquePtr());
6144 }
6145
6146 static bool classof(const Type *T) {
6147 return T->getTypeClass() == ObjCObjectPointer;
6148 }
6149};
6150
6151class AtomicType : public Type, public llvm::FoldingSetNode {
6152 friend class ASTContext; // ASTContext creates these.
6153
6154 QualType ValueType;
6155
6156 AtomicType(QualType ValTy, QualType Canonical)
6157 : Type(Atomic, Canonical, ValTy->isDependentType(),
6158 ValTy->isInstantiationDependentType(),
6159 ValTy->isVariablyModifiedType(),
6160 ValTy->containsUnexpandedParameterPack()),
6161 ValueType(ValTy) {}
6162
6163public:
6164 /// Gets the type contained by this atomic type, i.e.
6165 /// the type returned by performing an atomic load of this atomic type.
6166 QualType getValueType() const { return ValueType; }
6167
6168 bool isSugared() const { return false; }
6169 QualType desugar() const { return QualType(this, 0); }
6170
6171 void Profile(llvm::FoldingSetNodeID &ID) {
6172 Profile(ID, getValueType());
6173 }
6174
6175 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6176 ID.AddPointer(T.getAsOpaquePtr());
6177 }
6178
6179 static bool classof(const Type *T) {
6180 return T->getTypeClass() == Atomic;
6181 }
6182};
6183
6184/// PipeType - OpenCL20.
6185class PipeType : public Type, public llvm::FoldingSetNode {
6186 friend class ASTContext; // ASTContext creates these.
6187
6188 QualType ElementType;
6189 bool isRead;
6190
6191 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6192 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6193 elemType->isInstantiationDependentType(),
6194 elemType->isVariablyModifiedType(),
6195 elemType->containsUnexpandedParameterPack()),
6196 ElementType(elemType), isRead(isRead) {}
6197
6198public:
6199 QualType getElementType() const { return ElementType; }
6200
6201 bool isSugared() const { return false; }
6202
6203 QualType desugar() const { return QualType(this, 0); }
6204
6205 void Profile(llvm::FoldingSetNodeID &ID) {
6206 Profile(ID, getElementType(), isReadOnly());
6207 }
6208
6209 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6210 ID.AddPointer(T.getAsOpaquePtr());
6211 ID.AddBoolean(isRead);
6212 }
6213
6214 static bool classof(const Type *T) {
6215 return T->getTypeClass() == Pipe;
6216 }
6217
6218 bool isReadOnly() const { return isRead; }
6219};
6220
6221/// A qualifier set is used to build a set of qualifiers.
6222class QualifierCollector : public Qualifiers {
6223public:
6224 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6225
6226 /// Collect any qualifiers on the given type and return an
6227 /// unqualified type. The qualifiers are assumed to be consistent
6228 /// with those already in the type.
6229 const Type *strip(QualType type) {
6230 addFastQualifiers(type.getLocalFastQualifiers());
6231 if (!type.hasLocalNonFastQualifiers())
6232 return type.getTypePtrUnsafe();
6233
6234 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6235 addConsistentQualifiers(extQuals->getQualifiers());
6236 return extQuals->getBaseType();
6237 }
6238
6239 /// Apply the collected qualifiers to the given type.
6240 QualType apply(const ASTContext &Context, QualType QT) const;
6241
6242 /// Apply the collected qualifiers to the given type.
6243 QualType apply(const ASTContext &Context, const Type* T) const;
6244};
6245
6246/// A container of type source information.
6247///
6248/// A client can read the relevant info using TypeLoc wrappers, e.g:
6249/// @code
6250/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
6251/// TL.getBeginLoc().print(OS, SrcMgr);
6252/// @endcode
6253class alignas(8) TypeSourceInfo {
6254 // Contains a memory block after the class, used for type source information,
6255 // allocated by ASTContext.
6256 friend class ASTContext;
6257
6258 QualType Ty;
6259
6260 TypeSourceInfo(QualType ty) : Ty(ty) {}
6261
6262public:
6263 /// Return the type wrapped by this type source info.
6264 QualType getType() const { return Ty; }
6265
6266 /// Return the TypeLoc wrapper for the type source info.
6267 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
6268
6269 /// Override the type stored in this TypeSourceInfo. Use with caution!
6270 void overrideType(QualType T) { Ty = T; }
6271};
6272
6273// Inline function definitions.
6274
6275inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6276 SplitQualType desugar =
6277 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6278 desugar.Quals.addConsistentQualifiers(Quals);
6279 return desugar;
6280}
6281
6282inline const Type *QualType::getTypePtr() const {
6283 return getCommonPtr()->BaseType;
6284}
6285
6286inline const Type *QualType::getTypePtrOrNull() const {
6287 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6288}
6289
6290inline SplitQualType QualType::split() const {
6291 if (!hasLocalNonFastQualifiers())
6292 return SplitQualType(getTypePtrUnsafe(),
6293 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6294
6295 const ExtQuals *eq = getExtQualsUnsafe();
6296 Qualifiers qs = eq->getQualifiers();
6297 qs.addFastQualifiers(getLocalFastQualifiers());
6298 return SplitQualType(eq->getBaseType(), qs);
6299}
6300
6301inline Qualifiers QualType::getLocalQualifiers() const {
6302 Qualifiers Quals;
6303 if (hasLocalNonFastQualifiers())
6304 Quals = getExtQualsUnsafe()->getQualifiers();
6305 Quals.addFastQualifiers(getLocalFastQualifiers());
6306 return Quals;
6307}
6308
6309inline Qualifiers QualType::getQualifiers() const {
6310 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6311 quals.addFastQualifiers(getLocalFastQualifiers());
6312 return quals;
6313}
6314
6315inline unsigned QualType::getCVRQualifiers() const {
6316 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6317 cvr |= getLocalCVRQualifiers();
6318 return cvr;
6319}
6320
6321inline QualType QualType::getCanonicalType() const {
6322 QualType canon = getCommonPtr()->CanonicalType;
6323 return canon.withFastQualifiers(getLocalFastQualifiers());
6324}
6325
6326inline bool QualType::isCanonical() const {
6327 return getTypePtr()->isCanonicalUnqualified();
6328}
6329
6330inline bool QualType::isCanonicalAsParam() const {
6331 if (!isCanonical()) return false;
6332 if (hasLocalQualifiers()) return false;
6333
6334 const Type *T = getTypePtr();
6335 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6336 return false;
6337
6338 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6339}
6340
6341inline bool QualType::isConstQualified() const {
6342 return isLocalConstQualified() ||
6343 getCommonPtr()->CanonicalType.isLocalConstQualified();
6344}
6345
6346inline bool QualType::isRestrictQualified() const {
6347 return isLocalRestrictQualified() ||
6348 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6349}
6350
6351
6352inline bool QualType::isVolatileQualified() const {
6353 return isLocalVolatileQualified() ||
6354 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6355}
6356
6357inline bool QualType::hasQualifiers() const {
6358 return hasLocalQualifiers() ||
6359 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6360}
6361
6362inline QualType QualType::getUnqualifiedType() const {
6363 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6364 return QualType(getTypePtr(), 0);
6365
6366 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6367}
6368
6369inline SplitQualType QualType::getSplitUnqualifiedType() const {
6370 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6371 return split();
6372
6373 return getSplitUnqualifiedTypeImpl(*this);
6374}
6375
6376inline void QualType::removeLocalConst() {
6377 removeLocalFastQualifiers(Qualifiers::Const);
6378}
6379
6380inline void QualType::removeLocalRestrict() {
6381 removeLocalFastQualifiers(Qualifiers::Restrict);
6382}
6383
6384inline void QualType::removeLocalVolatile() {
6385 removeLocalFastQualifiers(Qualifiers::Volatile);
6386}
6387
6388inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6389 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 6389, __PRETTY_FUNCTION__))
;
6390 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6391 "Fast bits differ from CVR bits!");
6392
6393 // Fast path: we don't need to touch the slow qualifiers.
6394 removeLocalFastQualifiers(Mask);
6395}
6396
6397/// Check if this type has any address space qualifier.
6398inline bool QualType::hasAddressSpace() const {
6399 return getQualifiers().hasAddressSpace();
6400}
6401
6402/// Return the address space of this type.
6403inline LangAS QualType::getAddressSpace() const {
6404 return getQualifiers().getAddressSpace();
6405}
6406
6407/// Return the gc attribute of this type.
6408inline Qualifiers::GC QualType::getObjCGCAttr() const {
6409 return getQualifiers().getObjCGCAttr();
6410}
6411
6412inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6413 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6414 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6415 return false;
6416}
6417
6418inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6419 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6420 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6421 return false;
6422}
6423
6424inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6425 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6426 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6427 return false;
6428}
6429
6430inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6431 if (const auto *PT = t.getAs<PointerType>()) {
6432 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6433 return FT->getExtInfo();
6434 } else if (const auto *FT = t.getAs<FunctionType>())
6435 return FT->getExtInfo();
6436
6437 return FunctionType::ExtInfo();
6438}
6439
6440inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6441 return getFunctionExtInfo(*t);
6442}
6443
6444/// Determine whether this type is more
6445/// qualified than the Other type. For example, "const volatile int"
6446/// is more qualified than "const int", "volatile int", and
6447/// "int". However, it is not more qualified than "const volatile
6448/// int".
6449inline bool QualType::isMoreQualifiedThan(QualType other) const {
6450 Qualifiers MyQuals = getQualifiers();
6451 Qualifiers OtherQuals = other.getQualifiers();
6452 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6453}
6454
6455/// Determine whether this type is at last
6456/// as qualified as the Other type. For example, "const volatile
6457/// int" is at least as qualified as "const int", "volatile int",
6458/// "int", and "const volatile int".
6459inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6460 Qualifiers OtherQuals = other.getQualifiers();
6461
6462 // Ignore __unaligned qualifier if this type is a void.
6463 if (getUnqualifiedType()->isVoidType())
6464 OtherQuals.removeUnaligned();
6465
6466 return getQualifiers().compatiblyIncludes(OtherQuals);
6467}
6468
6469/// If Type is a reference type (e.g., const
6470/// int&), returns the type that the reference refers to ("const
6471/// int"). Otherwise, returns the type itself. This routine is used
6472/// throughout Sema to implement C++ 5p6:
6473///
6474/// If an expression initially has the type "reference to T" (8.3.2,
6475/// 8.5.3), the type is adjusted to "T" prior to any further
6476/// analysis, the expression designates the object or function
6477/// denoted by the reference, and the expression is an lvalue.
6478inline QualType QualType::getNonReferenceType() const {
6479 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6480 return RefType->getPointeeType();
6481 else
6482 return *this;
6483}
6484
6485inline bool QualType::isCForbiddenLValueType() const {
6486 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6487 getTypePtr()->isFunctionType());
6488}
6489
6490/// Tests whether the type is categorized as a fundamental type.
6491///
6492/// \returns True for types specified in C++0x [basic.fundamental].
6493inline bool Type::isFundamentalType() const {
6494 return isVoidType() ||
6495 isNullPtrType() ||
6496 // FIXME: It's really annoying that we don't have an
6497 // 'isArithmeticType()' which agrees with the standard definition.
6498 (isArithmeticType() && !isEnumeralType());
6499}
6500
6501/// Tests whether the type is categorized as a compound type.
6502///
6503/// \returns True for types specified in C++0x [basic.compound].
6504inline bool Type::isCompoundType() const {
6505 // C++0x [basic.compound]p1:
6506 // Compound types can be constructed in the following ways:
6507 // -- arrays of objects of a given type [...];
6508 return isArrayType() ||
6509 // -- functions, which have parameters of given types [...];
6510 isFunctionType() ||
6511 // -- pointers to void or objects or functions [...];
6512 isPointerType() ||
6513 // -- references to objects or functions of a given type. [...]
6514 isReferenceType() ||
6515 // -- classes containing a sequence of objects of various types, [...];
6516 isRecordType() ||
6517 // -- unions, which are classes capable of containing objects of different
6518 // types at different times;
6519 isUnionType() ||
6520 // -- enumerations, which comprise a set of named constant values. [...];
6521 isEnumeralType() ||
6522 // -- pointers to non-static class members, [...].
6523 isMemberPointerType();
6524}
6525
6526inline bool Type::isFunctionType() const {
6527 return isa<FunctionType>(CanonicalType);
6528}
6529
6530inline bool Type::isPointerType() const {
6531 return isa<PointerType>(CanonicalType);
6532}
6533
6534inline bool Type::isAnyPointerType() const {
6535 return isPointerType() || isObjCObjectPointerType();
6536}
6537
6538inline bool Type::isBlockPointerType() const {
6539 return isa<BlockPointerType>(CanonicalType);
6540}
6541
6542inline bool Type::isReferenceType() const {
6543 return isa<ReferenceType>(CanonicalType);
6544}
6545
6546inline bool Type::isLValueReferenceType() const {
6547 return isa<LValueReferenceType>(CanonicalType);
6548}
6549
6550inline bool Type::isRValueReferenceType() const {
6551 return isa<RValueReferenceType>(CanonicalType);
6552}
6553
6554inline bool Type::isObjectPointerType() const {
6555 // Note: an "object pointer type" is not the same thing as a pointer to an
6556 // object type; rather, it is a pointer to an object type or a pointer to cv
6557 // void.
6558 if (const auto *T = getAs<PointerType>())
6559 return !T->getPointeeType()->isFunctionType();
6560 else
6561 return false;
6562}
6563
6564inline bool Type::isFunctionPointerType() const {
6565 if (const auto *T = getAs<PointerType>())
6566 return T->getPointeeType()->isFunctionType();
6567 else
6568 return false;
6569}
6570
6571inline bool Type::isFunctionReferenceType() const {
6572 if (const auto *T = getAs<ReferenceType>())
6573 return T->getPointeeType()->isFunctionType();
6574 else
6575 return false;
6576}
6577
6578inline bool Type::isMemberPointerType() const {
6579 return isa<MemberPointerType>(CanonicalType);
6580}
6581
6582inline bool Type::isMemberFunctionPointerType() const {
6583 if (const auto *T = getAs<MemberPointerType>())
6584 return T->isMemberFunctionPointer();
6585 else
6586 return false;
6587}
6588
6589inline bool Type::isMemberDataPointerType() const {
6590 if (const auto *T = getAs<MemberPointerType>())
6591 return T->isMemberDataPointer();
6592 else
6593 return false;
6594}
6595
6596inline bool Type::isArrayType() const {
6597 return isa<ArrayType>(CanonicalType);
6598}
6599
6600inline bool Type::isConstantArrayType() const {
6601 return isa<ConstantArrayType>(CanonicalType);
6602}
6603
6604inline bool Type::isIncompleteArrayType() const {
6605 return isa<IncompleteArrayType>(CanonicalType);
6606}
6607
6608inline bool Type::isVariableArrayType() const {
6609 return isa<VariableArrayType>(CanonicalType);
6610}
6611
6612inline bool Type::isDependentSizedArrayType() const {
6613 return isa<DependentSizedArrayType>(CanonicalType);
6614}
6615
6616inline bool Type::isBuiltinType() const {
6617 return isa<BuiltinType>(CanonicalType);
6618}
6619
6620inline bool Type::isRecordType() const {
6621 return isa<RecordType>(CanonicalType);
6622}
6623
6624inline bool Type::isEnumeralType() const {
6625 return isa<EnumType>(CanonicalType);
6626}
6627
6628inline bool Type::isAnyComplexType() const {
6629 return isa<ComplexType>(CanonicalType);
6630}
6631
6632inline bool Type::isVectorType() const {
6633 return isa<VectorType>(CanonicalType);
6634}
6635
6636inline bool Type::isExtVectorType() const {
6637 return isa<ExtVectorType>(CanonicalType);
6638}
6639
6640inline bool Type::isDependentAddressSpaceType() const {
6641 return isa<DependentAddressSpaceType>(CanonicalType);
6642}
6643
6644inline bool Type::isObjCObjectPointerType() const {
6645 return isa<ObjCObjectPointerType>(CanonicalType);
6646}
6647
6648inline bool Type::isObjCObjectType() const {
6649 return isa<ObjCObjectType>(CanonicalType);
6650}
6651
6652inline bool Type::isObjCObjectOrInterfaceType() const {
6653 return isa<ObjCInterfaceType>(CanonicalType) ||
6654 isa<ObjCObjectType>(CanonicalType);
6655}
6656
6657inline bool Type::isAtomicType() const {
6658 return isa<AtomicType>(CanonicalType);
6659}
6660
6661inline bool Type::isUndeducedAutoType() const {
6662 return isa<AutoType>(CanonicalType);
6663}
6664
6665inline bool Type::isObjCQualifiedIdType() const {
6666 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6667 return OPT->isObjCQualifiedIdType();
6668 return false;
6669}
6670
6671inline bool Type::isObjCQualifiedClassType() const {
6672 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6673 return OPT->isObjCQualifiedClassType();
6674 return false;
6675}
6676
6677inline bool Type::isObjCIdType() const {
6678 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6679 return OPT->isObjCIdType();
6680 return false;
6681}
6682
6683inline bool Type::isObjCClassType() const {
6684 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6685 return OPT->isObjCClassType();
6686 return false;
6687}
6688
6689inline bool Type::isObjCSelType() const {
6690 if (const auto *OPT = getAs<PointerType>())
6691 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6692 return false;
6693}
6694
6695inline bool Type::isObjCBuiltinType() const {
6696 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6697}
6698
6699inline bool Type::isDecltypeType() const {
6700 return isa<DecltypeType>(this);
6701}
6702
6703#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6704 inline bool Type::is##Id##Type() const { \
6705 return isSpecificBuiltinType(BuiltinType::Id); \
6706 }
6707#include "clang/Basic/OpenCLImageTypes.def"
6708
6709inline bool Type::isSamplerT() const {
6710 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6711}
6712
6713inline bool Type::isEventT() const {
6714 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6715}
6716
6717inline bool Type::isClkEventT() const {
6718 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6719}
6720
6721inline bool Type::isQueueT() const {
6722 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6723}
6724
6725inline bool Type::isReserveIDT() const {
6726 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6727}
6728
6729inline bool Type::isImageType() const {
6730#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6731 return
6732#include "clang/Basic/OpenCLImageTypes.def"
6733 false; // end boolean or operation
6734}
6735
6736inline bool Type::isPipeType() const {
6737 return isa<PipeType>(CanonicalType);
6738}
6739
6740#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6741 inline bool Type::is##Id##Type() const { \
6742 return isSpecificBuiltinType(BuiltinType::Id); \
6743 }
6744#include "clang/Basic/OpenCLExtensionTypes.def"
6745
6746inline bool Type::isOCLIntelSubgroupAVCType() const {
6747#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6748 isOCLIntelSubgroupAVC##Id##Type() ||
6749 return
6750#include "clang/Basic/OpenCLExtensionTypes.def"
6751 false; // end of boolean or operation
6752}
6753
6754inline bool Type::isOCLExtOpaqueType() const {
6755#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6756 return
6757#include "clang/Basic/OpenCLExtensionTypes.def"
6758 false; // end of boolean or operation
6759}
6760
6761inline bool Type::isOpenCLSpecificType() const {
6762 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6763 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6764}
6765
6766inline bool Type::isTemplateTypeParmType() const {
6767 return isa<TemplateTypeParmType>(CanonicalType);
6768}
6769
6770inline bool Type::isSpecificBuiltinType(unsigned K) const {
6771 if (const BuiltinType *BT = getAs<BuiltinType>())
6772 if (BT->getKind() == (BuiltinType::Kind) K)
6773 return true;
6774 return false;
6775}
6776
6777inline bool Type::isPlaceholderType() const {
6778 if (const auto *BT = dyn_cast<BuiltinType>(this))
6779 return BT->isPlaceholderType();
6780 return false;
6781}
6782
6783inline const BuiltinType *Type::getAsPlaceholderType() const {
6784 if (const auto *BT = dyn_cast<BuiltinType>(this))
6785 if (BT->isPlaceholderType())
6786 return BT;
6787 return nullptr;
6788}
6789
6790inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6791 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 6791, __PRETTY_FUNCTION__))
;
6792 if (const auto *BT = dyn_cast<BuiltinType>(this))
6793 return (BT->getKind() == (BuiltinType::Kind) K);
6794 return false;
6795}
6796
6797inline bool Type::isNonOverloadPlaceholderType() const {
6798 if (const auto *BT = dyn_cast<BuiltinType>(this))
6799 return BT->isNonOverloadPlaceholderType();
6800 return false;
6801}
6802
6803inline bool Type::isVoidType() const {
6804 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6805 return BT->getKind() == BuiltinType::Void;
6806 return false;
6807}
6808
6809inline bool Type::isHalfType() const {
6810 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6811 return BT->getKind() == BuiltinType::Half;
6812 // FIXME: Should we allow complex __fp16? Probably not.
6813 return false;
6814}
6815
6816inline bool Type::isFloat16Type() const {
6817 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6818 return BT->getKind() == BuiltinType::Float16;
6819 return false;
6820}
6821
6822inline bool Type::isFloat128Type() const {
6823 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6824 return BT->getKind() == BuiltinType::Float128;
6825 return false;
6826}
6827
6828inline bool Type::isNullPtrType() const {
6829 if (const auto *BT = getAs<BuiltinType>())
6830 return BT->getKind() == BuiltinType::NullPtr;
6831 return false;
6832}
6833
6834bool IsEnumDeclComplete(EnumDecl *);
6835bool IsEnumDeclScoped(EnumDecl *);
6836
6837inline bool Type::isIntegerType() const {
6838 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6839 return BT->getKind() >= BuiltinType::Bool &&
6840 BT->getKind() <= BuiltinType::Int128;
6841 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6842 // Incomplete enum types are not treated as integer types.
6843 // FIXME: In C++, enum types are never integer types.
6844 return IsEnumDeclComplete(ET->getDecl()) &&
6845 !IsEnumDeclScoped(ET->getDecl());
6846 }
6847 return false;
6848}
6849
6850inline bool Type::isFixedPointType() const {
6851 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6852 return BT->getKind() >= BuiltinType::ShortAccum &&
6853 BT->getKind() <= BuiltinType::SatULongFract;
6854 }
6855 return false;
6856}
6857
6858inline bool Type::isFixedPointOrIntegerType() const {
6859 return isFixedPointType() || isIntegerType();
6860}
6861
6862inline bool Type::isSaturatedFixedPointType() const {
6863 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6864 return BT->getKind() >= BuiltinType::SatShortAccum &&
6865 BT->getKind() <= BuiltinType::SatULongFract;
6866 }
6867 return false;
6868}
6869
6870inline bool Type::isUnsaturatedFixedPointType() const {
6871 return isFixedPointType() && !isSaturatedFixedPointType();
6872}
6873
6874inline bool Type::isSignedFixedPointType() const {
6875 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6876 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6877 BT->getKind() <= BuiltinType::LongAccum) ||
6878 (BT->getKind() >= BuiltinType::ShortFract &&
6879 BT->getKind() <= BuiltinType::LongFract) ||
6880 (BT->getKind() >= BuiltinType::SatShortAccum &&
6881 BT->getKind() <= BuiltinType::SatLongAccum) ||
6882 (BT->getKind() >= BuiltinType::SatShortFract &&
6883 BT->getKind() <= BuiltinType::SatLongFract));
6884 }
6885 return false;
6886}
6887
6888inline bool Type::isUnsignedFixedPointType() const {
6889 return isFixedPointType() && !isSignedFixedPointType();
6890}
6891
6892inline bool Type::isScalarType() const {
6893 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6894 return BT->getKind() > BuiltinType::Void &&
6895 BT->getKind() <= BuiltinType::NullPtr;
6896 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6897 // Enums are scalar types, but only if they are defined. Incomplete enums
6898 // are not treated as scalar types.
6899 return IsEnumDeclComplete(ET->getDecl());
6900 return isa<PointerType>(CanonicalType) ||
6901 isa<BlockPointerType>(CanonicalType) ||
6902 isa<MemberPointerType>(CanonicalType) ||
6903 isa<ComplexType>(CanonicalType) ||
6904 isa<ObjCObjectPointerType>(CanonicalType);
6905}
6906
6907inline bool Type::isIntegralOrEnumerationType() const {
6908 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6909 return BT->getKind() >= BuiltinType::Bool &&
6910 BT->getKind() <= BuiltinType::Int128;
6911
6912 // Check for a complete enum type; incomplete enum types are not properly an
6913 // enumeration type in the sense required here.
6914 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6915 return IsEnumDeclComplete(ET->getDecl());
6916
6917 return false;
6918}
6919
6920inline bool Type::isBooleanType() const {
6921 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6922 return BT->getKind() == BuiltinType::Bool;
6923 return false;
6924}
6925
6926inline bool Type::isUndeducedType() const {
6927 auto *DT = getContainedDeducedType();
6928 return DT && !DT->isDeduced();
6929}
6930
6931/// Determines whether this is a type for which one can define
6932/// an overloaded operator.
6933inline bool Type::isOverloadableType() const {
6934 return isDependentType() || isRecordType() || isEnumeralType();
6935}
6936
6937/// Determines whether this type can decay to a pointer type.
6938inline bool Type::canDecayToPointerType() const {
6939 return isFunctionType() || isArrayType();
6940}
6941
6942inline bool Type::hasPointerRepresentation() const {
6943 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6944 isObjCObjectPointerType() || isNullPtrType());
6945}
6946
6947inline bool Type::hasObjCPointerRepresentation() const {
6948 return isObjCObjectPointerType();
6949}
6950
6951inline const Type *Type::getBaseElementTypeUnsafe() const {
6952 const Type *type = this;
6953 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6954 type = arrayType->getElementType().getTypePtr();
6955 return type;
6956}
6957
6958inline const Type *Type::getPointeeOrArrayElementType() const {
6959 const Type *type = this;
6960 if (type->isAnyPointerType())
6961 return type->getPointeeType().getTypePtr();
6962 else if (type->isArrayType())
6963 return type->getBaseElementTypeUnsafe();
6964 return type;
6965}
6966/// Insertion operator for diagnostics. This allows sending address spaces into
6967/// a diagnostic with <<.
6968inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6969 LangAS AS) {
6970 DB.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
6971 DiagnosticsEngine::ArgumentKind::ak_addrspace);
6972 return DB;
6973}
6974
6975/// Insertion operator for partial diagnostics. This allows sending adress
6976/// spaces into a diagnostic with <<.
6977inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6978 LangAS AS) {
6979 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
6980 DiagnosticsEngine::ArgumentKind::ak_addrspace);
6981 return PD;
6982}
6983
6984/// Insertion operator for diagnostics. This allows sending Qualifiers into a
6985/// diagnostic with <<.
6986inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6987 Qualifiers Q) {
6988 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6989 DiagnosticsEngine::ArgumentKind::ak_qual);
6990 return DB;
6991}
6992
6993/// Insertion operator for partial diagnostics. This allows sending Qualifiers
6994/// into a diagnostic with <<.
6995inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6996 Qualifiers Q) {
6997 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6998 DiagnosticsEngine::ArgumentKind::ak_qual);
6999 return PD;
7000}
7001
7002/// Insertion operator for diagnostics. This allows sending QualType's into a
7003/// diagnostic with <<.
7004inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
7005 QualType T) {
7006 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7007 DiagnosticsEngine::ak_qualtype);
7008 return DB;
7009}
7010
7011/// Insertion operator for partial diagnostics. This allows sending QualType's
7012/// into a diagnostic with <<.
7013inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
7014 QualType T) {
7015 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7016 DiagnosticsEngine::ak_qualtype);
7017 return PD;
7018}
7019
7020// Helper class template that is used by Type::getAs to ensure that one does
7021// not try to look through a qualified type to get to an array type.
7022template <typename T>
7023using TypeIsArrayType =
7024 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7025 std::is_base_of<ArrayType, T>::value>;
7026
7027// Member-template getAs<specific type>'.
7028template <typename T> const T *Type::getAs() const {
7029 static_assert(!TypeIsArrayType<T>::value,
7030 "ArrayType cannot be used with getAs!");
7031
7032 // If this is directly a T type, return it.
7033 if (const auto *Ty = dyn_cast<T>(this))
7034 return Ty;
7035
7036 // If the canonical form of this type isn't the right kind, reject it.
7037 if (!isa<T>(CanonicalType))
7038 return nullptr;
7039
7040 // If this is a typedef for the type, strip the typedef off without
7041 // losing all typedef information.
7042 return cast<T>(getUnqualifiedDesugaredType());
7043}
7044
7045template <typename T> const T *Type::getAsAdjusted() const {
7046 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7047
7048 // If this is directly a T type, return it.
7049 if (const auto *Ty = dyn_cast<T>(this))
7050 return Ty;
7051
7052 // If the canonical form of this type isn't the right kind, reject it.
7053 if (!isa<T>(CanonicalType))
7054 return nullptr;
7055
7056 // Strip off type adjustments that do not modify the underlying nature of the
7057 // type.
7058 const Type *Ty = this;
7059 while (Ty) {
7060 if (const auto *A = dyn_cast<AttributedType>(Ty))
7061 Ty = A->getModifiedType().getTypePtr();
7062 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7063 Ty = E->desugar().getTypePtr();
7064 else if (const auto *P = dyn_cast<ParenType>(Ty))
7065 Ty = P->desugar().getTypePtr();
7066 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7067 Ty = A->desugar().getTypePtr();
7068 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7069 Ty = M->desugar().getTypePtr();
7070 else
7071 break;
7072 }
7073
7074 // Just because the canonical type is correct does not mean we can use cast<>,
7075 // since we may not have stripped off all the sugar down to the base type.
7076 return dyn_cast<T>(Ty);
7077}
7078
7079inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7080 // If this is directly an array type, return it.
7081 if (const auto *arr = dyn_cast<ArrayType>(this))
7082 return arr;
7083
7084 // If the canonical form of this type isn't the right kind, reject it.
7085 if (!isa<ArrayType>(CanonicalType))
7086 return nullptr;
7087
7088 // If this is a typedef for the type, strip the typedef off without
7089 // losing all typedef information.
7090 return cast<ArrayType>(getUnqualifiedDesugaredType());
7091}
7092
7093template <typename T> const T *Type::castAs() const {
7094 static_assert(!TypeIsArrayType<T>::value,
7095 "ArrayType cannot be used with castAs!");
7096
7097 if (const auto *ty = dyn_cast<T>(this)) return ty;
7098 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 7098, __PRETTY_FUNCTION__))
;
7099 return cast<T>(getUnqualifiedDesugaredType());
7100}
7101
7102inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7103 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 7103, __PRETTY_FUNCTION__))
;
7104 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7105 return cast<ArrayType>(getUnqualifiedDesugaredType());
7106}
7107
7108DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7109 QualType CanonicalPtr)
7110 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7111#ifndef NDEBUG
7112 QualType Adjusted = getAdjustedType();
7113 (void)AttributedType::stripOuterNullability(Adjusted);
7114 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/AST/Type.h"
, 7114, __PRETTY_FUNCTION__))
;
7115#endif
7116}
7117
7118QualType DecayedType::getPointeeType() const {
7119 QualType Decayed = getDecayedType();
7120 (void)AttributedType::stripOuterNullability(Decayed);
7121 return cast<PointerType>(Decayed)->getPointeeType();
7122}
7123
7124// Get the decimal string representation of a fixed point type, represented
7125// as a scaled integer.
7126// TODO: At some point, we should change the arguments to instead just accept an
7127// APFixedPoint instead of APSInt and scale.
7128void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
7129 unsigned Scale);
7130
7131} // namespace clang
7132
7133#endif // LLVM_CLANG_AST_TYPE_H

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/PointerIntPair.h

1//===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- 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 PointerIntPair class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_POINTERINTPAIR_H
14#define LLVM_ADT_POINTERINTPAIR_H
15
16#include "llvm/Support/Compiler.h"
17#include "llvm/Support/PointerLikeTypeTraits.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <cstdint>
21#include <limits>
22
23namespace llvm {
24
25template <typename T> struct DenseMapInfo;
26template <typename PointerT, unsigned IntBits, typename PtrTraits>
27struct PointerIntPairInfo;
28
29/// PointerIntPair - This class implements a pair of a pointer and small
30/// integer. It is designed to represent this in the space required by one
31/// pointer by bitmangling the integer into the low part of the pointer. This
32/// can only be done for small integers: typically up to 3 bits, but it depends
33/// on the number of bits available according to PointerLikeTypeTraits for the
34/// type.
35///
36/// Note that PointerIntPair always puts the IntVal part in the highest bits
37/// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for
38/// the bool into bit #2, not bit #0, which allows the low two bits to be used
39/// for something else. For example, this allows:
40/// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool>
41/// ... and the two bools will land in different bits.
42template <typename PointerTy, unsigned IntBits, typename IntType = unsigned,
43 typename PtrTraits = PointerLikeTypeTraits<PointerTy>,
44 typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>>
45class PointerIntPair {
46 // Used by MSVC visualizer and generally helpful for debugging/visualizing.
47 using InfoTy = Info;
48 intptr_t Value = 0;
49
50public:
51 constexpr PointerIntPair() = default;
52
53 PointerIntPair(PointerTy PtrVal, IntType IntVal) {
54 setPointerAndInt(PtrVal, IntVal);
55 }
56
57 explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); }
58
59 PointerTy getPointer() const { return Info::getPointer(Value); }
60
61 IntType getInt() const { return (IntType)Info::getInt(Value); }
62
63 void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
64 Value = Info::updatePointer(Value, PtrVal);
65 }
66
67 void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION& {
68 Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal));
69 }
70
71 void initWithPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& {
72 Value = Info::updatePointer(0, PtrVal);
73 }
74
75 void setPointerAndInt(PointerTy PtrVal, IntType IntVal) LLVM_LVALUE_FUNCTION& {
76 Value = Info::updateInt(Info::updatePointer(0, PtrVal),
77 static_cast<intptr_t>(IntVal));
78 }
79
80 PointerTy const *getAddrOfPointer() const {
81 return const_cast<PointerIntPair *>(this)->getAddrOfPointer();
82 }
83
84 PointerTy *getAddrOfPointer() {
85 assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
86 "Can only return the address if IntBits is cleared and "((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
87 "PtrTraits doesn't change the pointer")((Value == reinterpret_cast<intptr_t>(getPointer()) &&
"Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer"
) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/PointerIntPair.h"
, 87, __PRETTY_FUNCTION__))
;
88 return reinterpret_cast<PointerTy *>(&Value);
89 }
90
91 void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); }
92
93 void setFromOpaqueValue(void *Val) LLVM_LVALUE_FUNCTION& {
94 Value = reinterpret_cast<intptr_t>(Val);
95 }
96
97 static PointerIntPair getFromOpaqueValue(void *V) {
98 PointerIntPair P;
99 P.setFromOpaqueValue(V);
100 return P;
101 }
102
103 // Allow PointerIntPairs to be created from const void * if and only if the
104 // pointer type could be created from a const void *.
105 static PointerIntPair getFromOpaqueValue(const void *V) {
106 (void)PtrTraits::getFromVoidPointer(V);
107 return getFromOpaqueValue(const_cast<void *>(V));
108 }
109
110 bool operator==(const PointerIntPair &RHS) const {
111 return Value == RHS.Value;
19
Assuming 'Value' is not equal to 'RHS.Value'
20
Returning zero, which participates in a condition later
112 }
113
114 bool operator!=(const PointerIntPair &RHS) const {
115 return Value != RHS.Value;
116 }
117
118 bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; }
119 bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; }
120
121 bool operator<=(const PointerIntPair &RHS) const {
122 return Value <= RHS.Value;
123 }
124
125 bool operator>=(const PointerIntPair &RHS) const {
126 return Value >= RHS.Value;
127 }
128};
129
130// Specialize is_trivially_copyable to avoid limitation of llvm::is_trivially_copyable
131// when compiled with gcc 4.9.
132template <typename PointerTy, unsigned IntBits, typename IntType,
133 typename PtrTraits,
134 typename Info>
135struct is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>> : std::true_type {
136#ifdef HAVE_STD_IS_TRIVIALLY_COPYABLE
137 static_assert(std::is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>>::value,
138 "inconsistent behavior between llvm:: and std:: implementation of is_trivially_copyable");
139#endif
140};
141
142
143template <typename PointerT, unsigned IntBits, typename PtrTraits>
144struct PointerIntPairInfo {
145 static_assert(PtrTraits::NumLowBitsAvailable <
146 std::numeric_limits<uintptr_t>::digits,
147 "cannot use a pointer type that has all bits free");
148 static_assert(IntBits <= PtrTraits::NumLowBitsAvailable,
149 "PointerIntPair with integer size too large for pointer");
150 enum MaskAndShiftConstants : uintptr_t {
151 /// PointerBitMask - The bits that come from the pointer.
152 PointerBitMask =
153 ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1),
154
155 /// IntShift - The number of low bits that we reserve for other uses, and
156 /// keep zero.
157 IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits,
158
159 /// IntMask - This is the unshifted mask for valid bits of the int type.
160 IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1),
161
162 // ShiftedIntMask - This is the bits for the integer shifted in place.
163 ShiftedIntMask = (uintptr_t)(IntMask << IntShift)
164 };
165
166 static PointerT getPointer(intptr_t Value) {
167 return PtrTraits::getFromVoidPointer(
168 reinterpret_cast<void *>(Value & PointerBitMask));
169 }
170
171 static intptr_t getInt(intptr_t Value) {
172 return (Value >> IntShift) & IntMask;
173 }
174
175 static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) {
176 intptr_t PtrWord =
177 reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr));
178 assert((PtrWord & ~PointerBitMask) == 0 &&(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __PRETTY_FUNCTION__))
179 "Pointer is not sufficiently aligned")(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned"
) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/PointerIntPair.h"
, 179, __PRETTY_FUNCTION__))
;
180 // Preserve all low bits, just update the pointer.
181 return PtrWord | (OrigValue & ~PointerBitMask);
182 }
183
184 static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) {
185 intptr_t IntWord = static_cast<intptr_t>(Int);
186 assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(((IntWord & ~IntMask) == 0 && "Integer too large for field"
) ? static_cast<void> (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/ADT/PointerIntPair.h"
, 186, __PRETTY_FUNCTION__))
;
187
188 // Preserve all bits other than the ones we are updating.
189 return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift;
190 }
191};
192
193// Provide specialization of DenseMapInfo for PointerIntPair.
194template <typename PointerTy, unsigned IntBits, typename IntType>
195struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>> {
196 using Ty = PointerIntPair<PointerTy, IntBits, IntType>;
197
198 static Ty getEmptyKey() {
199 uintptr_t Val = static_cast<uintptr_t>(-1);
200 Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable;
201 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
202 }
203
204 static Ty getTombstoneKey() {
205 uintptr_t Val = static_cast<uintptr_t>(-2);
206 Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable;
207 return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val));
208 }
209
210 static unsigned getHashValue(Ty V) {
211 uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue());
212 return unsigned(IV) ^ unsigned(IV >> 9);
213 }
214
215 static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; }
216};
217
218// Teach SmallPtrSet that PointerIntPair is "basically a pointer".
219template <typename PointerTy, unsigned IntBits, typename IntType,
220 typename PtrTraits>
221struct PointerLikeTypeTraits<
222 PointerIntPair<PointerTy, IntBits, IntType, PtrTraits>> {
223 static inline void *
224 getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) {
225 return P.getOpaqueValue();
226 }
227
228 static inline PointerIntPair<PointerTy, IntBits, IntType>
229 getFromVoidPointer(void *P) {
230 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
231 }
232
233 static inline PointerIntPair<PointerTy, IntBits, IntType>
234 getFromVoidPointer(const void *P) {
235 return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P);
236 }
237
238 static constexpr int NumLowBitsAvailable =
239 PtrTraits::NumLowBitsAvailable - IntBits;
240};
241
242} // end namespace llvm
243
244#endif // LLVM_ADT_POINTERINTPAIR_H