Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210107111113+c9154e8fa377/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210107111113+c9154e8fa377/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210107111113+c9154e8fa377/clang/include -I /build/llvm-toolchain-snapshot-12~++20210107111113+c9154e8fa377/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210107111113+c9154e8fa377/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210107111113+c9154e8fa377/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-12/lib/clang/12.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-12~++20210107111113+c9154e8fa377/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210107111113+c9154e8fa377=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-08-143434-21064-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210107111113+c9154e8fa377/clang/lib/Sema/SemaTemplateDeduction.cpp

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

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

/build/llvm-toolchain-snapshot-12~++20210107111113+c9154e8fa377/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-12~++20210107111113+c9154e8fa377/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-12~++20210107111113+c9154e8fa377/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-12~++20210107111113+c9154e8fa377/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;
21
Assuming 'Value' is not equal to 'RHS.Value'
22
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-12~++20210107111113+c9154e8fa377/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-12~++20210107111113+c9154e8fa377/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-12~++20210107111113+c9154e8fa377/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