Bug Summary

File:clang/lib/Sema/SemaCast.cpp
Warning:line 1360, column 14
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 -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaCast.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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/Sema/SemaCast.cpp

/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/Sema/SemaCast.cpp

1//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
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 semantic analysis for cast expressions, including
10// 1) C-style casts like '(int) x'
11// 2) C++ functional casts like 'int(x)'
12// 3) C++ named casts like 'static_cast<int>(x)'
13//
14//===----------------------------------------------------------------------===//
15
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTStructuralEquivalence.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/RecordLayout.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/SemaInternal.h"
27#include "llvm/ADT/SmallVector.h"
28#include <set>
29using namespace clang;
30
31
32
33enum TryCastResult {
34 TC_NotApplicable, ///< The cast method is not applicable.
35 TC_Success, ///< The cast method is appropriate and successful.
36 TC_Extension, ///< The cast method is appropriate and accepted as a
37 ///< language extension.
38 TC_Failed ///< The cast method is appropriate, but failed. A
39 ///< diagnostic has been emitted.
40};
41
42static bool isValidCast(TryCastResult TCR) {
43 return TCR == TC_Success || TCR == TC_Extension;
44}
45
46enum CastType {
47 CT_Const, ///< const_cast
48 CT_Static, ///< static_cast
49 CT_Reinterpret, ///< reinterpret_cast
50 CT_Dynamic, ///< dynamic_cast
51 CT_CStyle, ///< (Type)expr
52 CT_Functional, ///< Type(expr)
53 CT_Addrspace ///< addrspace_cast
54};
55
56namespace {
57 struct CastOperation {
58 CastOperation(Sema &S, QualType destType, ExprResult src)
59 : Self(S), SrcExpr(src), DestType(destType),
60 ResultType(destType.getNonLValueExprType(S.Context)),
61 ValueKind(Expr::getValueKindForType(destType)),
62 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
63
64 // C++ [expr.type]/8.2.2:
65 // If a pr-value initially has the type cv-T, where T is a
66 // cv-unqualified non-class, non-array type, the type of the
67 // expression is adjusted to T prior to any further analysis.
68 if (!S.Context.getLangOpts().ObjC && !DestType->isRecordType() &&
69 !DestType->isArrayType()) {
70 DestType = DestType.getUnqualifiedType();
71 }
72
73 if (const BuiltinType *placeholder =
74 src.get()->getType()->getAsPlaceholderType()) {
75 PlaceholderKind = placeholder->getKind();
76 } else {
77 PlaceholderKind = (BuiltinType::Kind) 0;
78 }
79 }
80
81 Sema &Self;
82 ExprResult SrcExpr;
83 QualType DestType;
84 QualType ResultType;
85 ExprValueKind ValueKind;
86 CastKind Kind;
87 BuiltinType::Kind PlaceholderKind;
88 CXXCastPath BasePath;
89 bool IsARCUnbridgedCast;
90
91 SourceRange OpRange;
92 SourceRange DestRange;
93
94 // Top-level semantics-checking routines.
95 void CheckConstCast();
96 void CheckReinterpretCast();
97 void CheckStaticCast();
98 void CheckDynamicCast();
99 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
100 void CheckCStyleCast();
101 void CheckBuiltinBitCast();
102 void CheckAddrspaceCast();
103
104 void updatePartOfExplicitCastFlags(CastExpr *CE) {
105 // Walk down from the CE to the OrigSrcExpr, and mark all immediate
106 // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
107 // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
108 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)
109 ICE->setIsPartOfExplicitCast(true);
110 }
111
112 /// Complete an apparently-successful cast operation that yields
113 /// the given expression.
114 ExprResult complete(CastExpr *castExpr) {
115 // If this is an unbridged cast, wrap the result in an implicit
116 // cast that yields the unbridged-cast placeholder type.
117 if (IsARCUnbridgedCast) {
118 castExpr = ImplicitCastExpr::Create(
119 Self.Context, Self.Context.ARCUnbridgedCastTy, CK_Dependent,
120 castExpr, nullptr, castExpr->getValueKind(),
121 Self.CurFPFeatureOverrides());
122 }
123 updatePartOfExplicitCastFlags(castExpr);
124 return castExpr;
125 }
126
127 // Internal convenience methods.
128
129 /// Try to handle the given placeholder expression kind. Return
130 /// true if the source expression has the appropriate placeholder
131 /// kind. A placeholder can only be claimed once.
132 bool claimPlaceholder(BuiltinType::Kind K) {
133 if (PlaceholderKind != K) return false;
134
135 PlaceholderKind = (BuiltinType::Kind) 0;
136 return true;
137 }
138
139 bool isPlaceholder() const {
140 return PlaceholderKind != 0;
141 }
142 bool isPlaceholder(BuiltinType::Kind K) const {
143 return PlaceholderKind == K;
144 }
145
146 // Language specific cast restrictions for address spaces.
147 void checkAddressSpaceCast(QualType SrcType, QualType DestType);
148
149 void checkCastAlign() {
150 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
151 }
152
153 void checkObjCConversion(Sema::CheckedConversionKind CCK) {
154 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())(static_cast <bool> (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers
()) ? void (0) : __assert_fail ("Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()"
, "clang/lib/Sema/SemaCast.cpp", 154, __extension__ __PRETTY_FUNCTION__
))
;
155
156 Expr *src = SrcExpr.get();
157 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
158 Sema::ACR_unbridged)
159 IsARCUnbridgedCast = true;
160 SrcExpr = src;
161 }
162
163 /// Check for and handle non-overload placeholder expressions.
164 void checkNonOverloadPlaceholders() {
165 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
166 return;
167
168 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
169 if (SrcExpr.isInvalid())
170 return;
171 PlaceholderKind = (BuiltinType::Kind) 0;
172 }
173 };
174
175 void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType,
176 SourceLocation OpLoc) {
177 if (const auto *PtrType = dyn_cast<PointerType>(FromType)) {
178 if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
179 if (const auto *DestType = dyn_cast<PointerType>(ToType)) {
180 if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) {
181 S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer);
182 }
183 }
184 }
185 }
186 }
187
188 struct CheckNoDerefRAII {
189 CheckNoDerefRAII(CastOperation &Op) : Op(Op) {}
190 ~CheckNoDerefRAII() {
191 if (!Op.SrcExpr.isInvalid())
192 CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType,
193 Op.OpRange.getBegin());
194 }
195
196 CastOperation &Op;
197 };
198}
199
200static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
201 QualType DestType);
202
203// The Try functions attempt a specific way of casting. If they succeed, they
204// return TC_Success. If their way of casting is not appropriate for the given
205// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
206// to emit if no other way succeeds. If their way of casting is appropriate but
207// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
208// they emit a specialized diagnostic.
209// All diagnostics returned by these functions must expect the same three
210// arguments:
211// %0: Cast Type (a value from the CastType enumeration)
212// %1: Source Type
213// %2: Destination Type
214static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
215 QualType DestType, bool CStyle,
216 CastKind &Kind,
217 CXXCastPath &BasePath,
218 unsigned &msg);
219static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
220 QualType DestType, bool CStyle,
221 SourceRange OpRange,
222 unsigned &msg,
223 CastKind &Kind,
224 CXXCastPath &BasePath);
225static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
226 QualType DestType, bool CStyle,
227 SourceRange OpRange,
228 unsigned &msg,
229 CastKind &Kind,
230 CXXCastPath &BasePath);
231static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
232 CanQualType DestType, bool CStyle,
233 SourceRange OpRange,
234 QualType OrigSrcType,
235 QualType OrigDestType, unsigned &msg,
236 CastKind &Kind,
237 CXXCastPath &BasePath);
238static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
239 QualType SrcType,
240 QualType DestType,bool CStyle,
241 SourceRange OpRange,
242 unsigned &msg,
243 CastKind &Kind,
244 CXXCastPath &BasePath);
245
246static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
247 QualType DestType,
248 Sema::CheckedConversionKind CCK,
249 SourceRange OpRange,
250 unsigned &msg, CastKind &Kind,
251 bool ListInitialization);
252static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
253 QualType DestType,
254 Sema::CheckedConversionKind CCK,
255 SourceRange OpRange,
256 unsigned &msg, CastKind &Kind,
257 CXXCastPath &BasePath,
258 bool ListInitialization);
259static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
260 QualType DestType, bool CStyle,
261 unsigned &msg);
262static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
263 QualType DestType, bool CStyle,
264 SourceRange OpRange, unsigned &msg,
265 CastKind &Kind);
266static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
267 QualType DestType, bool CStyle,
268 unsigned &msg, CastKind &Kind);
269
270/// ActOnCXXNamedCast - Parse
271/// {dynamic,static,reinterpret,const,addrspace}_cast's.
272ExprResult
273Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
274 SourceLocation LAngleBracketLoc, Declarator &D,
275 SourceLocation RAngleBracketLoc,
276 SourceLocation LParenLoc, Expr *E,
277 SourceLocation RParenLoc) {
278
279 assert(!D.isInvalidType())(static_cast <bool> (!D.isInvalidType()) ? void (0) : __assert_fail
("!D.isInvalidType()", "clang/lib/Sema/SemaCast.cpp", 279, __extension__
__PRETTY_FUNCTION__))
;
280
281 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
282 if (D.isInvalidType())
283 return ExprError();
284
285 if (getLangOpts().CPlusPlus) {
286 // Check that there are no default arguments (C++ only).
287 CheckExtraCXXDefaultArguments(D);
288 }
289
290 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
291 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
292 SourceRange(LParenLoc, RParenLoc));
293}
294
295ExprResult
296Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
297 TypeSourceInfo *DestTInfo, Expr *E,
298 SourceRange AngleBrackets, SourceRange Parens) {
299 ExprResult Ex = E;
300 QualType DestType = DestTInfo->getType();
301
302 // If the type is dependent, we won't do the semantic analysis now.
303 bool TypeDependent =
304 DestType->isDependentType() || Ex.get()->isTypeDependent();
305
306 CastOperation Op(*this, DestType, E);
307 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
308 Op.DestRange = AngleBrackets;
309
310 switch (Kind) {
311 default: llvm_unreachable("Unknown C++ cast!")::llvm::llvm_unreachable_internal("Unknown C++ cast!", "clang/lib/Sema/SemaCast.cpp"
, 311)
;
312
313 case tok::kw_addrspace_cast:
314 if (!TypeDependent) {
315 Op.CheckAddrspaceCast();
316 if (Op.SrcExpr.isInvalid())
317 return ExprError();
318 }
319 return Op.complete(CXXAddrspaceCastExpr::Create(
320 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
321 DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets));
322
323 case tok::kw_const_cast:
324 if (!TypeDependent) {
325 Op.CheckConstCast();
326 if (Op.SrcExpr.isInvalid())
327 return ExprError();
328 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
329 }
330 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
331 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
332 OpLoc, Parens.getEnd(),
333 AngleBrackets));
334
335 case tok::kw_dynamic_cast: {
336 // dynamic_cast is not supported in C++ for OpenCL.
337 if (getLangOpts().OpenCLCPlusPlus) {
338 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
339 << "dynamic_cast");
340 }
341
342 if (!TypeDependent) {
343 Op.CheckDynamicCast();
344 if (Op.SrcExpr.isInvalid())
345 return ExprError();
346 }
347 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
348 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
349 &Op.BasePath, DestTInfo,
350 OpLoc, Parens.getEnd(),
351 AngleBrackets));
352 }
353 case tok::kw_reinterpret_cast: {
354 if (!TypeDependent) {
355 Op.CheckReinterpretCast();
356 if (Op.SrcExpr.isInvalid())
357 return ExprError();
358 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
359 }
360 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
361 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
362 nullptr, DestTInfo, OpLoc,
363 Parens.getEnd(),
364 AngleBrackets));
365 }
366 case tok::kw_static_cast: {
367 if (!TypeDependent) {
368 Op.CheckStaticCast();
369 if (Op.SrcExpr.isInvalid())
370 return ExprError();
371 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
372 }
373
374 return Op.complete(CXXStaticCastExpr::Create(
375 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
376 &Op.BasePath, DestTInfo, CurFPFeatureOverrides(), OpLoc,
377 Parens.getEnd(), AngleBrackets));
378 }
379 }
380}
381
382ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D,
383 ExprResult Operand,
384 SourceLocation RParenLoc) {
385 assert(!D.isInvalidType())(static_cast <bool> (!D.isInvalidType()) ? void (0) : __assert_fail
("!D.isInvalidType()", "clang/lib/Sema/SemaCast.cpp", 385, __extension__
__PRETTY_FUNCTION__))
;
386
387 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType());
388 if (D.isInvalidType())
389 return ExprError();
390
391 return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc);
392}
393
394ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc,
395 TypeSourceInfo *TSI, Expr *Operand,
396 SourceLocation RParenLoc) {
397 CastOperation Op(*this, TSI->getType(), Operand);
398 Op.OpRange = SourceRange(KWLoc, RParenLoc);
399 TypeLoc TL = TSI->getTypeLoc();
400 Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
401
402 if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) {
403 Op.CheckBuiltinBitCast();
404 if (Op.SrcExpr.isInvalid())
405 return ExprError();
406 }
407
408 BuiltinBitCastExpr *BCE =
409 new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind,
410 Op.SrcExpr.get(), TSI, KWLoc, RParenLoc);
411 return Op.complete(BCE);
412}
413
414/// Try to diagnose a failed overloaded cast. Returns true if
415/// diagnostics were emitted.
416static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
417 SourceRange range, Expr *src,
418 QualType destType,
419 bool listInitialization) {
420 switch (CT) {
421 // These cast kinds don't consider user-defined conversions.
422 case CT_Const:
423 case CT_Reinterpret:
424 case CT_Dynamic:
425 case CT_Addrspace:
426 return false;
427
428 // These do.
429 case CT_Static:
430 case CT_CStyle:
431 case CT_Functional:
432 break;
433 }
434
435 QualType srcType = src->getType();
436 if (!destType->isRecordType() && !srcType->isRecordType())
437 return false;
438
439 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
440 InitializationKind initKind
441 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
442 range, listInitialization)
443 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
444 listInitialization)
445 : InitializationKind::CreateCast(/*type range?*/ range);
446 InitializationSequence sequence(S, entity, initKind, src);
447
448 assert(sequence.Failed() && "initialization succeeded on second try?")(static_cast <bool> (sequence.Failed() && "initialization succeeded on second try?"
) ? void (0) : __assert_fail ("sequence.Failed() && \"initialization succeeded on second try?\""
, "clang/lib/Sema/SemaCast.cpp", 448, __extension__ __PRETTY_FUNCTION__
))
;
449 switch (sequence.getFailureKind()) {
450 default: return false;
451
452 case InitializationSequence::FK_ConstructorOverloadFailed:
453 case InitializationSequence::FK_UserConversionOverloadFailed:
454 break;
455 }
456
457 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
458
459 unsigned msg = 0;
460 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
461
462 switch (sequence.getFailedOverloadResult()) {
463 case OR_Success: llvm_unreachable("successful failed overload")::llvm::llvm_unreachable_internal("successful failed overload"
, "clang/lib/Sema/SemaCast.cpp", 463)
;
464 case OR_No_Viable_Function:
465 if (candidates.empty())
466 msg = diag::err_ovl_no_conversion_in_cast;
467 else
468 msg = diag::err_ovl_no_viable_conversion_in_cast;
469 howManyCandidates = OCD_AllCandidates;
470 break;
471
472 case OR_Ambiguous:
473 msg = diag::err_ovl_ambiguous_conversion_in_cast;
474 howManyCandidates = OCD_AmbiguousCandidates;
475 break;
476
477 case OR_Deleted:
478 msg = diag::err_ovl_deleted_conversion_in_cast;
479 howManyCandidates = OCD_ViableCandidates;
480 break;
481 }
482
483 candidates.NoteCandidates(
484 PartialDiagnosticAt(range.getBegin(),
485 S.PDiag(msg) << CT << srcType << destType << range
486 << src->getSourceRange()),
487 S, howManyCandidates, src);
488
489 return true;
490}
491
492/// Diagnose a failed cast.
493static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
494 SourceRange opRange, Expr *src, QualType destType,
495 bool listInitialization) {
496 if (msg == diag::err_bad_cxx_cast_generic &&
497 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
498 listInitialization))
499 return;
500
501 S.Diag(opRange.getBegin(), msg) << castType
502 << src->getType() << destType << opRange << src->getSourceRange();
503
504 // Detect if both types are (ptr to) class, and note any incompleteness.
505 int DifferentPtrness = 0;
506 QualType From = destType;
507 if (auto Ptr = From->getAs<PointerType>()) {
508 From = Ptr->getPointeeType();
509 DifferentPtrness++;
510 }
511 QualType To = src->getType();
512 if (auto Ptr = To->getAs<PointerType>()) {
513 To = Ptr->getPointeeType();
514 DifferentPtrness--;
515 }
516 if (!DifferentPtrness) {
517 auto RecFrom = From->getAs<RecordType>();
518 auto RecTo = To->getAs<RecordType>();
519 if (RecFrom && RecTo) {
520 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
521 if (!DeclFrom->isCompleteDefinition())
522 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom;
523 auto DeclTo = RecTo->getAsCXXRecordDecl();
524 if (!DeclTo->isCompleteDefinition())
525 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo;
526 }
527 }
528}
529
530namespace {
531/// The kind of unwrapping we did when determining whether a conversion casts
532/// away constness.
533enum CastAwayConstnessKind {
534 /// The conversion does not cast away constness.
535 CACK_None = 0,
536 /// We unwrapped similar types.
537 CACK_Similar = 1,
538 /// We unwrapped dissimilar types with similar representations (eg, a pointer
539 /// versus an Objective-C object pointer).
540 CACK_SimilarKind = 2,
541 /// We unwrapped representationally-unrelated types, such as a pointer versus
542 /// a pointer-to-member.
543 CACK_Incoherent = 3,
544};
545}
546
547/// Unwrap one level of types for CastsAwayConstness.
548///
549/// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
550/// both types, provided that they're both pointer-like or array-like. Unlike
551/// the Sema function, doesn't care if the unwrapped pieces are related.
552///
553/// This function may remove additional levels as necessary for correctness:
554/// the resulting T1 is unwrapped sufficiently that it is never an array type,
555/// so that its qualifiers can be directly compared to those of T2 (which will
556/// have the combined set of qualifiers from all indermediate levels of T2),
557/// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
558/// with those from T2.
559static CastAwayConstnessKind
560unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
561 enum { None, Ptr, MemPtr, BlockPtr, Array };
562 auto Classify = [](QualType T) {
563 if (T->isAnyPointerType()) return Ptr;
564 if (T->isMemberPointerType()) return MemPtr;
565 if (T->isBlockPointerType()) return BlockPtr;
566 // We somewhat-arbitrarily don't look through VLA types here. This is at
567 // least consistent with the behavior of UnwrapSimilarTypes.
568 if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
569 return None;
570 };
571
572 auto Unwrap = [&](QualType T) {
573 if (auto *AT = Context.getAsArrayType(T))
574 return AT->getElementType();
575 return T->getPointeeType();
576 };
577
578 CastAwayConstnessKind Kind;
579
580 if (T2->isReferenceType()) {
581 // Special case: if the destination type is a reference type, unwrap it as
582 // the first level. (The source will have been an lvalue expression in this
583 // case, so there is no corresponding "reference to" in T1 to remove.) This
584 // simulates removing a "pointer to" from both sides.
585 T2 = T2->getPointeeType();
586 Kind = CastAwayConstnessKind::CACK_Similar;
587 } else if (Context.UnwrapSimilarTypes(T1, T2)) {
588 Kind = CastAwayConstnessKind::CACK_Similar;
589 } else {
590 // Try unwrapping mismatching levels.
591 int T1Class = Classify(T1);
592 if (T1Class == None)
593 return CastAwayConstnessKind::CACK_None;
594
595 int T2Class = Classify(T2);
596 if (T2Class == None)
597 return CastAwayConstnessKind::CACK_None;
598
599 T1 = Unwrap(T1);
600 T2 = Unwrap(T2);
601 Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
602 : CastAwayConstnessKind::CACK_Incoherent;
603 }
604
605 // We've unwrapped at least one level. If the resulting T1 is a (possibly
606 // multidimensional) array type, any qualifier on any matching layer of
607 // T2 is considered to correspond to T1. Decompose down to the element
608 // type of T1 so that we can compare properly.
609 while (true) {
610 Context.UnwrapSimilarArrayTypes(T1, T2);
611
612 if (Classify(T1) != Array)
613 break;
614
615 auto T2Class = Classify(T2);
616 if (T2Class == None)
617 break;
618
619 if (T2Class != Array)
620 Kind = CastAwayConstnessKind::CACK_Incoherent;
621 else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
622 Kind = CastAwayConstnessKind::CACK_SimilarKind;
623
624 T1 = Unwrap(T1);
625 T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
626 }
627
628 return Kind;
629}
630
631/// Check if the pointer conversion from SrcType to DestType casts away
632/// constness as defined in C++ [expr.const.cast]. This is used by the cast
633/// checkers. Both arguments must denote pointer (possibly to member) types.
634///
635/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
636/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
637static CastAwayConstnessKind
638CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
639 bool CheckCVR, bool CheckObjCLifetime,
640 QualType *TheOffendingSrcType = nullptr,
641 QualType *TheOffendingDestType = nullptr,
642 Qualifiers *CastAwayQualifiers = nullptr) {
643 // If the only checking we care about is for Objective-C lifetime qualifiers,
644 // and we're not in ObjC mode, there's nothing to check.
645 if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
646 return CastAwayConstnessKind::CACK_None;
647
648 if (!DestType->isReferenceType()) {
649 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||(static_cast <bool> ((SrcType->isAnyPointerType() ||
SrcType->isMemberPointerType() || SrcType->isBlockPointerType
()) && "Source type is not pointer or pointer to member."
) ? void (0) : __assert_fail ("(SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && \"Source type is not pointer or pointer to member.\""
, "clang/lib/Sema/SemaCast.cpp", 651, __extension__ __PRETTY_FUNCTION__
))
650 SrcType->isBlockPointerType()) &&(static_cast <bool> ((SrcType->isAnyPointerType() ||
SrcType->isMemberPointerType() || SrcType->isBlockPointerType
()) && "Source type is not pointer or pointer to member."
) ? void (0) : __assert_fail ("(SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && \"Source type is not pointer or pointer to member.\""
, "clang/lib/Sema/SemaCast.cpp", 651, __extension__ __PRETTY_FUNCTION__
))
651 "Source type is not pointer or pointer to member.")(static_cast <bool> ((SrcType->isAnyPointerType() ||
SrcType->isMemberPointerType() || SrcType->isBlockPointerType
()) && "Source type is not pointer or pointer to member."
) ? void (0) : __assert_fail ("(SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && \"Source type is not pointer or pointer to member.\""
, "clang/lib/Sema/SemaCast.cpp", 651, __extension__ __PRETTY_FUNCTION__
))
;
652 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||(static_cast <bool> ((DestType->isAnyPointerType() ||
DestType->isMemberPointerType() || DestType->isBlockPointerType
()) && "Destination type is not pointer or pointer to member."
) ? void (0) : __assert_fail ("(DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && \"Destination type is not pointer or pointer to member.\""
, "clang/lib/Sema/SemaCast.cpp", 654, __extension__ __PRETTY_FUNCTION__
))
653 DestType->isBlockPointerType()) &&(static_cast <bool> ((DestType->isAnyPointerType() ||
DestType->isMemberPointerType() || DestType->isBlockPointerType
()) && "Destination type is not pointer or pointer to member."
) ? void (0) : __assert_fail ("(DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && \"Destination type is not pointer or pointer to member.\""
, "clang/lib/Sema/SemaCast.cpp", 654, __extension__ __PRETTY_FUNCTION__
))
654 "Destination type is not pointer or pointer to member.")(static_cast <bool> ((DestType->isAnyPointerType() ||
DestType->isMemberPointerType() || DestType->isBlockPointerType
()) && "Destination type is not pointer or pointer to member."
) ? void (0) : __assert_fail ("(DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && \"Destination type is not pointer or pointer to member.\""
, "clang/lib/Sema/SemaCast.cpp", 654, __extension__ __PRETTY_FUNCTION__
))
;
655 }
656
657 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
658 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
659
660 // Find the qualifiers. We only care about cvr-qualifiers for the
661 // purpose of this check, because other qualifiers (address spaces,
662 // Objective-C GC, etc.) are part of the type's identity.
663 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
664 QualType PrevUnwrappedDestType = UnwrappedDestType;
665 auto WorstKind = CastAwayConstnessKind::CACK_Similar;
666 bool AllConstSoFar = true;
667 while (auto Kind = unwrapCastAwayConstnessLevel(
668 Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
669 // Track the worst kind of unwrap we needed to do before we found a
670 // problem.
671 if (Kind > WorstKind)
672 WorstKind = Kind;
673
674 // Determine the relevant qualifiers at this level.
675 Qualifiers SrcQuals, DestQuals;
676 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
677 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
678
679 // We do not meaningfully track object const-ness of Objective-C object
680 // types. Remove const from the source type if either the source or
681 // the destination is an Objective-C object type.
682 if (UnwrappedSrcType->isObjCObjectType() ||
683 UnwrappedDestType->isObjCObjectType())
684 SrcQuals.removeConst();
685
686 if (CheckCVR) {
687 Qualifiers SrcCvrQuals =
688 Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
689 Qualifiers DestCvrQuals =
690 Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
691
692 if (SrcCvrQuals != DestCvrQuals) {
693 if (CastAwayQualifiers)
694 *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
695
696 // If we removed a cvr-qualifier, this is casting away 'constness'.
697 if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
698 if (TheOffendingSrcType)
699 *TheOffendingSrcType = PrevUnwrappedSrcType;
700 if (TheOffendingDestType)
701 *TheOffendingDestType = PrevUnwrappedDestType;
702 return WorstKind;
703 }
704
705 // If any prior level was not 'const', this is also casting away
706 // 'constness'. We noted the outermost type missing a 'const' already.
707 if (!AllConstSoFar)
708 return WorstKind;
709 }
710 }
711
712 if (CheckObjCLifetime &&
713 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
714 return WorstKind;
715
716 // If we found our first non-const-qualified type, this may be the place
717 // where things start to go wrong.
718 if (AllConstSoFar && !DestQuals.hasConst()) {
719 AllConstSoFar = false;
720 if (TheOffendingSrcType)
721 *TheOffendingSrcType = PrevUnwrappedSrcType;
722 if (TheOffendingDestType)
723 *TheOffendingDestType = PrevUnwrappedDestType;
724 }
725
726 PrevUnwrappedSrcType = UnwrappedSrcType;
727 PrevUnwrappedDestType = UnwrappedDestType;
728 }
729
730 return CastAwayConstnessKind::CACK_None;
731}
732
733static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
734 unsigned &DiagID) {
735 switch (CACK) {
736 case CastAwayConstnessKind::CACK_None:
737 llvm_unreachable("did not cast away constness")::llvm::llvm_unreachable_internal("did not cast away constness"
, "clang/lib/Sema/SemaCast.cpp", 737)
;
738
739 case CastAwayConstnessKind::CACK_Similar:
740 // FIXME: Accept these as an extension too?
741 case CastAwayConstnessKind::CACK_SimilarKind:
742 DiagID = diag::err_bad_cxx_cast_qualifiers_away;
743 return TC_Failed;
744
745 case CastAwayConstnessKind::CACK_Incoherent:
746 DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
747 return TC_Extension;
748 }
749
750 llvm_unreachable("unexpected cast away constness kind")::llvm::llvm_unreachable_internal("unexpected cast away constness kind"
, "clang/lib/Sema/SemaCast.cpp", 750)
;
751}
752
753/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
754/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
755/// checked downcasts in class hierarchies.
756void CastOperation::CheckDynamicCast() {
757 CheckNoDerefRAII NoderefCheck(*this);
758
759 if (ValueKind == VK_PRValue)
760 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
761 else if (isPlaceholder())
762 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
763 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
764 return;
765
766 QualType OrigSrcType = SrcExpr.get()->getType();
767 QualType DestType = Self.Context.getCanonicalType(this->DestType);
768
769 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
770 // or "pointer to cv void".
771
772 QualType DestPointee;
773 const PointerType *DestPointer = DestType->getAs<PointerType>();
774 const ReferenceType *DestReference = nullptr;
775 if (DestPointer) {
776 DestPointee = DestPointer->getPointeeType();
777 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
778 DestPointee = DestReference->getPointeeType();
779 } else {
780 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
781 << this->DestType << DestRange;
782 SrcExpr = ExprError();
783 return;
784 }
785
786 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
787 if (DestPointee->isVoidType()) {
788 assert(DestPointer && "Reference to void is not possible")(static_cast <bool> (DestPointer && "Reference to void is not possible"
) ? void (0) : __assert_fail ("DestPointer && \"Reference to void is not possible\""
, "clang/lib/Sema/SemaCast.cpp", 788, __extension__ __PRETTY_FUNCTION__
))
;
789 } else if (DestRecord) {
790 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
791 diag::err_bad_cast_incomplete,
792 DestRange)) {
793 SrcExpr = ExprError();
794 return;
795 }
796 } else {
797 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
798 << DestPointee.getUnqualifiedType() << DestRange;
799 SrcExpr = ExprError();
800 return;
801 }
802
803 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
804 // complete class type, [...]. If T is an lvalue reference type, v shall be
805 // an lvalue of a complete class type, [...]. If T is an rvalue reference
806 // type, v shall be an expression having a complete class type, [...]
807 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
808 QualType SrcPointee;
809 if (DestPointer) {
810 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
811 SrcPointee = SrcPointer->getPointeeType();
812 } else {
813 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
814 << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange();
815 SrcExpr = ExprError();
816 return;
817 }
818 } else if (DestReference->isLValueReferenceType()) {
819 if (!SrcExpr.get()->isLValue()) {
820 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
821 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
822 }
823 SrcPointee = SrcType;
824 } else {
825 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
826 // to materialize the prvalue before we bind the reference to it.
827 if (SrcExpr.get()->isPRValue())
828 SrcExpr = Self.CreateMaterializeTemporaryExpr(
829 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
830 SrcPointee = SrcType;
831 }
832
833 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
834 if (SrcRecord) {
835 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
836 diag::err_bad_cast_incomplete,
837 SrcExpr.get())) {
838 SrcExpr = ExprError();
839 return;
840 }
841 } else {
842 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
843 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
844 SrcExpr = ExprError();
845 return;
846 }
847
848 assert((DestPointer || DestReference) &&(static_cast <bool> ((DestPointer || DestReference) &&
"Bad destination non-ptr/ref slipped through.") ? void (0) :
__assert_fail ("(DestPointer || DestReference) && \"Bad destination non-ptr/ref slipped through.\""
, "clang/lib/Sema/SemaCast.cpp", 849, __extension__ __PRETTY_FUNCTION__
))
849 "Bad destination non-ptr/ref slipped through.")(static_cast <bool> ((DestPointer || DestReference) &&
"Bad destination non-ptr/ref slipped through.") ? void (0) :
__assert_fail ("(DestPointer || DestReference) && \"Bad destination non-ptr/ref slipped through.\""
, "clang/lib/Sema/SemaCast.cpp", 849, __extension__ __PRETTY_FUNCTION__
))
;
850 assert((DestRecord || DestPointee->isVoidType()) &&(static_cast <bool> ((DestRecord || DestPointee->isVoidType
()) && "Bad destination pointee slipped through.") ? void
(0) : __assert_fail ("(DestRecord || DestPointee->isVoidType()) && \"Bad destination pointee slipped through.\""
, "clang/lib/Sema/SemaCast.cpp", 851, __extension__ __PRETTY_FUNCTION__
))
851 "Bad destination pointee slipped through.")(static_cast <bool> ((DestRecord || DestPointee->isVoidType
()) && "Bad destination pointee slipped through.") ? void
(0) : __assert_fail ("(DestRecord || DestPointee->isVoidType()) && \"Bad destination pointee slipped through.\""
, "clang/lib/Sema/SemaCast.cpp", 851, __extension__ __PRETTY_FUNCTION__
))
;
852 assert(SrcRecord && "Bad source pointee slipped through.")(static_cast <bool> (SrcRecord && "Bad source pointee slipped through."
) ? void (0) : __assert_fail ("SrcRecord && \"Bad source pointee slipped through.\""
, "clang/lib/Sema/SemaCast.cpp", 852, __extension__ __PRETTY_FUNCTION__
))
;
853
854 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
855 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
856 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
857 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
858 SrcExpr = ExprError();
859 return;
860 }
861
862 // C++ 5.2.7p3: If the type of v is the same as the required result type,
863 // [except for cv].
864 if (DestRecord == SrcRecord) {
865 Kind = CK_NoOp;
866 return;
867 }
868
869 // C++ 5.2.7p5
870 // Upcasts are resolved statically.
871 if (DestRecord &&
872 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
873 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
874 OpRange.getBegin(), OpRange,
875 &BasePath)) {
876 SrcExpr = ExprError();
877 return;
878 }
879
880 Kind = CK_DerivedToBase;
881 return;
882 }
883
884 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
885 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
886 assert(SrcDecl && "Definition missing")(static_cast <bool> (SrcDecl && "Definition missing"
) ? void (0) : __assert_fail ("SrcDecl && \"Definition missing\""
, "clang/lib/Sema/SemaCast.cpp", 886, __extension__ __PRETTY_FUNCTION__
))
;
887 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
888 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
889 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
890 SrcExpr = ExprError();
891 }
892
893 // dynamic_cast is not available with -fno-rtti.
894 // As an exception, dynamic_cast to void* is available because it doesn't
895 // use RTTI.
896 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
897 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
898 SrcExpr = ExprError();
899 return;
900 }
901
902 // Warns when dynamic_cast is used with RTTI data disabled.
903 if (!Self.getLangOpts().RTTIData) {
904 bool MicrosoftABI =
905 Self.getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
906 bool isClangCL = Self.getDiagnostics().getDiagnosticOptions().getFormat() ==
907 DiagnosticOptions::MSVC;
908 if (MicrosoftABI || !DestPointee->isVoidType())
909 Self.Diag(OpRange.getBegin(),
910 diag::warn_no_dynamic_cast_with_rtti_disabled)
911 << isClangCL;
912 }
913
914 // Done. Everything else is run-time checks.
915 Kind = CK_Dynamic;
916}
917
918/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
919/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
920/// like this:
921/// const char *str = "literal";
922/// legacy_function(const_cast\<char*\>(str));
923void CastOperation::CheckConstCast() {
924 CheckNoDerefRAII NoderefCheck(*this);
925
926 if (ValueKind == VK_PRValue)
927 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
928 else if (isPlaceholder())
929 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
930 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
931 return;
932
933 unsigned msg = diag::err_bad_cxx_cast_generic;
934 auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
935 if (TCR != TC_Success && msg != 0) {
936 Self.Diag(OpRange.getBegin(), msg) << CT_Const
937 << SrcExpr.get()->getType() << DestType << OpRange;
938 }
939 if (!isValidCast(TCR))
940 SrcExpr = ExprError();
941}
942
943void CastOperation::CheckAddrspaceCast() {
944 unsigned msg = diag::err_bad_cxx_cast_generic;
945 auto TCR =
946 TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind);
947 if (TCR != TC_Success && msg != 0) {
948 Self.Diag(OpRange.getBegin(), msg)
949 << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange;
950 }
951 if (!isValidCast(TCR))
952 SrcExpr = ExprError();
953}
954
955/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
956/// or downcast between respective pointers or references.
957static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
958 QualType DestType,
959 SourceRange OpRange) {
960 QualType SrcType = SrcExpr->getType();
961 // When casting from pointer or reference, get pointee type; use original
962 // type otherwise.
963 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
964 const CXXRecordDecl *SrcRD =
965 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
966
967 // Examining subobjects for records is only possible if the complete and
968 // valid definition is available. Also, template instantiation is not
969 // allowed here.
970 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
971 return;
972
973 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
974
975 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
976 return;
977
978 enum {
979 ReinterpretUpcast,
980 ReinterpretDowncast
981 } ReinterpretKind;
982
983 CXXBasePaths BasePaths;
984
985 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
986 ReinterpretKind = ReinterpretUpcast;
987 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
988 ReinterpretKind = ReinterpretDowncast;
989 else
990 return;
991
992 bool VirtualBase = true;
993 bool NonZeroOffset = false;
994 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
995 E = BasePaths.end();
996 I != E; ++I) {
997 const CXXBasePath &Path = *I;
998 CharUnits Offset = CharUnits::Zero();
999 bool IsVirtual = false;
1000 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
1001 IElem != EElem; ++IElem) {
1002 IsVirtual = IElem->Base->isVirtual();
1003 if (IsVirtual)
1004 break;
1005 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
1006 assert(BaseRD && "Base type should be a valid unqualified class type")(static_cast <bool> (BaseRD && "Base type should be a valid unqualified class type"
) ? void (0) : __assert_fail ("BaseRD && \"Base type should be a valid unqualified class type\""
, "clang/lib/Sema/SemaCast.cpp", 1006, __extension__ __PRETTY_FUNCTION__
))
;
1007 // Don't check if any base has invalid declaration or has no definition
1008 // since it has no layout info.
1009 const CXXRecordDecl *Class = IElem->Class,
1010 *ClassDefinition = Class->getDefinition();
1011 if (Class->isInvalidDecl() || !ClassDefinition ||
1012 !ClassDefinition->isCompleteDefinition())
1013 return;
1014
1015 const ASTRecordLayout &DerivedLayout =
1016 Self.Context.getASTRecordLayout(Class);
1017 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
1018 }
1019 if (!IsVirtual) {
1020 // Don't warn if any path is a non-virtually derived base at offset zero.
1021 if (Offset.isZero())
1022 return;
1023 // Offset makes sense only for non-virtual bases.
1024 else
1025 NonZeroOffset = true;
1026 }
1027 VirtualBase = VirtualBase && IsVirtual;
1028 }
1029
1030 (void) NonZeroOffset; // Silence set but not used warning.
1031 assert((VirtualBase || NonZeroOffset) &&(static_cast <bool> ((VirtualBase || NonZeroOffset) &&
"Should have returned if has non-virtual base with zero offset"
) ? void (0) : __assert_fail ("(VirtualBase || NonZeroOffset) && \"Should have returned if has non-virtual base with zero offset\""
, "clang/lib/Sema/SemaCast.cpp", 1032, __extension__ __PRETTY_FUNCTION__
))
1032 "Should have returned if has non-virtual base with zero offset")(static_cast <bool> ((VirtualBase || NonZeroOffset) &&
"Should have returned if has non-virtual base with zero offset"
) ? void (0) : __assert_fail ("(VirtualBase || NonZeroOffset) && \"Should have returned if has non-virtual base with zero offset\""
, "clang/lib/Sema/SemaCast.cpp", 1032, __extension__ __PRETTY_FUNCTION__
))
;
1033
1034 QualType BaseType =
1035 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
1036 QualType DerivedType =
1037 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
1038
1039 SourceLocation BeginLoc = OpRange.getBegin();
1040 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
1041 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
1042 << OpRange;
1043 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
1044 << int(ReinterpretKind)
1045 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
1046}
1047
1048static bool argTypeIsABIEquivalent(QualType SrcType, QualType DestType,
1049 ASTContext &Context) {
1050 if (SrcType->isPointerType() && DestType->isPointerType())
1051 return true;
1052
1053 // Allow integral type mismatch if their size are equal.
1054 if (SrcType->isIntegralType(Context) && DestType->isIntegralType(Context))
1055 if (Context.getTypeInfoInChars(SrcType).Width ==
1056 Context.getTypeInfoInChars(DestType).Width)
1057 return true;
1058
1059 return Context.hasSameUnqualifiedType(SrcType, DestType);
1060}
1061
1062static bool checkCastFunctionType(Sema &Self, const ExprResult &SrcExpr,
1063 QualType DestType) {
1064 if (Self.Diags.isIgnored(diag::warn_cast_function_type,
1065 SrcExpr.get()->getExprLoc()))
1066 return true;
1067
1068 QualType SrcType = SrcExpr.get()->getType();
1069 const FunctionType *SrcFTy = nullptr;
1070 const FunctionType *DstFTy = nullptr;
1071 if (((SrcType->isBlockPointerType() || SrcType->isFunctionPointerType()) &&
1072 DestType->isFunctionPointerType()) ||
1073 (SrcType->isMemberFunctionPointerType() &&
1074 DestType->isMemberFunctionPointerType())) {
1075 SrcFTy = SrcType->getPointeeType()->castAs<FunctionType>();
1076 DstFTy = DestType->getPointeeType()->castAs<FunctionType>();
1077 } else if (SrcType->isFunctionType() && DestType->isFunctionReferenceType()) {
1078 SrcFTy = SrcType->castAs<FunctionType>();
1079 DstFTy = DestType.getNonReferenceType()->castAs<FunctionType>();
1080 } else {
1081 return true;
1082 }
1083 assert(SrcFTy && DstFTy)(static_cast <bool> (SrcFTy && DstFTy) ? void (
0) : __assert_fail ("SrcFTy && DstFTy", "clang/lib/Sema/SemaCast.cpp"
, 1083, __extension__ __PRETTY_FUNCTION__))
;
1084
1085 auto IsVoidVoid = [](const FunctionType *T) {
1086 if (!T->getReturnType()->isVoidType())
1087 return false;
1088 if (const auto *PT = T->getAs<FunctionProtoType>())
1089 return !PT->isVariadic() && PT->getNumParams() == 0;
1090 return false;
1091 };
1092
1093 // Skip if either function type is void(*)(void)
1094 if (IsVoidVoid(SrcFTy) || IsVoidVoid(DstFTy))
1095 return true;
1096
1097 // Check return type.
1098 if (!argTypeIsABIEquivalent(SrcFTy->getReturnType(), DstFTy->getReturnType(),
1099 Self.Context))
1100 return false;
1101
1102 // Check if either has unspecified number of parameters
1103 if (SrcFTy->isFunctionNoProtoType() || DstFTy->isFunctionNoProtoType())
1104 return true;
1105
1106 // Check parameter types.
1107
1108 const auto *SrcFPTy = cast<FunctionProtoType>(SrcFTy);
1109 const auto *DstFPTy = cast<FunctionProtoType>(DstFTy);
1110
1111 // In a cast involving function types with a variable argument list only the
1112 // types of initial arguments that are provided are considered.
1113 unsigned NumParams = SrcFPTy->getNumParams();
1114 unsigned DstNumParams = DstFPTy->getNumParams();
1115 if (NumParams > DstNumParams) {
1116 if (!DstFPTy->isVariadic())
1117 return false;
1118 NumParams = DstNumParams;
1119 } else if (NumParams < DstNumParams) {
1120 if (!SrcFPTy->isVariadic())
1121 return false;
1122 }
1123
1124 for (unsigned i = 0; i < NumParams; ++i)
1125 if (!argTypeIsABIEquivalent(SrcFPTy->getParamType(i),
1126 DstFPTy->getParamType(i), Self.Context))
1127 return false;
1128
1129 return true;
1130}
1131
1132/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
1133/// valid.
1134/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
1135/// like this:
1136/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
1137void CastOperation::CheckReinterpretCast() {
1138 if (ValueKind == VK_PRValue && !isPlaceholder(BuiltinType::Overload))
1139 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
1140 else
1141 checkNonOverloadPlaceholders();
1142 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1143 return;
1144
1145 unsigned msg = diag::err_bad_cxx_cast_generic;
1146 TryCastResult tcr =
1147 TryReinterpretCast(Self, SrcExpr, DestType,
1148 /*CStyle*/false, OpRange, msg, Kind);
1149 if (tcr != TC_Success && msg != 0) {
1150 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1151 return;
1152 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1153 //FIXME: &f<int>; is overloaded and resolvable
1154 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
1155 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
1156 << DestType << OpRange;
1157 Self.NoteAllOverloadCandidates(SrcExpr.get());
1158
1159 } else {
1160 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
1161 DestType, /*listInitialization=*/false);
1162 }
1163 }
1164
1165 if (isValidCast(tcr)) {
1166 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1167 checkObjCConversion(Sema::CCK_OtherCast);
1168 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
1169
1170 if (!checkCastFunctionType(Self, SrcExpr, DestType))
1171 Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
1172 << SrcExpr.get()->getType() << DestType << OpRange;
1173 } else {
1174 SrcExpr = ExprError();
1175 }
1176}
1177
1178
1179/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
1180/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
1181/// implicit conversions explicit and getting rid of data loss warnings.
1182void CastOperation::CheckStaticCast() {
1183 CheckNoDerefRAII NoderefCheck(*this);
1184
1185 if (isPlaceholder()) {
1
Taking false branch
1186 checkNonOverloadPlaceholders();
1187 if (SrcExpr.isInvalid())
1188 return;
1189 }
1190
1191 // This test is outside everything else because it's the only case where
1192 // a non-lvalue-reference target type does not lead to decay.
1193 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1194 if (DestType->isVoidType()) {
1195 Kind = CK_ToVoid;
1196
1197 if (claimPlaceholder(BuiltinType::Overload)) {
1198 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
1199 false, // Decay Function to ptr
1200 true, // Complain
1201 OpRange, DestType, diag::err_bad_static_cast_overload);
1202 if (SrcExpr.isInvalid())
1203 return;
1204 }
1205
1206 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
1207 return;
1208 }
1209
1210 if (ValueKind == VK_PRValue && !DestType->isRecordType() &&
2
Assuming field 'ValueKind' is not equal to VK_PRValue
1211 !isPlaceholder(BuiltinType::Overload)) {
1212 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
1213 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1214 return;
1215 }
1216
1217 unsigned msg = diag::err_bad_cxx_cast_generic;
1218 TryCastResult tcr
1219 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
3
Calling 'TryStaticCast'
1220 Kind, BasePath, /*ListInitialization=*/false);
1221 if (tcr != TC_Success && msg != 0) {
1222 if (SrcExpr.isInvalid())
1223 return;
1224 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1225 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
1226 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
1227 << oe->getName() << DestType << OpRange
1228 << oe->getQualifierLoc().getSourceRange();
1229 Self.NoteAllOverloadCandidates(SrcExpr.get());
1230 } else {
1231 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
1232 /*listInitialization=*/false);
1233 }
1234 }
1235
1236 if (isValidCast(tcr)) {
1237 if (Kind == CK_BitCast)
1238 checkCastAlign();
1239 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1240 checkObjCConversion(Sema::CCK_OtherCast);
1241 } else {
1242 SrcExpr = ExprError();
1243 }
1244}
1245
1246static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1247 auto *SrcPtrType = SrcType->getAs<PointerType>();
1248 if (!SrcPtrType)
1249 return false;
1250 auto *DestPtrType = DestType->getAs<PointerType>();
1251 if (!DestPtrType)
1252 return false;
1253 return SrcPtrType->getPointeeType().getAddressSpace() !=
1254 DestPtrType->getPointeeType().getAddressSpace();
1255}
1256
1257/// TryStaticCast - Check if a static cast can be performed, and do so if
1258/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1259/// and casting away constness.
1260static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
1261 QualType DestType,
1262 Sema::CheckedConversionKind CCK,
1263 SourceRange OpRange, unsigned &msg,
1264 CastKind &Kind, CXXCastPath &BasePath,
1265 bool ListInitialization) {
1266 // Determine whether we have the semantics of a C-style cast.
1267 bool CStyle
1268 = (CCK
3.1
'CCK' is not equal to CCK_CStyleCast
3.1
'CCK' is not equal to CCK_CStyleCast
3.1
'CCK' is not equal to CCK_CStyleCast
== Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1269
1270 // The order the tests is not entirely arbitrary. There is one conversion
1271 // that can be handled in two different ways. Given:
1272 // struct A {};
1273 // struct B : public A {
1274 // B(); B(const A&);
1275 // };
1276 // const A &a = B();
1277 // the cast static_cast<const B&>(a) could be seen as either a static
1278 // reference downcast, or an explicit invocation of the user-defined
1279 // conversion using B's conversion constructor.
1280 // DR 427 specifies that the downcast is to be applied here.
1281
1282 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1283 // Done outside this function.
1284
1285 TryCastResult tcr;
1286
1287 // C++ 5.2.9p5, reference downcast.
1288 // See the function for details.
1289 // DR 427 specifies that this is to be applied before paragraph 2.
1290 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1291 OpRange, msg, Kind, BasePath);
1292 if (tcr
3.2
'tcr' is equal to TC_NotApplicable
3.2
'tcr' is equal to TC_NotApplicable
3.2
'tcr' is equal to TC_NotApplicable
!= TC_NotApplicable)
4
Taking false branch
1293 return tcr;
1294
1295 // C++11 [expr.static.cast]p3:
1296 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1297 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1298 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
1299 BasePath, msg);
1300 if (tcr
4.1
'tcr' is equal to TC_NotApplicable
4.1
'tcr' is equal to TC_NotApplicable
4.1
'tcr' is equal to TC_NotApplicable
!= TC_NotApplicable)
5
Taking false branch
1301 return tcr;
1302
1303 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1304 // [...] if the declaration "T t(e);" is well-formed, [...].
1305 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
1306 Kind, ListInitialization);
1307 if (SrcExpr.isInvalid())
6
Assuming the condition is false
7
Taking false branch
1308 return TC_Failed;
1309 if (tcr
7.1
'tcr' is equal to TC_NotApplicable
7.1
'tcr' is equal to TC_NotApplicable
7.1
'tcr' is equal to TC_NotApplicable
!= TC_NotApplicable)
8
Taking false branch
1310 return tcr;
1311
1312 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1313 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1314 // conversions, subject to further restrictions.
1315 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1316 // of qualification conversions impossible. (In C++20, adding an array bound
1317 // would be the reverse of a qualification conversion, but adding permission
1318 // to add an array bound in a static_cast is a wording oversight.)
1319 // In the CStyle case, the earlier attempt to const_cast should have taken
1320 // care of reverse qualification conversions.
1321
1322 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
1323
1324 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1325 // converted to an integral type. [...] A value of a scoped enumeration type
1326 // can also be explicitly converted to a floating-point type [...].
1327 if (const EnumType *Enum
9.1
'Enum' is null
9.1
'Enum' is null
9.1
'Enum' is null
= SrcType->getAs<EnumType>()) {
9
Assuming the object is not a 'EnumType'
10
Taking false branch
1328 if (Enum->getDecl()->isScoped()) {
1329 if (DestType->isBooleanType()) {
1330 Kind = CK_IntegralToBoolean;
1331 return TC_Success;
1332 } else if (DestType->isIntegralType(Self.Context)) {
1333 Kind = CK_IntegralCast;
1334 return TC_Success;
1335 } else if (DestType->isRealFloatingType()) {
1336 Kind = CK_IntegralToFloating;
1337 return TC_Success;
1338 }
1339 }
1340 }
1341
1342 // Reverse integral promotion/conversion. All such conversions are themselves
1343 // again integral promotions or conversions and are thus already handled by
1344 // p2 (TryDirectInitialization above).
1345 // (Note: any data loss warnings should be suppressed.)
1346 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1347 // enum->enum). See also C++ 5.2.9p7.
1348 // The same goes for reverse floating point promotion/conversion and
1349 // floating-integral conversions. Again, only floating->enum is relevant.
1350 if (DestType->isEnumeralType()) {
11
Calling 'Type::isEnumeralType'
14
Returning from 'Type::isEnumeralType'
15
Taking true branch
1351 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
16
Assuming the condition is false
17
Taking false branch
1352 diag::err_bad_cast_incomplete)) {
1353 SrcExpr = ExprError();
1354 return TC_Failed;
1355 }
1356 if (SrcType->isIntegralOrEnumerationType()) {
18
Calling 'Type::isIntegralOrEnumerationType'
36
Returning from 'Type::isIntegralOrEnumerationType'
37
Taking true branch
1357 // [expr.static.cast]p10 If the enumeration type has a fixed underlying
1358 // type, the value is first converted to that type by integral conversion
1359 const EnumType *Enum = DestType->getAs<EnumType>();
38
Assuming the object is not a 'EnumType'
39
'Enum' initialized to a null pointer value
1360 Kind = Enum->getDecl()->isFixed() &&
40
Called C++ object pointer is null
1361 Enum->getDecl()->getIntegerType()->isBooleanType()
1362 ? CK_IntegralToBoolean
1363 : CK_IntegralCast;
1364 return TC_Success;
1365 } else if (SrcType->isRealFloatingType()) {
1366 Kind = CK_FloatingToIntegral;
1367 return TC_Success;
1368 }
1369 }
1370
1371 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1372 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1373 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1374 Kind, BasePath);
1375 if (tcr != TC_NotApplicable)
1376 return tcr;
1377
1378 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1379 // conversion. C++ 5.2.9p9 has additional information.
1380 // DR54's access restrictions apply here also.
1381 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1382 OpRange, msg, Kind, BasePath);
1383 if (tcr != TC_NotApplicable)
1384 return tcr;
1385
1386 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1387 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1388 // just the usual constness stuff.
1389 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1390 QualType SrcPointee = SrcPointer->getPointeeType();
1391 if (SrcPointee->isVoidType()) {
1392 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1393 QualType DestPointee = DestPointer->getPointeeType();
1394 if (DestPointee->isIncompleteOrObjectType()) {
1395 // This is definitely the intended conversion, but it might fail due
1396 // to a qualifier violation. Note that we permit Objective-C lifetime
1397 // and GC qualifier mismatches here.
1398 if (!CStyle) {
1399 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1400 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1401 DestPointeeQuals.removeObjCGCAttr();
1402 DestPointeeQuals.removeObjCLifetime();
1403 SrcPointeeQuals.removeObjCGCAttr();
1404 SrcPointeeQuals.removeObjCLifetime();
1405 if (DestPointeeQuals != SrcPointeeQuals &&
1406 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1407 msg = diag::err_bad_cxx_cast_qualifiers_away;
1408 return TC_Failed;
1409 }
1410 }
1411 Kind = IsAddressSpaceConversion(SrcType, DestType)
1412 ? CK_AddressSpaceConversion
1413 : CK_BitCast;
1414 return TC_Success;
1415 }
1416
1417 // Microsoft permits static_cast from 'pointer-to-void' to
1418 // 'pointer-to-function'.
1419 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1420 DestPointee->isFunctionType()) {
1421 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1422 Kind = CK_BitCast;
1423 return TC_Success;
1424 }
1425 }
1426 else if (DestType->isObjCObjectPointerType()) {
1427 // allow both c-style cast and static_cast of objective-c pointers as
1428 // they are pervasive.
1429 Kind = CK_CPointerToObjCPointerCast;
1430 return TC_Success;
1431 }
1432 else if (CStyle && DestType->isBlockPointerType()) {
1433 // allow c-style cast of void * to block pointers.
1434 Kind = CK_AnyPointerToBlockPointerCast;
1435 return TC_Success;
1436 }
1437 }
1438 }
1439 // Allow arbitrary objective-c pointer conversion with static casts.
1440 if (SrcType->isObjCObjectPointerType() &&
1441 DestType->isObjCObjectPointerType()) {
1442 Kind = CK_BitCast;
1443 return TC_Success;
1444 }
1445 // Allow ns-pointer to cf-pointer conversion in either direction
1446 // with static casts.
1447 if (!CStyle &&
1448 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1449 return TC_Success;
1450
1451 // See if it looks like the user is trying to convert between
1452 // related record types, and select a better diagnostic if so.
1453 if (auto SrcPointer = SrcType->getAs<PointerType>())
1454 if (auto DestPointer = DestType->getAs<PointerType>())
1455 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1456 DestPointer->getPointeeType()->getAs<RecordType>())
1457 msg = diag::err_bad_cxx_cast_unrelated_class;
1458
1459 if (SrcType->isMatrixType() && DestType->isMatrixType()) {
1460 if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) {
1461 SrcExpr = ExprError();
1462 return TC_Failed;
1463 }
1464 return TC_Success;
1465 }
1466
1467 // We tried everything. Everything! Nothing works! :-(
1468 return TC_NotApplicable;
1469}
1470
1471/// Tests whether a conversion according to N2844 is valid.
1472TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1473 QualType DestType, bool CStyle,
1474 CastKind &Kind, CXXCastPath &BasePath,
1475 unsigned &msg) {
1476 // C++11 [expr.static.cast]p3:
1477 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1478 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1479 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1480 if (!R)
1481 return TC_NotApplicable;
1482
1483 if (!SrcExpr->isGLValue())
1484 return TC_NotApplicable;
1485
1486 // Because we try the reference downcast before this function, from now on
1487 // this is the only cast possibility, so we issue an error if we fail now.
1488 // FIXME: Should allow casting away constness if CStyle.
1489 QualType FromType = SrcExpr->getType();
1490 QualType ToType = R->getPointeeType();
1491 if (CStyle) {
1492 FromType = FromType.getUnqualifiedType();
1493 ToType = ToType.getUnqualifiedType();
1494 }
1495
1496 Sema::ReferenceConversions RefConv;
1497 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1498 SrcExpr->getBeginLoc(), ToType, FromType, &RefConv);
1499 if (RefResult != Sema::Ref_Compatible) {
1500 if (CStyle || RefResult == Sema::Ref_Incompatible)
1501 return TC_NotApplicable;
1502 // Diagnose types which are reference-related but not compatible here since
1503 // we can provide better diagnostics. In these cases forwarding to
1504 // [expr.static.cast]p4 should never result in a well-formed cast.
1505 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1506 : diag::err_bad_rvalue_to_rvalue_cast;
1507 return TC_Failed;
1508 }
1509
1510 if (RefConv & Sema::ReferenceConversions::DerivedToBase) {
1511 Kind = CK_DerivedToBase;
1512 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1513 /*DetectVirtual=*/true);
1514 if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),
1515 R->getPointeeType(), Paths))
1516 return TC_NotApplicable;
1517
1518 Self.BuildBasePathArray(Paths, BasePath);
1519 } else
1520 Kind = CK_NoOp;
1521
1522 return TC_Success;
1523}
1524
1525/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1526TryCastResult
1527TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1528 bool CStyle, SourceRange OpRange,
1529 unsigned &msg, CastKind &Kind,
1530 CXXCastPath &BasePath) {
1531 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1532 // cast to type "reference to cv2 D", where D is a class derived from B,
1533 // if a valid standard conversion from "pointer to D" to "pointer to B"
1534 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1535 // In addition, DR54 clarifies that the base must be accessible in the
1536 // current context. Although the wording of DR54 only applies to the pointer
1537 // variant of this rule, the intent is clearly for it to apply to the this
1538 // conversion as well.
1539
1540 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1541 if (!DestReference) {
1542 return TC_NotApplicable;
1543 }
1544 bool RValueRef = DestReference->isRValueReferenceType();
1545 if (!RValueRef && !SrcExpr->isLValue()) {
1546 // We know the left side is an lvalue reference, so we can suggest a reason.
1547 msg = diag::err_bad_cxx_cast_rvalue;
1548 return TC_NotApplicable;
1549 }
1550
1551 QualType DestPointee = DestReference->getPointeeType();
1552
1553 // FIXME: If the source is a prvalue, we should issue a warning (because the
1554 // cast always has undefined behavior), and for AST consistency, we should
1555 // materialize a temporary.
1556 return TryStaticDowncast(Self,
1557 Self.Context.getCanonicalType(SrcExpr->getType()),
1558 Self.Context.getCanonicalType(DestPointee), CStyle,
1559 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1560 BasePath);
1561}
1562
1563/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1564TryCastResult
1565TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1566 bool CStyle, SourceRange OpRange,
1567 unsigned &msg, CastKind &Kind,
1568 CXXCastPath &BasePath) {
1569 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1570 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1571 // is a class derived from B, if a valid standard conversion from "pointer
1572 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1573 // class of D.
1574 // In addition, DR54 clarifies that the base must be accessible in the
1575 // current context.
1576
1577 const PointerType *DestPointer = DestType->getAs<PointerType>();
1578 if (!DestPointer) {
1579 return TC_NotApplicable;
1580 }
1581
1582 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1583 if (!SrcPointer) {
1584 msg = diag::err_bad_static_cast_pointer_nonpointer;
1585 return TC_NotApplicable;
1586 }
1587
1588 return TryStaticDowncast(Self,
1589 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1590 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1591 CStyle, OpRange, SrcType, DestType, msg, Kind,
1592 BasePath);
1593}
1594
1595/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1596/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1597/// DestType is possible and allowed.
1598TryCastResult
1599TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1600 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
1601 QualType OrigDestType, unsigned &msg,
1602 CastKind &Kind, CXXCastPath &BasePath) {
1603 // We can only work with complete types. But don't complain if it doesn't work
1604 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1605 !Self.isCompleteType(OpRange.getBegin(), DestType))
1606 return TC_NotApplicable;
1607
1608 // Downcast can only happen in class hierarchies, so we need classes.
1609 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1610 return TC_NotApplicable;
1611 }
1612
1613 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1614 /*DetectVirtual=*/true);
1615 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
1616 return TC_NotApplicable;
1617 }
1618
1619 // Target type does derive from source type. Now we're serious. If an error
1620 // appears now, it's not ignored.
1621 // This may not be entirely in line with the standard. Take for example:
1622 // struct A {};
1623 // struct B : virtual A {
1624 // B(A&);
1625 // };
1626 //
1627 // void f()
1628 // {
1629 // (void)static_cast<const B&>(*((A*)0));
1630 // }
1631 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1632 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1633 // However, both GCC and Comeau reject this example, and accepting it would
1634 // mean more complex code if we're to preserve the nice error message.
1635 // FIXME: Being 100% compliant here would be nice to have.
1636
1637 // Must preserve cv, as always, unless we're in C-style mode.
1638 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1639 msg = diag::err_bad_cxx_cast_qualifiers_away;
1640 return TC_Failed;
1641 }
1642
1643 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1644 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1645 // that it builds the paths in reverse order.
1646 // To sum up: record all paths to the base and build a nice string from
1647 // them. Use it to spice up the error message.
1648 if (!Paths.isRecordingPaths()) {
1649 Paths.clear();
1650 Paths.setRecordingPaths(true);
1651 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
1652 }
1653 std::string PathDisplayStr;
1654 std::set<unsigned> DisplayedPaths;
1655 for (clang::CXXBasePath &Path : Paths) {
1656 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
1657 // We haven't displayed a path to this particular base
1658 // class subobject yet.
1659 PathDisplayStr += "\n ";
1660 for (CXXBasePathElement &PE : llvm::reverse(Path))
1661 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
1662 PathDisplayStr += QualType(DestType).getAsString();
1663 }
1664 }
1665
1666 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1667 << QualType(SrcType).getUnqualifiedType()
1668 << QualType(DestType).getUnqualifiedType()
1669 << PathDisplayStr << OpRange;
1670 msg = 0;
1671 return TC_Failed;
1672 }
1673
1674 if (Paths.getDetectedVirtual() != nullptr) {
1675 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1676 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1677 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1678 msg = 0;
1679 return TC_Failed;
1680 }
1681
1682 if (!CStyle) {
1683 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1684 SrcType, DestType,
1685 Paths.front(),
1686 diag::err_downcast_from_inaccessible_base)) {
1687 case Sema::AR_accessible:
1688 case Sema::AR_delayed: // be optimistic
1689 case Sema::AR_dependent: // be optimistic
1690 break;
1691
1692 case Sema::AR_inaccessible:
1693 msg = 0;
1694 return TC_Failed;
1695 }
1696 }
1697
1698 Self.BuildBasePathArray(Paths, BasePath);
1699 Kind = CK_BaseToDerived;
1700 return TC_Success;
1701}
1702
1703/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1704/// C++ 5.2.9p9 is valid:
1705///
1706/// An rvalue of type "pointer to member of D of type cv1 T" can be
1707/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1708/// where B is a base class of D [...].
1709///
1710TryCastResult
1711TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1712 QualType DestType, bool CStyle,
1713 SourceRange OpRange,
1714 unsigned &msg, CastKind &Kind,
1715 CXXCastPath &BasePath) {
1716 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1717 if (!DestMemPtr)
1718 return TC_NotApplicable;
1719
1720 bool WasOverloadedFunction = false;
1721 DeclAccessPair FoundOverload;
1722 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1723 if (FunctionDecl *Fn
1724 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1725 FoundOverload)) {
1726 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1727 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1728 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1729 WasOverloadedFunction = true;
1730 }
1731 }
1732
1733 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1734 if (!SrcMemPtr) {
1735 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1736 return TC_NotApplicable;
1737 }
1738
1739 // Lock down the inheritance model right now in MS ABI, whether or not the
1740 // pointee types are the same.
1741 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1742 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1743 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1744 }
1745
1746 // T == T, modulo cv
1747 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1748 DestMemPtr->getPointeeType()))
1749 return TC_NotApplicable;
1750
1751 // B base of D
1752 QualType SrcClass(SrcMemPtr->getClass(), 0);
1753 QualType DestClass(DestMemPtr->getClass(), 0);
1754 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1755 /*DetectVirtual=*/true);
1756 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
1757 return TC_NotApplicable;
1758
1759 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1760 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1761 Paths.clear();
1762 Paths.setRecordingPaths(true);
1763 bool StillOkay =
1764 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
1765 assert(StillOkay)(static_cast <bool> (StillOkay) ? void (0) : __assert_fail
("StillOkay", "clang/lib/Sema/SemaCast.cpp", 1765, __extension__
__PRETTY_FUNCTION__))
;
1766 (void)StillOkay;
1767 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1768 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1769 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1770 msg = 0;
1771 return TC_Failed;
1772 }
1773
1774 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1775 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1776 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1777 msg = 0;
1778 return TC_Failed;
1779 }
1780
1781 if (!CStyle) {
1782 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1783 DestClass, SrcClass,
1784 Paths.front(),
1785 diag::err_upcast_to_inaccessible_base)) {
1786 case Sema::AR_accessible:
1787 case Sema::AR_delayed:
1788 case Sema::AR_dependent:
1789 // Optimistically assume that the delayed and dependent cases
1790 // will work out.
1791 break;
1792
1793 case Sema::AR_inaccessible:
1794 msg = 0;
1795 return TC_Failed;
1796 }
1797 }
1798
1799 if (WasOverloadedFunction) {
1800 // Resolve the address of the overloaded function again, this time
1801 // allowing complaints if something goes wrong.
1802 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1803 DestType,
1804 true,
1805 FoundOverload);
1806 if (!Fn) {
1807 msg = 0;
1808 return TC_Failed;
1809 }
1810
1811 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1812 if (!SrcExpr.isUsable()) {
1813 msg = 0;
1814 return TC_Failed;
1815 }
1816 }
1817
1818 Self.BuildBasePathArray(Paths, BasePath);
1819 Kind = CK_DerivedToBaseMemberPointer;
1820 return TC_Success;
1821}
1822
1823/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1824/// is valid:
1825///
1826/// An expression e can be explicitly converted to a type T using a
1827/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1828TryCastResult
1829TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1830 Sema::CheckedConversionKind CCK,
1831 SourceRange OpRange, unsigned &msg,
1832 CastKind &Kind, bool ListInitialization) {
1833 if (DestType->isRecordType()) {
1834 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1835 diag::err_bad_cast_incomplete) ||
1836 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1837 diag::err_allocation_of_abstract_type)) {
1838 msg = 0;
1839 return TC_Failed;
1840 }
1841 }
1842
1843 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1844 InitializationKind InitKind
1845 = (CCK == Sema::CCK_CStyleCast)
1846 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1847 ListInitialization)
1848 : (CCK == Sema::CCK_FunctionalCast)
1849 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1850 : InitializationKind::CreateCast(OpRange);
1851 Expr *SrcExprRaw = SrcExpr.get();
1852 // FIXME: Per DR242, we should check for an implicit conversion sequence
1853 // or for a constructor that could be invoked by direct-initialization
1854 // here, not for an initialization sequence.
1855 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1856
1857 // At this point of CheckStaticCast, if the destination is a reference,
1858 // or the expression is an overload expression this has to work.
1859 // There is no other way that works.
1860 // On the other hand, if we're checking a C-style cast, we've still got
1861 // the reinterpret_cast way.
1862 bool CStyle
1863 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1864 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1865 return TC_NotApplicable;
1866
1867 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1868 if (Result.isInvalid()) {
1869 msg = 0;
1870 return TC_Failed;
1871 }
1872
1873 if (InitSeq.isConstructorInitialization())
1874 Kind = CK_ConstructorConversion;
1875 else
1876 Kind = CK_NoOp;
1877
1878 SrcExpr = Result;
1879 return TC_Success;
1880}
1881
1882/// TryConstCast - See if a const_cast from source to destination is allowed,
1883/// and perform it if it is.
1884static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1885 QualType DestType, bool CStyle,
1886 unsigned &msg) {
1887 DestType = Self.Context.getCanonicalType(DestType);
1888 QualType SrcType = SrcExpr.get()->getType();
1889 bool NeedToMaterializeTemporary = false;
1890
1891 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1892 // C++11 5.2.11p4:
1893 // if a pointer to T1 can be explicitly converted to the type "pointer to
1894 // T2" using a const_cast, then the following conversions can also be
1895 // made:
1896 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1897 // type T2 using the cast const_cast<T2&>;
1898 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1899 // type T2 using the cast const_cast<T2&&>; and
1900 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1901 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1902
1903 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1904 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1905 // is C-style, static_cast might find a way, so we simply suggest a
1906 // message and tell the parent to keep searching.
1907 msg = diag::err_bad_cxx_cast_rvalue;
1908 return TC_NotApplicable;
1909 }
1910
1911 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isPRValue()) {
1912 if (!SrcType->isRecordType()) {
1913 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1914 // this is C-style, static_cast can do this.
1915 msg = diag::err_bad_cxx_cast_rvalue;
1916 return TC_NotApplicable;
1917 }
1918
1919 // Materialize the class prvalue so that the const_cast can bind a
1920 // reference to it.
1921 NeedToMaterializeTemporary = true;
1922 }
1923
1924 // It's not completely clear under the standard whether we can
1925 // const_cast bit-field gl-values. Doing so would not be
1926 // intrinsically complicated, but for now, we say no for
1927 // consistency with other compilers and await the word of the
1928 // committee.
1929 if (SrcExpr.get()->refersToBitField()) {
1930 msg = diag::err_bad_cxx_cast_bitfield;
1931 return TC_NotApplicable;
1932 }
1933
1934 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1935 SrcType = Self.Context.getPointerType(SrcType);
1936 }
1937
1938 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1939 // the rules for const_cast are the same as those used for pointers.
1940
1941 if (!DestType->isPointerType() &&
1942 !DestType->isMemberPointerType() &&
1943 !DestType->isObjCObjectPointerType()) {
1944 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1945 // was a reference type, we converted it to a pointer above.
1946 // The status of rvalue references isn't entirely clear, but it looks like
1947 // conversion to them is simply invalid.
1948 // C++ 5.2.11p3: For two pointer types [...]
1949 if (!CStyle)
1950 msg = diag::err_bad_const_cast_dest;
1951 return TC_NotApplicable;
1952 }
1953 if (DestType->isFunctionPointerType() ||
1954 DestType->isMemberFunctionPointerType()) {
1955 // Cannot cast direct function pointers.
1956 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1957 // T is the ultimate pointee of source and target type.
1958 if (!CStyle)
1959 msg = diag::err_bad_const_cast_dest;
1960 return TC_NotApplicable;
1961 }
1962
1963 // C++ [expr.const.cast]p3:
1964 // "For two similar types T1 and T2, [...]"
1965 //
1966 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1967 // type qualifiers. (Likewise, we ignore other changes when determining
1968 // whether a cast casts away constness.)
1969 if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
1970 return TC_NotApplicable;
1971
1972 if (NeedToMaterializeTemporary)
1973 // This is a const_cast from a class prvalue to an rvalue reference type.
1974 // Materialize a temporary to store the result of the conversion.
1975 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1976 SrcExpr.get(),
1977 /*IsLValueReference*/ false);
1978
1979 return TC_Success;
1980}
1981
1982// Checks for undefined behavior in reinterpret_cast.
1983// The cases that is checked for is:
1984// *reinterpret_cast<T*>(&a)
1985// reinterpret_cast<T&>(a)
1986// where accessing 'a' as type 'T' will result in undefined behavior.
1987void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1988 bool IsDereference,
1989 SourceRange Range) {
1990 unsigned DiagID = IsDereference ?
1991 diag::warn_pointer_indirection_from_incompatible_type :
1992 diag::warn_undefined_reinterpret_cast;
1993
1994 if (Diags.isIgnored(DiagID, Range.getBegin()))
1995 return;
1996
1997 QualType SrcTy, DestTy;
1998 if (IsDereference) {
1999 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
2000 return;
2001 }
2002 SrcTy = SrcType->getPointeeType();
2003 DestTy = DestType->getPointeeType();
2004 } else {
2005 if (!DestType->getAs<ReferenceType>()) {
2006 return;
2007 }
2008 SrcTy = SrcType;
2009 DestTy = DestType->getPointeeType();
2010 }
2011
2012 // Cast is compatible if the types are the same.
2013 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
2014 return;
2015 }
2016 // or one of the types is a char or void type
2017 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
2018 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
2019 return;
2020 }
2021 // or one of the types is a tag type.
2022 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
2023 return;
2024 }
2025
2026 // FIXME: Scoped enums?
2027 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
2028 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
2029 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
2030 return;
2031 }
2032 }
2033
2034 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
2035}
2036
2037static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
2038 QualType DestType) {
2039 QualType SrcType = SrcExpr.get()->getType();
2040 if (Self.Context.hasSameType(SrcType, DestType))
2041 return;
2042 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
2043 if (SrcPtrTy->isObjCSelType()) {
2044 QualType DT = DestType;
2045 if (isa<PointerType>(DestType))
2046 DT = DestType->getPointeeType();
2047 if (!DT.getUnqualifiedType()->isVoidType())
2048 Self.Diag(SrcExpr.get()->getExprLoc(),
2049 diag::warn_cast_pointer_from_sel)
2050 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2051 }
2052}
2053
2054/// Diagnose casts that change the calling convention of a pointer to a function
2055/// defined in the current TU.
2056static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
2057 QualType DstType, SourceRange OpRange) {
2058 // Check if this cast would change the calling convention of a function
2059 // pointer type.
2060 QualType SrcType = SrcExpr.get()->getType();
2061 if (Self.Context.hasSameType(SrcType, DstType) ||
2062 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
2063 return;
2064 const auto *SrcFTy =
2065 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
2066 const auto *DstFTy =
2067 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
2068 CallingConv SrcCC = SrcFTy->getCallConv();
2069 CallingConv DstCC = DstFTy->getCallConv();
2070 if (SrcCC == DstCC)
2071 return;
2072
2073 // We have a calling convention cast. Check if the source is a pointer to a
2074 // known, specific function that has already been defined.
2075 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
2076 if (auto *UO = dyn_cast<UnaryOperator>(Src))
2077 if (UO->getOpcode() == UO_AddrOf)
2078 Src = UO->getSubExpr()->IgnoreParenImpCasts();
2079 auto *DRE = dyn_cast<DeclRefExpr>(Src);
2080 if (!DRE)
2081 return;
2082 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2083 if (!FD)
2084 return;
2085
2086 // Only warn if we are casting from the default convention to a non-default
2087 // convention. This can happen when the programmer forgot to apply the calling
2088 // convention to the function declaration and then inserted this cast to
2089 // satisfy the type system.
2090 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
2091 FD->isVariadic(), FD->isCXXInstanceMember());
2092 if (DstCC == DefaultCC || SrcCC != DefaultCC)
2093 return;
2094
2095 // Diagnose this cast, as it is probably bad.
2096 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
2097 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
2098 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
2099 << SrcCCName << DstCCName << OpRange;
2100
2101 // The checks above are cheaper than checking if the diagnostic is enabled.
2102 // However, it's worth checking if the warning is enabled before we construct
2103 // a fixit.
2104 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
2105 return;
2106
2107 // Try to suggest a fixit to change the calling convention of the function
2108 // whose address was taken. Try to use the latest macro for the convention.
2109 // For example, users probably want to write "WINAPI" instead of "__stdcall"
2110 // to match the Windows header declarations.
2111 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
2112 Preprocessor &PP = Self.getPreprocessor();
2113 SmallVector<TokenValue, 6> AttrTokens;
2114 SmallString<64> CCAttrText;
2115 llvm::raw_svector_ostream OS(CCAttrText);
2116 if (Self.getLangOpts().MicrosoftExt) {
2117 // __stdcall or __vectorcall
2118 OS << "__" << DstCCName;
2119 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
2120 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2121 ? TokenValue(II->getTokenID())
2122 : TokenValue(II));
2123 } else {
2124 // __attribute__((stdcall)) or __attribute__((vectorcall))
2125 OS << "__attribute__((" << DstCCName << "))";
2126 AttrTokens.push_back(tok::kw___attribute);
2127 AttrTokens.push_back(tok::l_paren);
2128 AttrTokens.push_back(tok::l_paren);
2129 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
2130 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2131 ? TokenValue(II->getTokenID())
2132 : TokenValue(II));
2133 AttrTokens.push_back(tok::r_paren);
2134 AttrTokens.push_back(tok::r_paren);
2135 }
2136 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
2137 if (!AttrSpelling.empty())
2138 CCAttrText = AttrSpelling;
2139 OS << ' ';
2140 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
2141 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
2142}
2143
2144static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,
2145 const Expr *SrcExpr, QualType DestType,
2146 Sema &Self) {
2147 QualType SrcType = SrcExpr->getType();
2148
2149 // Not warning on reinterpret_cast, boolean, constant expressions, etc
2150 // are not explicit design choices, but consistent with GCC's behavior.
2151 // Feel free to modify them if you've reason/evidence for an alternative.
2152 if (CStyle && SrcType->isIntegralType(Self.Context)
2153 && !SrcType->isBooleanType()
2154 && !SrcType->isEnumeralType()
2155 && !SrcExpr->isIntegerConstantExpr(Self.Context)
2156 && Self.Context.getTypeSize(DestType) >
2157 Self.Context.getTypeSize(SrcType)) {
2158 // Separate between casts to void* and non-void* pointers.
2159 // Some APIs use (abuse) void* for something like a user context,
2160 // and often that value is an integer even if it isn't a pointer itself.
2161 // Having a separate warning flag allows users to control the warning
2162 // for their workflow.
2163 unsigned Diag = DestType->isVoidPointerType() ?
2164 diag::warn_int_to_void_pointer_cast
2165 : diag::warn_int_to_pointer_cast;
2166 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2167 }
2168}
2169
2170static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
2171 ExprResult &Result) {
2172 // We can only fix an overloaded reinterpret_cast if
2173 // - it is a template with explicit arguments that resolves to an lvalue
2174 // unambiguously, or
2175 // - it is the only function in an overload set that may have its address
2176 // taken.
2177
2178 Expr *E = Result.get();
2179 // TODO: what if this fails because of DiagnoseUseOfDecl or something
2180 // like it?
2181 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2182 Result,
2183 Expr::getValueKindForType(DestType) ==
2184 VK_PRValue // Convert Fun to Ptr
2185 ) &&
2186 Result.isUsable())
2187 return true;
2188
2189 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
2190 // preserves Result.
2191 Result = E;
2192 if (!Self.resolveAndFixAddressOfSingleOverloadCandidate(
2193 Result, /*DoFunctionPointerConversion=*/true))
2194 return false;
2195 return Result.isUsable();
2196}
2197
2198static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
2199 QualType DestType, bool CStyle,
2200 SourceRange OpRange,
2201 unsigned &msg,
2202 CastKind &Kind) {
2203 bool IsLValueCast = false;
2204
2205 DestType = Self.Context.getCanonicalType(DestType);
2206 QualType SrcType = SrcExpr.get()->getType();
2207
2208 // Is the source an overloaded name? (i.e. &foo)
2209 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
2210 if (SrcType == Self.Context.OverloadTy) {
2211 ExprResult FixedExpr = SrcExpr;
2212 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
2213 return TC_NotApplicable;
2214
2215 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr")(static_cast <bool> (FixedExpr.isUsable() && "Invalid result fixing overloaded expr"
) ? void (0) : __assert_fail ("FixedExpr.isUsable() && \"Invalid result fixing overloaded expr\""
, "clang/lib/Sema/SemaCast.cpp", 2215, __extension__ __PRETTY_FUNCTION__
))
;
2216 SrcExpr = FixedExpr;
2217 SrcType = SrcExpr.get()->getType();
2218 }
2219
2220 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
2221 if (!SrcExpr.get()->isGLValue()) {
2222 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2223 // similar comment in const_cast.
2224 msg = diag::err_bad_cxx_cast_rvalue;
2225 return TC_NotApplicable;
2226 }
2227
2228 if (!CStyle) {
2229 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
2230 /*IsDereference=*/false, OpRange);
2231 }
2232
2233 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2234 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2235 // built-in & and * operators.
2236
2237 const char *inappropriate = nullptr;
2238 switch (SrcExpr.get()->getObjectKind()) {
2239 case OK_Ordinary:
2240 break;
2241 case OK_BitField:
2242 msg = diag::err_bad_cxx_cast_bitfield;
2243 return TC_NotApplicable;
2244 // FIXME: Use a specific diagnostic for the rest of these cases.
2245 case OK_VectorComponent: inappropriate = "vector element"; break;
2246 case OK_MatrixComponent:
2247 inappropriate = "matrix element";
2248 break;
2249 case OK_ObjCProperty: inappropriate = "property expression"; break;
2250 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
2251 break;
2252 }
2253 if (inappropriate) {
2254 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2255 << inappropriate << DestType
2256 << OpRange << SrcExpr.get()->getSourceRange();
2257 msg = 0; SrcExpr = ExprError();
2258 return TC_NotApplicable;
2259 }
2260
2261 // This code does this transformation for the checked types.
2262 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2263 SrcType = Self.Context.getPointerType(SrcType);
2264
2265 IsLValueCast = true;
2266 }
2267
2268 // Canonicalize source for comparison.
2269 SrcType = Self.Context.getCanonicalType(SrcType);
2270
2271 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2272 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
2273 if (DestMemPtr && SrcMemPtr) {
2274 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2275 // can be explicitly converted to an rvalue of type "pointer to member
2276 // of Y of type T2" if T1 and T2 are both function types or both object
2277 // types.
2278 if (DestMemPtr->isMemberFunctionPointer() !=
2279 SrcMemPtr->isMemberFunctionPointer())
2280 return TC_NotApplicable;
2281
2282 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2283 // We need to determine the inheritance model that the class will use if
2284 // haven't yet.
2285 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2286 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
2287 }
2288
2289 // Don't allow casting between member pointers of different sizes.
2290 if (Self.Context.getTypeSize(DestMemPtr) !=
2291 Self.Context.getTypeSize(SrcMemPtr)) {
2292 msg = diag::err_bad_cxx_cast_member_pointer_size;
2293 return TC_Failed;
2294 }
2295
2296 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2297 // constness.
2298 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2299 // we accept it.
2300 if (auto CACK =
2301 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2302 /*CheckObjCLifetime=*/CStyle))
2303 return getCastAwayConstnessCastKind(CACK, msg);
2304
2305 // A valid member pointer cast.
2306 assert(!IsLValueCast)(static_cast <bool> (!IsLValueCast) ? void (0) : __assert_fail
("!IsLValueCast", "clang/lib/Sema/SemaCast.cpp", 2306, __extension__
__PRETTY_FUNCTION__))
;
2307 Kind = CK_ReinterpretMemberPointer;
2308 return TC_Success;
2309 }
2310
2311 // See below for the enumeral issue.
2312 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
2313 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2314 // type large enough to hold it. A value of std::nullptr_t can be
2315 // converted to an integral type; the conversion has the same meaning
2316 // and validity as a conversion of (void*)0 to the integral type.
2317 if (Self.Context.getTypeSize(SrcType) >
2318 Self.Context.getTypeSize(DestType)) {
2319 msg = diag::err_bad_reinterpret_cast_small_int;
2320 return TC_Failed;
2321 }
2322 Kind = CK_PointerToIntegral;
2323 return TC_Success;
2324 }
2325
2326 // Allow reinterpret_casts between vectors of the same size and
2327 // between vectors and integers of the same size.
2328 bool destIsVector = DestType->isVectorType();
2329 bool srcIsVector = SrcType->isVectorType();
2330 if (srcIsVector || destIsVector) {
2331 // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
2332 if (Self.isValidSveBitcast(SrcType, DestType)) {
2333 Kind = CK_BitCast;
2334 return TC_Success;
2335 }
2336
2337 // The non-vector type, if any, must have integral type. This is
2338 // the same rule that C vector casts use; note, however, that enum
2339 // types are not integral in C++.
2340 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2341 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
2342 return TC_NotApplicable;
2343
2344 // The size we want to consider is eltCount * eltSize.
2345 // That's exactly what the lax-conversion rules will check.
2346 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
2347 Kind = CK_BitCast;
2348 return TC_Success;
2349 }
2350
2351 if (Self.LangOpts.OpenCL && !CStyle) {
2352 if (DestType->isExtVectorType() || SrcType->isExtVectorType()) {
2353 // FIXME: Allow for reinterpret cast between 3 and 4 element vectors
2354 if (Self.areVectorTypesSameSize(SrcType, DestType)) {
2355 Kind = CK_BitCast;
2356 return TC_Success;
2357 }
2358 }
2359 }
2360
2361 // Otherwise, pick a reasonable diagnostic.
2362 if (!destIsVector)
2363 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2364 else if (!srcIsVector)
2365 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2366 else
2367 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2368
2369 return TC_Failed;
2370 }
2371
2372 if (SrcType == DestType) {
2373 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2374 // restrictions, a cast to the same type is allowed so long as it does not
2375 // cast away constness. In C++98, the intent was not entirely clear here,
2376 // since all other paragraphs explicitly forbid casts to the same type.
2377 // C++11 clarifies this case with p2.
2378 //
2379 // The only allowed types are: integral, enumeration, pointer, or
2380 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2381 Kind = CK_NoOp;
2382 TryCastResult Result = TC_NotApplicable;
2383 if (SrcType->isIntegralOrEnumerationType() ||
2384 SrcType->isAnyPointerType() ||
2385 SrcType->isMemberPointerType() ||
2386 SrcType->isBlockPointerType()) {
2387 Result = TC_Success;
2388 }
2389 return Result;
2390 }
2391
2392 bool destIsPtr = DestType->isAnyPointerType() ||
2393 DestType->isBlockPointerType();
2394 bool srcIsPtr = SrcType->isAnyPointerType() ||
2395 SrcType->isBlockPointerType();
2396 if (!destIsPtr && !srcIsPtr) {
2397 // Except for std::nullptr_t->integer and lvalue->reference, which are
2398 // handled above, at least one of the two arguments must be a pointer.
2399 return TC_NotApplicable;
2400 }
2401
2402 if (DestType->isIntegralType(Self.Context)) {
2403 assert(srcIsPtr && "One type must be a pointer")(static_cast <bool> (srcIsPtr && "One type must be a pointer"
) ? void (0) : __assert_fail ("srcIsPtr && \"One type must be a pointer\""
, "clang/lib/Sema/SemaCast.cpp", 2403, __extension__ __PRETTY_FUNCTION__
))
;
2404 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2405 // type large enough to hold it; except in Microsoft mode, where the
2406 // integral type size doesn't matter (except we don't allow bool).
2407 if ((Self.Context.getTypeSize(SrcType) >
2408 Self.Context.getTypeSize(DestType))) {
2409 bool MicrosoftException =
2410 Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType();
2411 if (MicrosoftException) {
2412 unsigned Diag = SrcType->isVoidPointerType()
2413 ? diag::warn_void_pointer_to_int_cast
2414 : diag::warn_pointer_to_int_cast;
2415 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2416 } else {
2417 msg = diag::err_bad_reinterpret_cast_small_int;
2418 return TC_Failed;
2419 }
2420 }
2421 Kind = CK_PointerToIntegral;
2422 return TC_Success;
2423 }
2424
2425 if (SrcType->isIntegralOrEnumerationType()) {
2426 assert(destIsPtr && "One type must be a pointer")(static_cast <bool> (destIsPtr && "One type must be a pointer"
) ? void (0) : __assert_fail ("destIsPtr && \"One type must be a pointer\""
, "clang/lib/Sema/SemaCast.cpp", 2426, __extension__ __PRETTY_FUNCTION__
))
;
2427 checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self);
2428 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2429 // converted to a pointer.
2430 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2431 // necessarily converted to a null pointer value.]
2432 Kind = CK_IntegralToPointer;
2433 return TC_Success;
2434 }
2435
2436 if (!destIsPtr || !srcIsPtr) {
2437 // With the valid non-pointer conversions out of the way, we can be even
2438 // more stringent.
2439 return TC_NotApplicable;
2440 }
2441
2442 // Cannot convert between block pointers and Objective-C object pointers.
2443 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2444 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2445 return TC_NotApplicable;
2446
2447 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2448 // The C-style cast operator can.
2449 TryCastResult SuccessResult = TC_Success;
2450 if (auto CACK =
2451 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2452 /*CheckObjCLifetime=*/CStyle))
2453 SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2454
2455 if (IsAddressSpaceConversion(SrcType, DestType)) {
2456 Kind = CK_AddressSpaceConversion;
2457 assert(SrcType->isPointerType() && DestType->isPointerType())(static_cast <bool> (SrcType->isPointerType() &&
DestType->isPointerType()) ? void (0) : __assert_fail ("SrcType->isPointerType() && DestType->isPointerType()"
, "clang/lib/Sema/SemaCast.cpp", 2457, __extension__ __PRETTY_FUNCTION__
))
;
2458 if (!CStyle &&
2459 !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
2460 SrcType->getPointeeType().getQualifiers())) {
2461 SuccessResult = TC_Failed;
2462 }
2463 } else if (IsLValueCast) {
2464 Kind = CK_LValueBitCast;
2465 } else if (DestType->isObjCObjectPointerType()) {
2466 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
2467 } else if (DestType->isBlockPointerType()) {
2468 if (!SrcType->isBlockPointerType()) {
2469 Kind = CK_AnyPointerToBlockPointerCast;
2470 } else {
2471 Kind = CK_BitCast;
2472 }
2473 } else {
2474 Kind = CK_BitCast;
2475 }
2476
2477 // Any pointer can be cast to an Objective-C pointer type with a C-style
2478 // cast.
2479 if (CStyle && DestType->isObjCObjectPointerType()) {
2480 return SuccessResult;
2481 }
2482 if (CStyle)
2483 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2484
2485 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2486
2487 // Not casting away constness, so the only remaining check is for compatible
2488 // pointer categories.
2489
2490 if (SrcType->isFunctionPointerType()) {
2491 if (DestType->isFunctionPointerType()) {
2492 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2493 // a pointer to a function of a different type.
2494 return SuccessResult;
2495 }
2496
2497 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2498 // an object type or vice versa is conditionally-supported.
2499 // Compilers support it in C++03 too, though, because it's necessary for
2500 // casting the return value of dlsym() and GetProcAddress().
2501 // FIXME: Conditionally-supported behavior should be configurable in the
2502 // TargetInfo or similar.
2503 Self.Diag(OpRange.getBegin(),
2504 Self.getLangOpts().CPlusPlus11 ?
2505 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2506 << OpRange;
2507 return SuccessResult;
2508 }
2509
2510 if (DestType->isFunctionPointerType()) {
2511 // See above.
2512 Self.Diag(OpRange.getBegin(),
2513 Self.getLangOpts().CPlusPlus11 ?
2514 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2515 << OpRange;
2516 return SuccessResult;
2517 }
2518
2519 // Diagnose address space conversion in nested pointers.
2520 QualType DestPtee = DestType->getPointeeType().isNull()
2521 ? DestType->getPointeeType()
2522 : DestType->getPointeeType()->getPointeeType();
2523 QualType SrcPtee = SrcType->getPointeeType().isNull()
2524 ? SrcType->getPointeeType()
2525 : SrcType->getPointeeType()->getPointeeType();
2526 while (!DestPtee.isNull() && !SrcPtee.isNull()) {
2527 if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {
2528 Self.Diag(OpRange.getBegin(),
2529 diag::warn_bad_cxx_cast_nested_pointer_addr_space)
2530 << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();
2531 break;
2532 }
2533 DestPtee = DestPtee->getPointeeType();
2534 SrcPtee = SrcPtee->getPointeeType();
2535 }
2536
2537 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2538 // a pointer to an object of different type.
2539 // Void pointers are not specified, but supported by every compiler out there.
2540 // So we finish by allowing everything that remains - it's got to be two
2541 // object pointers.
2542 return SuccessResult;
2543}
2544
2545static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
2546 QualType DestType, bool CStyle,
2547 unsigned &msg, CastKind &Kind) {
2548 if (!Self.getLangOpts().OpenCL)
2549 // FIXME: As compiler doesn't have any information about overlapping addr
2550 // spaces at the moment we have to be permissive here.
2551 return TC_NotApplicable;
2552 // Even though the logic below is general enough and can be applied to
2553 // non-OpenCL mode too, we fast-path above because no other languages
2554 // define overlapping address spaces currently.
2555 auto SrcType = SrcExpr.get()->getType();
2556 // FIXME: Should this be generalized to references? The reference parameter
2557 // however becomes a reference pointee type here and therefore rejected.
2558 // Perhaps this is the right behavior though according to C++.
2559 auto SrcPtrType = SrcType->getAs<PointerType>();
2560 if (!SrcPtrType)
2561 return TC_NotApplicable;
2562 auto DestPtrType = DestType->getAs<PointerType>();
2563 if (!DestPtrType)
2564 return TC_NotApplicable;
2565 auto SrcPointeeType = SrcPtrType->getPointeeType();
2566 auto DestPointeeType = DestPtrType->getPointeeType();
2567 if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {
2568 msg = diag::err_bad_cxx_cast_addr_space_mismatch;
2569 return TC_Failed;
2570 }
2571 auto SrcPointeeTypeWithoutAS =
2572 Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());
2573 auto DestPointeeTypeWithoutAS =
2574 Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());
2575 if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS,
2576 DestPointeeTypeWithoutAS)) {
2577 Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()
2578 ? CK_NoOp
2579 : CK_AddressSpaceConversion;
2580 return TC_Success;
2581 } else {
2582 return TC_NotApplicable;
2583 }
2584}
2585
2586void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2587 // In OpenCL only conversions between pointers to objects in overlapping
2588 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2589 // with any named one, except for constant.
2590
2591 // Converting the top level pointee addrspace is permitted for compatible
2592 // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2593 // if any of the nested pointee addrspaces differ, we emit a warning
2594 // regardless of addrspace compatibility. This makes
2595 // local int ** p;
2596 // return (generic int **) p;
2597 // warn even though local -> generic is permitted.
2598 if (Self.getLangOpts().OpenCL) {
2599 const Type *DestPtr, *SrcPtr;
2600 bool Nested = false;
2601 unsigned DiagID = diag::err_typecheck_incompatible_address_space;
2602 DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),
2603 SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());
2604
2605 while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) {
2606 const PointerType *DestPPtr = cast<PointerType>(DestPtr);
2607 const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);
2608 QualType DestPPointee = DestPPtr->getPointeeType();
2609 QualType SrcPPointee = SrcPPtr->getPointeeType();
2610 if (Nested
2611 ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
2612 : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) {
2613 Self.Diag(OpRange.getBegin(), DiagID)
2614 << SrcType << DestType << Sema::AA_Casting
2615 << SrcExpr.get()->getSourceRange();
2616 if (!Nested)
2617 SrcExpr = ExprError();
2618 return;
2619 }
2620
2621 DestPtr = DestPPtr->getPointeeType().getTypePtr();
2622 SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
2623 Nested = true;
2624 DiagID = diag::ext_nested_pointer_qualifier_mismatch;
2625 }
2626 }
2627}
2628
2629bool Sema::ShouldSplatAltivecScalarInCast(const VectorType *VecTy) {
2630 bool SrcCompatXL = this->getLangOpts().getAltivecSrcCompat() ==
2631 LangOptions::AltivecSrcCompatKind::XL;
2632 VectorType::VectorKind VKind = VecTy->getVectorKind();
2633
2634 if ((VKind == VectorType::AltiVecVector) ||
2635 (SrcCompatXL && ((VKind == VectorType::AltiVecBool) ||
2636 (VKind == VectorType::AltiVecPixel)))) {
2637 return true;
2638 }
2639 return false;
2640}
2641
2642bool Sema::CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2643 QualType SrcTy) {
2644 bool SrcCompatGCC = this->getLangOpts().getAltivecSrcCompat() ==
2645 LangOptions::AltivecSrcCompatKind::GCC;
2646 if (this->getLangOpts().AltiVec && SrcCompatGCC) {
2647 this->Diag(R.getBegin(),
2648 diag::err_invalid_conversion_between_vector_and_integer)
2649 << VecTy << SrcTy << R;
2650 return true;
2651 }
2652 return false;
2653}
2654
2655void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2656 bool ListInitialization) {
2657 assert(Self.getLangOpts().CPlusPlus)(static_cast <bool> (Self.getLangOpts().CPlusPlus) ? void
(0) : __assert_fail ("Self.getLangOpts().CPlusPlus", "clang/lib/Sema/SemaCast.cpp"
, 2657, __extension__ __PRETTY_FUNCTION__))
;
2658
2659 // Handle placeholders.
2660 if (isPlaceholder()) {
2661 // C-style casts can resolve __unknown_any types.
2662 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2663 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2664 SrcExpr.get(), Kind,
2665 ValueKind, BasePath);
2666 return;
2667 }
2668
2669 checkNonOverloadPlaceholders();
2670 if (SrcExpr.isInvalid())
2671 return;
2672 }
2673
2674 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2675 // This test is outside everything else because it's the only case where
2676 // a non-lvalue-reference target type does not lead to decay.
2677 if (DestType->isVoidType()) {
2678 Kind = CK_ToVoid;
2679
2680 if (claimPlaceholder(BuiltinType::Overload)) {
2681 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2682 SrcExpr, /* Decay Function to ptr */ false,
2683 /* Complain */ true, DestRange, DestType,
2684 diag::err_bad_cstyle_cast_overload);
2685 if (SrcExpr.isInvalid())
2686 return;
2687 }
2688
2689 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2690 return;
2691 }
2692
2693 // If the type is dependent, we won't do any other semantic analysis now.
2694 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2695 SrcExpr.get()->isValueDependent()) {
2696 assert(Kind == CK_Dependent)(static_cast <bool> (Kind == CK_Dependent) ? void (0) :
__assert_fail ("Kind == CK_Dependent", "clang/lib/Sema/SemaCast.cpp"
, 2696, __extension__ __PRETTY_FUNCTION__))
;
2697 return;
2698 }
2699
2700 if (ValueKind == VK_PRValue && !DestType->isRecordType() &&
2701 !isPlaceholder(BuiltinType::Overload)) {
2702 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2703 if (SrcExpr.isInvalid())
2704 return;
2705 }
2706
2707 // AltiVec vector initialization with a single literal.
2708 if (const VectorType *vecTy = DestType->getAs<VectorType>()) {
2709 if (Self.CheckAltivecInitFromScalar(OpRange, DestType,
2710 SrcExpr.get()->getType())) {
2711 SrcExpr = ExprError();
2712 return;
2713 }
2714 if (Self.ShouldSplatAltivecScalarInCast(vecTy) &&
2715 (SrcExpr.get()->getType()->isIntegerType() ||
2716 SrcExpr.get()->getType()->isFloatingType())) {
2717 Kind = CK_VectorSplat;
2718 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2719 return;
2720 }
2721 }
2722
2723 // C++ [expr.cast]p5: The conversions performed by
2724 // - a const_cast,
2725 // - a static_cast,
2726 // - a static_cast followed by a const_cast,
2727 // - a reinterpret_cast, or
2728 // - a reinterpret_cast followed by a const_cast,
2729 // can be performed using the cast notation of explicit type conversion.
2730 // [...] If a conversion can be interpreted in more than one of the ways
2731 // listed above, the interpretation that appears first in the list is used,
2732 // even if a cast resulting from that interpretation is ill-formed.
2733 // In plain language, this means trying a const_cast ...
2734 // Note that for address space we check compatibility after const_cast.
2735 unsigned msg = diag::err_bad_cxx_cast_generic;
2736 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2737 /*CStyle*/ true, msg);
2738 if (SrcExpr.isInvalid())
2739 return;
2740 if (isValidCast(tcr))
2741 Kind = CK_NoOp;
2742
2743 Sema::CheckedConversionKind CCK =
2744 FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast;
2745 if (tcr == TC_NotApplicable) {
2746 tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
2747 Kind);
2748 if (SrcExpr.isInvalid())
2749 return;
2750
2751 if (tcr == TC_NotApplicable) {
2752 // ... or if that is not possible, a static_cast, ignoring const and
2753 // addr space, ...
2754 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
2755 BasePath, ListInitialization);
2756 if (SrcExpr.isInvalid())
2757 return;
2758
2759 if (tcr == TC_NotApplicable) {
2760 // ... and finally a reinterpret_cast, ignoring const and addr space.
2761 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
2762 OpRange, msg, Kind);
2763 if (SrcExpr.isInvalid())
2764 return;
2765 }
2766 }
2767 }
2768
2769 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2770 isValidCast(tcr))
2771 checkObjCConversion(CCK);
2772
2773 if (tcr != TC_Success && msg != 0) {
2774 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2775 DeclAccessPair Found;
2776 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2777 DestType,
2778 /*Complain*/ true,
2779 Found);
2780 if (Fn) {
2781 // If DestType is a function type (not to be confused with the function
2782 // pointer type), it will be possible to resolve the function address,
2783 // but the type cast should be considered as failure.
2784 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2785 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2786 << OE->getName() << DestType << OpRange
2787 << OE->getQualifierLoc().getSourceRange();
2788 Self.NoteAllOverloadCandidates(SrcExpr.get());
2789 }
2790 } else {
2791 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2792 OpRange, SrcExpr.get(), DestType, ListInitialization);
2793 }
2794 }
2795
2796 if (isValidCast(tcr)) {
2797 if (Kind == CK_BitCast)
2798 checkCastAlign();
2799
2800 if (!checkCastFunctionType(Self, SrcExpr, DestType))
2801 Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
2802 << SrcExpr.get()->getType() << DestType << OpRange;
2803
2804 } else {
2805 SrcExpr = ExprError();
2806 }
2807}
2808
2809/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2810/// non-matching type. Such as enum function call to int, int call to
2811/// pointer; etc. Cast to 'void' is an exception.
2812static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2813 QualType DestType) {
2814 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2815 SrcExpr.get()->getExprLoc()))
2816 return;
2817
2818 if (!isa<CallExpr>(SrcExpr.get()))
2819 return;
2820
2821 QualType SrcType = SrcExpr.get()->getType();
2822 if (DestType.getUnqualifiedType()->isVoidType())
2823 return;
2824 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2825 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2826 return;
2827 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2828 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2829 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2830 return;
2831 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2832 return;
2833 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2834 return;
2835 if (SrcType->isComplexType() && DestType->isComplexType())
2836 return;
2837 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2838 return;
2839 if (SrcType->isFixedPointType() && DestType->isFixedPointType())
2840 return;
2841
2842 Self.Diag(SrcExpr.get()->getExprLoc(),
2843 diag::warn_bad_function_cast)
2844 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2845}
2846
2847/// Check the semantics of a C-style cast operation, in C.
2848void CastOperation::CheckCStyleCast() {
2849 assert(!Self.getLangOpts().CPlusPlus)(static_cast <bool> (!Self.getLangOpts().CPlusPlus) ? void
(0) : __assert_fail ("!Self.getLangOpts().CPlusPlus", "clang/lib/Sema/SemaCast.cpp"
, 2849, __extension__ __PRETTY_FUNCTION__))
;
2850
2851 // C-style casts can resolve __unknown_any types.
2852 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2853 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2854 SrcExpr.get(), Kind,
2855 ValueKind, BasePath);
2856 return;
2857 }
2858
2859 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2860 // type needs to be scalar.
2861 if (DestType->isVoidType()) {
2862 // We don't necessarily do lvalue-to-rvalue conversions on this.
2863 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2864 if (SrcExpr.isInvalid())
2865 return;
2866
2867 // Cast to void allows any expr type.
2868 Kind = CK_ToVoid;
2869 return;
2870 }
2871
2872 // If the type is dependent, we won't do any other semantic analysis now.
2873 if (Self.getASTContext().isDependenceAllowed() &&
2874 (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2875 SrcExpr.get()->isValueDependent())) {
2876 assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() ||(static_cast <bool> ((DestType->containsErrors() || SrcExpr
.get()->containsErrors() || SrcExpr.get()->containsErrors
()) && "should only occur in error-recovery path.") ?
void (0) : __assert_fail ("(DestType->containsErrors() || SrcExpr.get()->containsErrors() || SrcExpr.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaCast.cpp", 2878, __extension__ __PRETTY_FUNCTION__
))
2877 SrcExpr.get()->containsErrors()) &&(static_cast <bool> ((DestType->containsErrors() || SrcExpr
.get()->containsErrors() || SrcExpr.get()->containsErrors
()) && "should only occur in error-recovery path.") ?
void (0) : __assert_fail ("(DestType->containsErrors() || SrcExpr.get()->containsErrors() || SrcExpr.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaCast.cpp", 2878, __extension__ __PRETTY_FUNCTION__
))
2878 "should only occur in error-recovery path.")(static_cast <bool> ((DestType->containsErrors() || SrcExpr
.get()->containsErrors() || SrcExpr.get()->containsErrors
()) && "should only occur in error-recovery path.") ?
void (0) : __assert_fail ("(DestType->containsErrors() || SrcExpr.get()->containsErrors() || SrcExpr.get()->containsErrors()) && \"should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaCast.cpp", 2878, __extension__ __PRETTY_FUNCTION__
))
;
2879 assert(Kind == CK_Dependent)(static_cast <bool> (Kind == CK_Dependent) ? void (0) :
__assert_fail ("Kind == CK_Dependent", "clang/lib/Sema/SemaCast.cpp"
, 2879, __extension__ __PRETTY_FUNCTION__))
;
2880 return;
2881 }
2882
2883 // Overloads are allowed with C extensions, so we need to support them.
2884 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2885 DeclAccessPair DAP;
2886 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2887 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2888 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2889 else
2890 return;
2891 assert(SrcExpr.isUsable())(static_cast <bool> (SrcExpr.isUsable()) ? void (0) : __assert_fail
("SrcExpr.isUsable()", "clang/lib/Sema/SemaCast.cpp", 2891, __extension__
__PRETTY_FUNCTION__))
;
2892 }
2893 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2894 if (SrcExpr.isInvalid())
2895 return;
2896 QualType SrcType = SrcExpr.get()->getType();
2897
2898 assert(!SrcType->isPlaceholderType())(static_cast <bool> (!SrcType->isPlaceholderType()) ?
void (0) : __assert_fail ("!SrcType->isPlaceholderType()"
, "clang/lib/Sema/SemaCast.cpp", 2898, __extension__ __PRETTY_FUNCTION__
))
;
2899
2900 checkAddressSpaceCast(SrcType, DestType);
2901 if (SrcExpr.isInvalid())
2902 return;
2903
2904 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2905 diag::err_typecheck_cast_to_incomplete)) {
2906 SrcExpr = ExprError();
2907 return;
2908 }
2909
2910 // Allow casting a sizeless built-in type to itself.
2911 if (DestType->isSizelessBuiltinType() &&
2912 Self.Context.hasSameUnqualifiedType(DestType, SrcType)) {
2913 Kind = CK_NoOp;
2914 return;
2915 }
2916
2917 // Allow bitcasting between compatible SVE vector types.
2918 if ((SrcType->isVectorType() || DestType->isVectorType()) &&
2919 Self.isValidSveBitcast(SrcType, DestType)) {
2920 Kind = CK_BitCast;
2921 return;
2922 }
2923
2924 if (!DestType->isScalarType() && !DestType->isVectorType() &&
2925 !DestType->isMatrixType()) {
2926 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2927
2928 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2929 // GCC struct/union extension: allow cast to self.
2930 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2931 << DestType << SrcExpr.get()->getSourceRange();
2932 Kind = CK_NoOp;
2933 return;
2934 }
2935
2936 // GCC's cast to union extension.
2937 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2938 RecordDecl *RD = DestRecordTy->getDecl();
2939 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2940 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2941 << SrcExpr.get()->getSourceRange();
2942 Kind = CK_ToUnion;
2943 return;
2944 } else {
2945 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2946 << SrcType << SrcExpr.get()->getSourceRange();
2947 SrcExpr = ExprError();
2948 return;
2949 }
2950 }
2951
2952 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2953 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2954 Expr::EvalResult Result;
2955 if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
2956 llvm::APSInt CastInt = Result.Val.getInt();
2957 if (0 == CastInt) {
2958 Kind = CK_ZeroToOCLOpaqueType;
2959 return;
2960 }
2961 Self.Diag(OpRange.getBegin(),
2962 diag::err_opencl_cast_non_zero_to_event_t)
2963 << toString(CastInt, 10) << SrcExpr.get()->getSourceRange();
2964 SrcExpr = ExprError();
2965 return;
2966 }
2967 }
2968
2969 // Reject any other conversions to non-scalar types.
2970 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2971 << DestType << SrcExpr.get()->getSourceRange();
2972 SrcExpr = ExprError();
2973 return;
2974 }
2975
2976 // The type we're casting to is known to be a scalar, a vector, or a matrix.
2977
2978 // Require the operand to be a scalar, a vector, or a matrix.
2979 if (!SrcType->isScalarType() && !SrcType->isVectorType() &&
2980 !SrcType->isMatrixType()) {
2981 Self.Diag(SrcExpr.get()->getExprLoc(),
2982 diag::err_typecheck_expect_scalar_operand)
2983 << SrcType << SrcExpr.get()->getSourceRange();
2984 SrcExpr = ExprError();
2985 return;
2986 }
2987
2988 if (DestType->isExtVectorType()) {
2989 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
2990 return;
2991 }
2992
2993 if (DestType->getAs<MatrixType>() || SrcType->getAs<MatrixType>()) {
2994 if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind))
2995 SrcExpr = ExprError();
2996 return;
2997 }
2998
2999 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
3000 if (Self.CheckAltivecInitFromScalar(OpRange, DestType, SrcType)) {
3001 SrcExpr = ExprError();
3002 return;
3003 }
3004 if (Self.ShouldSplatAltivecScalarInCast(DestVecTy) &&
3005 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
3006 Kind = CK_VectorSplat;
3007 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
3008 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
3009 SrcExpr = ExprError();
3010 }
3011 return;
3012 }
3013
3014 if (SrcType->isVectorType()) {
3015 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
3016 SrcExpr = ExprError();
3017 return;
3018 }
3019
3020 // The source and target types are both scalars, i.e.
3021 // - arithmetic types (fundamental, enum, and complex)
3022 // - all kinds of pointers
3023 // Note that member pointers were filtered out with C++, above.
3024
3025 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
3026 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
3027 SrcExpr = ExprError();
3028 return;
3029 }
3030
3031 // Can't cast to or from bfloat
3032 if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()) {
3033 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16)
3034 << SrcExpr.get()->getSourceRange();
3035 SrcExpr = ExprError();
3036 return;
3037 }
3038 if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()) {
3039 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16)
3040 << SrcExpr.get()->getSourceRange();
3041 SrcExpr = ExprError();
3042 return;
3043 }
3044
3045 // If either type is a pointer, the other type has to be either an
3046 // integer or a pointer.
3047 if (!DestType->isArithmeticType()) {
3048 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
3049 Self.Diag(SrcExpr.get()->getExprLoc(),
3050 diag::err_cast_pointer_from_non_pointer_int)
3051 << SrcType << SrcExpr.get()->getSourceRange();
3052 SrcExpr = ExprError();
3053 return;
3054 }
3055 checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType,
3056 Self);
3057 } else if (!SrcType->isArithmeticType()) {
3058 if (!DestType->isIntegralType(Self.Context) &&
3059 DestType->isArithmeticType()) {
3060 Self.Diag(SrcExpr.get()->getBeginLoc(),
3061 diag::err_cast_pointer_to_non_pointer_int)
3062 << DestType << SrcExpr.get()->getSourceRange();
3063 SrcExpr = ExprError();
3064 return;
3065 }
3066
3067 if ((Self.Context.getTypeSize(SrcType) >
3068 Self.Context.getTypeSize(DestType)) &&
3069 !DestType->isBooleanType()) {
3070 // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
3071 // Except as previously specified, the result is implementation-defined.
3072 // If the result cannot be represented in the integer type, the behavior
3073 // is undefined. The result need not be in the range of values of any
3074 // integer type.
3075 unsigned Diag;
3076 if (SrcType->isVoidPointerType())
3077 Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
3078 : diag::warn_void_pointer_to_int_cast;
3079 else if (DestType->isEnumeralType())
3080 Diag = diag::warn_pointer_to_enum_cast;
3081 else
3082 Diag = diag::warn_pointer_to_int_cast;
3083 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
3084 }
3085 }
3086
3087 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption(
3088 "cl_khr_fp16", Self.getLangOpts())) {
3089 if (DestType->isHalfType()) {
3090 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
3091 << DestType << SrcExpr.get()->getSourceRange();
3092 SrcExpr = ExprError();
3093 return;
3094 }
3095 }
3096
3097 // ARC imposes extra restrictions on casts.
3098 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
3099 checkObjCConversion(Sema::CCK_CStyleCast);
3100 if (SrcExpr.isInvalid())
3101 return;
3102
3103 const PointerType *CastPtr = DestType->getAs<PointerType>();
3104 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
3105 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
3106 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
3107 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
3108 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
3109 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
3110 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
3111 Self.Diag(SrcExpr.get()->getBeginLoc(),
3112 diag::err_typecheck_incompatible_ownership)
3113 << SrcType << DestType << Sema::AA_Casting
3114 << SrcExpr.get()->getSourceRange();
3115 return;
3116 }
3117 }
3118 }
3119 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
3120 Self.Diag(SrcExpr.get()->getBeginLoc(),
3121 diag::err_arc_convesion_of_weak_unavailable)
3122 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
3123 SrcExpr = ExprError();
3124 return;
3125 }
3126 }
3127
3128 if (!checkCastFunctionType(Self, SrcExpr, DestType))
3129 Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
3130 << SrcType << DestType << OpRange;
3131
3132 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
3133 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
3134 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
3135 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
3136 if (SrcExpr.isInvalid())
3137 return;
3138
3139 if (Kind == CK_BitCast)
3140 checkCastAlign();
3141}
3142
3143void CastOperation::CheckBuiltinBitCast() {
3144 QualType SrcType = SrcExpr.get()->getType();
3145
3146 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
3147 diag::err_typecheck_cast_to_incomplete) ||
3148 Self.RequireCompleteType(OpRange.getBegin(), SrcType,
3149 diag::err_incomplete_type)) {
3150 SrcExpr = ExprError();
3151 return;
3152 }
3153
3154 if (SrcExpr.get()->isPRValue())
3155 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
3156 /*IsLValueReference=*/false);
3157
3158 CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);
3159 CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);
3160 if (DestSize != SourceSize) {
3161 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)
3162 << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity();
3163 SrcExpr = ExprError();
3164 return;
3165 }
3166
3167 if (!DestType.isTriviallyCopyableType(Self.Context)) {
3168 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
3169 << 1;
3170 SrcExpr = ExprError();
3171 return;
3172 }
3173
3174 if (!SrcType.isTriviallyCopyableType(Self.Context)) {
3175 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
3176 << 0;
3177 SrcExpr = ExprError();
3178 return;
3179 }
3180
3181 Kind = CK_LValueToRValueBitCast;
3182}
3183
3184/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
3185/// const, volatile or both.
3186static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
3187 QualType DestType) {
3188 if (SrcExpr.isInvalid())
3189 return;
3190
3191 QualType SrcType = SrcExpr.get()->getType();
3192 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
3193 DestType->isLValueReferenceType()))
3194 return;
3195
3196 QualType TheOffendingSrcType, TheOffendingDestType;
3197 Qualifiers CastAwayQualifiers;
3198 if (CastsAwayConstness(Self, SrcType, DestType, true, false,
3199 &TheOffendingSrcType, &TheOffendingDestType,
3200 &CastAwayQualifiers) !=
3201 CastAwayConstnessKind::CACK_Similar)
3202 return;
3203
3204 // FIXME: 'restrict' is not properly handled here.
3205 int qualifiers = -1;
3206 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
3207 qualifiers = 0;
3208 } else if (CastAwayQualifiers.hasConst()) {
3209 qualifiers = 1;
3210 } else if (CastAwayQualifiers.hasVolatile()) {
3211 qualifiers = 2;
3212 }
3213 // This is a variant of int **x; const int **y = (const int **)x;
3214 if (qualifiers == -1)
3215 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
3216 << SrcType << DestType;
3217 else
3218 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
3219 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
3220}
3221
3222ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
3223 TypeSourceInfo *CastTypeInfo,
3224 SourceLocation RPLoc,
3225 Expr *CastExpr) {
3226 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
3227 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3228 Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
3229
3230 if (getLangOpts().CPlusPlus) {
3231 Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
3232 isa<InitListExpr>(CastExpr));
3233 } else {
3234 Op.CheckCStyleCast();
3235 }
3236
3237 if (Op.SrcExpr.isInvalid())
3238 return ExprError();
3239
3240 // -Wcast-qual
3241 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
3242
3243 return Op.complete(CStyleCastExpr::Create(
3244 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
3245 &Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc));
3246}
3247
3248ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
3249 QualType Type,
3250 SourceLocation LPLoc,
3251 Expr *CastExpr,
3252 SourceLocation RPLoc) {
3253 assert(LPLoc.isValid() && "List-initialization shouldn't get here.")(static_cast <bool> (LPLoc.isValid() && "List-initialization shouldn't get here."
) ? void (0) : __assert_fail ("LPLoc.isValid() && \"List-initialization shouldn't get here.\""
, "clang/lib/Sema/SemaCast.cpp", 3253, __extension__ __PRETTY_FUNCTION__
))
;
3254 CastOperation Op(*this, Type, CastExpr);
3255 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3256 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
3257
3258 Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
3259 if (Op.SrcExpr.isInvalid())
3260 return ExprError();
3261
3262 auto *SubExpr = Op.SrcExpr.get();
3263 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
3264 SubExpr = BindExpr->getSubExpr();
3265 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
3266 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
3267
3268 return Op.complete(CXXFunctionalCastExpr::Create(
3269 Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind,
3270 Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc));
3271}

/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/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;
132class UsingShadowDecl;
133
134using CanQualType = CanQual<Type>;
135
136// Provide forward declarations for all of the *Type classes.
137#define TYPE(Class, Base) class Class##Type;
138#include "clang/AST/TypeNodes.inc"
139
140/// The collection of all-type qualifiers we support.
141/// Clang supports five independent qualifiers:
142/// * C99: const, volatile, and restrict
143/// * MS: __unaligned
144/// * Embedded C (TR18037): address spaces
145/// * Objective C: the GC attributes (none, weak, or strong)
146class Qualifiers {
147public:
148 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
149 Const = 0x1,
150 Restrict = 0x2,
151 Volatile = 0x4,
152 CVRMask = Const | Volatile | Restrict
153 };
154
155 enum GC {
156 GCNone = 0,
157 Weak,
158 Strong
159 };
160
161 enum ObjCLifetime {
162 /// There is no lifetime qualification on this type.
163 OCL_None,
164
165 /// This object can be modified without requiring retains or
166 /// releases.
167 OCL_ExplicitNone,
168
169 /// Assigning into this object requires the old value to be
170 /// released and the new value to be retained. The timing of the
171 /// release of the old value is inexact: it may be moved to
172 /// immediately after the last known point where the value is
173 /// live.
174 OCL_Strong,
175
176 /// Reading or writing from this object requires a barrier call.
177 OCL_Weak,
178
179 /// Assigning into this object requires a lifetime extension.
180 OCL_Autoreleasing
181 };
182
183 enum {
184 /// The maximum supported address space number.
185 /// 23 bits should be enough for anyone.
186 MaxAddressSpace = 0x7fffffu,
187
188 /// The width of the "fast" qualifier mask.
189 FastWidth = 3,
190
191 /// The fast qualifier mask.
192 FastMask = (1 << FastWidth) - 1
193 };
194
195 /// Returns the common set of qualifiers while removing them from
196 /// the given sets.
197 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
198 // If both are only CVR-qualified, bit operations are sufficient.
199 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
200 Qualifiers Q;
201 Q.Mask = L.Mask & R.Mask;
202 L.Mask &= ~Q.Mask;
203 R.Mask &= ~Q.Mask;
204 return Q;
205 }
206
207 Qualifiers Q;
208 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
209 Q.addCVRQualifiers(CommonCRV);
210 L.removeCVRQualifiers(CommonCRV);
211 R.removeCVRQualifiers(CommonCRV);
212
213 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
214 Q.setObjCGCAttr(L.getObjCGCAttr());
215 L.removeObjCGCAttr();
216 R.removeObjCGCAttr();
217 }
218
219 if (L.getObjCLifetime() == R.getObjCLifetime()) {
220 Q.setObjCLifetime(L.getObjCLifetime());
221 L.removeObjCLifetime();
222 R.removeObjCLifetime();
223 }
224
225 if (L.getAddressSpace() == R.getAddressSpace()) {
226 Q.setAddressSpace(L.getAddressSpace());
227 L.removeAddressSpace();
228 R.removeAddressSpace();
229 }
230 return Q;
231 }
232
233 static Qualifiers fromFastMask(unsigned Mask) {
234 Qualifiers Qs;
235 Qs.addFastQualifiers(Mask);
236 return Qs;
237 }
238
239 static Qualifiers fromCVRMask(unsigned CVR) {
240 Qualifiers Qs;
241 Qs.addCVRQualifiers(CVR);
242 return Qs;
243 }
244
245 static Qualifiers fromCVRUMask(unsigned CVRU) {
246 Qualifiers Qs;
247 Qs.addCVRUQualifiers(CVRU);
248 return Qs;
249 }
250
251 // Deserialize qualifiers from an opaque representation.
252 static Qualifiers fromOpaqueValue(unsigned opaque) {
253 Qualifiers Qs;
254 Qs.Mask = opaque;
255 return Qs;
256 }
257
258 // Serialize these qualifiers into an opaque representation.
259 unsigned getAsOpaqueValue() const {
260 return Mask;
261 }
262
263 bool hasConst() const { return Mask & Const; }
264 bool hasOnlyConst() const { return Mask == Const; }
265 void removeConst() { Mask &= ~Const; }
266 void addConst() { Mask |= Const; }
267
268 bool hasVolatile() const { return Mask & Volatile; }
269 bool hasOnlyVolatile() const { return Mask == Volatile; }
270 void removeVolatile() { Mask &= ~Volatile; }
271 void addVolatile() { Mask |= Volatile; }
272
273 bool hasRestrict() const { return Mask & Restrict; }
274 bool hasOnlyRestrict() const { return Mask == Restrict; }
275 void removeRestrict() { Mask &= ~Restrict; }
276 void addRestrict() { Mask |= Restrict; }
277
278 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
279 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
280 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
281
282 void setCVRQualifiers(unsigned mask) {
283 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "clang/include/clang/AST/Type.h", 283, __extension__ __PRETTY_FUNCTION__
))
;
284 Mask = (Mask & ~CVRMask) | mask;
285 }
286 void removeCVRQualifiers(unsigned mask) {
287 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "clang/include/clang/AST/Type.h", 287, __extension__ __PRETTY_FUNCTION__
))
;
288 Mask &= ~mask;
289 }
290 void removeCVRQualifiers() {
291 removeCVRQualifiers(CVRMask);
292 }
293 void addCVRQualifiers(unsigned mask) {
294 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "clang/include/clang/AST/Type.h", 294, __extension__ __PRETTY_FUNCTION__
))
;
295 Mask |= mask;
296 }
297 void addCVRUQualifiers(unsigned mask) {
298 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")(static_cast <bool> (!(mask & ~CVRMask & ~UMask
) && "bitmask contains non-CVRU bits") ? void (0) : __assert_fail
("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "clang/include/clang/AST/Type.h", 298, __extension__ __PRETTY_FUNCTION__
))
;
299 Mask |= mask;
300 }
301
302 bool hasUnaligned() const { return Mask & UMask; }
303 void setUnaligned(bool flag) {
304 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
305 }
306 void removeUnaligned() { Mask &= ~UMask; }
307 void addUnaligned() { Mask |= UMask; }
308
309 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
310 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
311 void setObjCGCAttr(GC type) {
312 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
313 }
314 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
315 void addObjCGCAttr(GC type) {
316 assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail (
"type", "clang/include/clang/AST/Type.h", 316, __extension__ __PRETTY_FUNCTION__
))
;
317 setObjCGCAttr(type);
318 }
319 Qualifiers withoutObjCGCAttr() const {
320 Qualifiers qs = *this;
321 qs.removeObjCGCAttr();
322 return qs;
323 }
324 Qualifiers withoutObjCLifetime() const {
325 Qualifiers qs = *this;
326 qs.removeObjCLifetime();
327 return qs;
328 }
329 Qualifiers withoutAddressSpace() const {
330 Qualifiers qs = *this;
331 qs.removeAddressSpace();
332 return qs;
333 }
334
335 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
336 ObjCLifetime getObjCLifetime() const {
337 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
338 }
339 void setObjCLifetime(ObjCLifetime type) {
340 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
341 }
342 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
343 void addObjCLifetime(ObjCLifetime type) {
344 assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail (
"type", "clang/include/clang/AST/Type.h", 344, __extension__ __PRETTY_FUNCTION__
))
;
345 assert(!hasObjCLifetime())(static_cast <bool> (!hasObjCLifetime()) ? void (0) : __assert_fail
("!hasObjCLifetime()", "clang/include/clang/AST/Type.h", 345
, __extension__ __PRETTY_FUNCTION__))
;
346 Mask |= (type << LifetimeShift);
347 }
348
349 /// True if the lifetime is neither None or ExplicitNone.
350 bool hasNonTrivialObjCLifetime() const {
351 ObjCLifetime lifetime = getObjCLifetime();
352 return (lifetime > OCL_ExplicitNone);
353 }
354
355 /// True if the lifetime is either strong or weak.
356 bool hasStrongOrWeakObjCLifetime() const {
357 ObjCLifetime lifetime = getObjCLifetime();
358 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
359 }
360
361 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
362 LangAS getAddressSpace() const {
363 return static_cast<LangAS>(Mask >> AddressSpaceShift);
364 }
365 bool hasTargetSpecificAddressSpace() const {
366 return isTargetAddressSpace(getAddressSpace());
367 }
368 /// Get the address space attribute value to be printed by diagnostics.
369 unsigned getAddressSpaceAttributePrintValue() const {
370 auto Addr = getAddressSpace();
371 // This function is not supposed to be used with language specific
372 // address spaces. If that happens, the diagnostic message should consider
373 // printing the QualType instead of the address space value.
374 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())(static_cast <bool> (Addr == LangAS::Default || hasTargetSpecificAddressSpace
()) ? void (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "clang/include/clang/AST/Type.h", 374, __extension__ __PRETTY_FUNCTION__
))
;
375 if (Addr != LangAS::Default)
376 return toTargetAddressSpace(Addr);
377 // TODO: The diagnostic messages where Addr may be 0 should be fixed
378 // since it cannot differentiate the situation where 0 denotes the default
379 // address space or user specified __attribute__((address_space(0))).
380 return 0;
381 }
382 void setAddressSpace(LangAS space) {
383 assert((unsigned)space <= MaxAddressSpace)(static_cast <bool> ((unsigned)space <= MaxAddressSpace
) ? void (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "clang/include/clang/AST/Type.h", 383, __extension__ __PRETTY_FUNCTION__
))
;
384 Mask = (Mask & ~AddressSpaceMask)
385 | (((uint32_t) space) << AddressSpaceShift);
386 }
387 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
388 void addAddressSpace(LangAS space) {
389 assert(space != LangAS::Default)(static_cast <bool> (space != LangAS::Default) ? void (
0) : __assert_fail ("space != LangAS::Default", "clang/include/clang/AST/Type.h"
, 389, __extension__ __PRETTY_FUNCTION__))
;
390 setAddressSpace(space);
391 }
392
393 // Fast qualifiers are those that can be allocated directly
394 // on a QualType object.
395 bool hasFastQualifiers() const { return getFastQualifiers(); }
396 unsigned getFastQualifiers() const { return Mask & FastMask; }
397 void setFastQualifiers(unsigned mask) {
398 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "clang/include/clang/AST/Type.h", 398, __extension__ __PRETTY_FUNCTION__
))
;
399 Mask = (Mask & ~FastMask) | mask;
400 }
401 void removeFastQualifiers(unsigned mask) {
402 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "clang/include/clang/AST/Type.h", 402, __extension__ __PRETTY_FUNCTION__
))
;
403 Mask &= ~mask;
404 }
405 void removeFastQualifiers() {
406 removeFastQualifiers(FastMask);
407 }
408 void addFastQualifiers(unsigned mask) {
409 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "clang/include/clang/AST/Type.h", 409, __extension__ __PRETTY_FUNCTION__
))
;
410 Mask |= mask;
411 }
412
413 /// Return true if the set contains any qualifiers which require an ExtQuals
414 /// node to be allocated.
415 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
416 Qualifiers getNonFastQualifiers() const {
417 Qualifiers Quals = *this;
418 Quals.setFastQualifiers(0);
419 return Quals;
420 }
421
422 /// Return true if the set contains any qualifiers.
423 bool hasQualifiers() const { return Mask; }
424 bool empty() const { return !Mask; }
425
426 /// Add the qualifiers from the given set to this set.
427 void addQualifiers(Qualifiers Q) {
428 // If the other set doesn't have any non-boolean qualifiers, just
429 // bit-or it in.
430 if (!(Q.Mask & ~CVRMask))
431 Mask |= Q.Mask;
432 else {
433 Mask |= (Q.Mask & CVRMask);
434 if (Q.hasAddressSpace())
435 addAddressSpace(Q.getAddressSpace());
436 if (Q.hasObjCGCAttr())
437 addObjCGCAttr(Q.getObjCGCAttr());
438 if (Q.hasObjCLifetime())
439 addObjCLifetime(Q.getObjCLifetime());
440 }
441 }
442
443 /// Remove the qualifiers from the given set from this set.
444 void removeQualifiers(Qualifiers Q) {
445 // If the other set doesn't have any non-boolean qualifiers, just
446 // bit-and the inverse in.
447 if (!(Q.Mask & ~CVRMask))
448 Mask &= ~Q.Mask;
449 else {
450 Mask &= ~(Q.Mask & CVRMask);
451 if (getObjCGCAttr() == Q.getObjCGCAttr())
452 removeObjCGCAttr();
453 if (getObjCLifetime() == Q.getObjCLifetime())
454 removeObjCLifetime();
455 if (getAddressSpace() == Q.getAddressSpace())
456 removeAddressSpace();
457 }
458 }
459
460 /// Add the qualifiers from the given set to this set, given that
461 /// they don't conflict.
462 void addConsistentQualifiers(Qualifiers qs) {
463 assert(getAddressSpace() == qs.getAddressSpace() ||(static_cast <bool> (getAddressSpace() == qs.getAddressSpace
() || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0)
: __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "clang/include/clang/AST/Type.h", 464, __extension__ __PRETTY_FUNCTION__
))
464 !hasAddressSpace() || !qs.hasAddressSpace())(static_cast <bool> (getAddressSpace() == qs.getAddressSpace
() || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0)
: __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "clang/include/clang/AST/Type.h", 464, __extension__ __PRETTY_FUNCTION__
))
;
465 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr
() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "clang/include/clang/AST/Type.h", 466, __extension__ __PRETTY_FUNCTION__
))
466 !hasObjCGCAttr() || !qs.hasObjCGCAttr())(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr
() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "clang/include/clang/AST/Type.h", 466, __extension__ __PRETTY_FUNCTION__
))
;
467 assert(getObjCLifetime() == qs.getObjCLifetime() ||(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime
() || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0)
: __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "clang/include/clang/AST/Type.h", 468, __extension__ __PRETTY_FUNCTION__
))
468 !hasObjCLifetime() || !qs.hasObjCLifetime())(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime
() || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0)
: __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "clang/include/clang/AST/Type.h", 468, __extension__ __PRETTY_FUNCTION__
))
;
469 Mask |= qs.Mask;
470 }
471
472 /// Returns true if address space A is equal to or a superset of B.
473 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
474 /// overlapping address spaces.
475 /// CL1.1 or CL1.2:
476 /// every address space is a superset of itself.
477 /// CL2.0 adds:
478 /// __generic is a superset of any address space except for __constant.
479 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
480 // Address spaces must match exactly.
481 return A == B ||
482 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
483 // for __constant can be used as __generic.
484 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
485 // We also define global_device and global_host address spaces,
486 // to distinguish global pointers allocated on host from pointers
487 // allocated on device, which are a subset of __global.
488 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
489 B == LangAS::opencl_global_host)) ||
490 (A == LangAS::sycl_global && (B == LangAS::sycl_global_device ||
491 B == LangAS::sycl_global_host)) ||
492 // Consider pointer size address spaces to be equivalent to default.
493 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
494 (isPtrSizeAddressSpace(B) || B == LangAS::Default)) ||
495 // Default is a superset of SYCL address spaces.
496 (A == LangAS::Default &&
497 (B == LangAS::sycl_private || B == LangAS::sycl_local ||
498 B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
499 B == LangAS::sycl_global_host)) ||
500 // In HIP device compilation, any cuda address space is allowed
501 // to implicitly cast into the default address space.
502 (A == LangAS::Default &&
503 (B == LangAS::cuda_constant || B == LangAS::cuda_device ||
504 B == LangAS::cuda_shared));
505 }
506
507 /// Returns true if the address space in these qualifiers is equal to or
508 /// a superset of the address space in the argument qualifiers.
509 bool isAddressSpaceSupersetOf(Qualifiers other) const {
510 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
511 }
512
513 /// Determines if these qualifiers compatibly include another set.
514 /// Generally this answers the question of whether an object with the other
515 /// qualifiers can be safely used as an object with these qualifiers.
516 bool compatiblyIncludes(Qualifiers other) const {
517 return isAddressSpaceSupersetOf(other) &&
518 // ObjC GC qualifiers can match, be added, or be removed, but can't
519 // be changed.
520 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
521 !other.hasObjCGCAttr()) &&
522 // ObjC lifetime qualifiers must match exactly.
523 getObjCLifetime() == other.getObjCLifetime() &&
524 // CVR qualifiers may subset.
525 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
526 // U qualifier may superset.
527 (!other.hasUnaligned() || hasUnaligned());
528 }
529
530 /// Determines if these qualifiers compatibly include another set of
531 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
532 ///
533 /// One set of Objective-C lifetime qualifiers compatibly includes the other
534 /// if the lifetime qualifiers match, or if both are non-__weak and the
535 /// including set also contains the 'const' qualifier, or both are non-__weak
536 /// and one is None (which can only happen in non-ARC modes).
537 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
538 if (getObjCLifetime() == other.getObjCLifetime())
539 return true;
540
541 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
542 return false;
543
544 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
545 return true;
546
547 return hasConst();
548 }
549
550 /// Determine whether this set of qualifiers is a strict superset of
551 /// another set of qualifiers, not considering qualifier compatibility.
552 bool isStrictSupersetOf(Qualifiers Other) const;
553
554 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
555 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
556
557 explicit operator bool() const { return hasQualifiers(); }
558
559 Qualifiers &operator+=(Qualifiers R) {
560 addQualifiers(R);
561 return *this;
562 }
563
564 // Union two qualifier sets. If an enumerated qualifier appears
565 // in both sets, use the one from the right.
566 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
567 L += R;
568 return L;
569 }
570
571 Qualifiers &operator-=(Qualifiers R) {
572 removeQualifiers(R);
573 return *this;
574 }
575
576 /// Compute the difference between two qualifier sets.
577 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
578 L -= R;
579 return L;
580 }
581
582 std::string getAsString() const;
583 std::string getAsString(const PrintingPolicy &Policy) const;
584
585 static std::string getAddrSpaceAsString(LangAS AS);
586
587 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
588 void print(raw_ostream &OS, const PrintingPolicy &Policy,
589 bool appendSpaceIfNonEmpty = false) const;
590
591 void Profile(llvm::FoldingSetNodeID &ID) const {
592 ID.AddInteger(Mask);
593 }
594
595private:
596 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
597 // |C R V|U|GCAttr|Lifetime|AddressSpace|
598 uint32_t Mask = 0;
599
600 static const uint32_t UMask = 0x8;
601 static const uint32_t UShift = 3;
602 static const uint32_t GCAttrMask = 0x30;
603 static const uint32_t GCAttrShift = 4;
604 static const uint32_t LifetimeMask = 0x1C0;
605 static const uint32_t LifetimeShift = 6;
606 static const uint32_t AddressSpaceMask =
607 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
608 static const uint32_t AddressSpaceShift = 9;
609};
610
611/// A std::pair-like structure for storing a qualified type split
612/// into its local qualifiers and its locally-unqualified type.
613struct SplitQualType {
614 /// The locally-unqualified type.
615 const Type *Ty = nullptr;
616
617 /// The local qualifiers.
618 Qualifiers Quals;
619
620 SplitQualType() = default;
621 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
622
623 SplitQualType getSingleStepDesugaredType() const; // end of this file
624
625 // Make std::tie work.
626 std::pair<const Type *,Qualifiers> asPair() const {
627 return std::pair<const Type *, Qualifiers>(Ty, Quals);
628 }
629
630 friend bool operator==(SplitQualType a, SplitQualType b) {
631 return a.Ty == b.Ty && a.Quals == b.Quals;
632 }
633 friend bool operator!=(SplitQualType a, SplitQualType b) {
634 return a.Ty != b.Ty || a.Quals != b.Quals;
635 }
636};
637
638/// The kind of type we are substituting Objective-C type arguments into.
639///
640/// The kind of substitution affects the replacement of type parameters when
641/// no concrete type information is provided, e.g., when dealing with an
642/// unspecialized type.
643enum class ObjCSubstitutionContext {
644 /// An ordinary type.
645 Ordinary,
646
647 /// The result type of a method or function.
648 Result,
649
650 /// The parameter type of a method or function.
651 Parameter,
652
653 /// The type of a property.
654 Property,
655
656 /// The superclass of a type.
657 Superclass,
658};
659
660/// A (possibly-)qualified type.
661///
662/// For efficiency, we don't store CV-qualified types as nodes on their
663/// own: instead each reference to a type stores the qualifiers. This
664/// greatly reduces the number of nodes we need to allocate for types (for
665/// example we only need one for 'int', 'const int', 'volatile int',
666/// 'const volatile int', etc).
667///
668/// As an added efficiency bonus, instead of making this a pair, we
669/// just store the two bits we care about in the low bits of the
670/// pointer. To handle the packing/unpacking, we make QualType be a
671/// simple wrapper class that acts like a smart pointer. A third bit
672/// indicates whether there are extended qualifiers present, in which
673/// case the pointer points to a special structure.
674class QualType {
675 friend class QualifierCollector;
676
677 // Thankfully, these are efficiently composable.
678 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
679 Qualifiers::FastWidth> Value;
680
681 const ExtQuals *getExtQualsUnsafe() const {
682 return Value.getPointer().get<const ExtQuals*>();
683 }
684
685 const Type *getTypePtrUnsafe() const {
686 return Value.getPointer().get<const Type*>();
687 }
688
689 const ExtQualsTypeCommonBase *getCommonPtr() const {
690 assert(!isNull() && "Cannot retrieve a NULL type pointer")(static_cast <bool> (!isNull() && "Cannot retrieve a NULL type pointer"
) ? void (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "clang/include/clang/AST/Type.h", 690, __extension__ __PRETTY_FUNCTION__
))
;
691 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
692 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
693 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
694 }
695
696public:
697 QualType() = default;
698 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
699 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
700
701 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
702 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
703
704 /// Retrieves a pointer to the underlying (unqualified) type.
705 ///
706 /// This function requires that the type not be NULL. If the type might be
707 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
708 const Type *getTypePtr() const;
709
710 const Type *getTypePtrOrNull() const;
711
712 /// Retrieves a pointer to the name of the base type.
713 const IdentifierInfo *getBaseTypeIdentifier() const;
714
715 /// Divides a QualType into its unqualified type and a set of local
716 /// qualifiers.
717 SplitQualType split() const;
718
719 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
720
721 static QualType getFromOpaquePtr(const void *Ptr) {
722 QualType T;
723 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
724 return T;
725 }
726
727 const Type &operator*() const {
728 return *getTypePtr();
729 }
730
731 const Type *operator->() const {
732 return getTypePtr();
733 }
734
735 bool isCanonical() const;
736 bool isCanonicalAsParam() const;
737
738 /// Return true if this QualType doesn't point to a type yet.
739 bool isNull() const {
740 return Value.getPointer().isNull();
741 }
742
743 /// Determine whether this particular QualType instance has the
744 /// "const" qualifier set, without looking through typedefs that may have
745 /// added "const" at a different level.
746 bool isLocalConstQualified() const {
747 return (getLocalFastQualifiers() & Qualifiers::Const);
748 }
749
750 /// Determine whether this type is const-qualified.
751 bool isConstQualified() const;
752
753 /// Determine whether this particular QualType instance has the
754 /// "restrict" qualifier set, without looking through typedefs that may have
755 /// added "restrict" at a different level.
756 bool isLocalRestrictQualified() const {
757 return (getLocalFastQualifiers() & Qualifiers::Restrict);
758 }
759
760 /// Determine whether this type is restrict-qualified.
761 bool isRestrictQualified() const;
762
763 /// Determine whether this particular QualType instance has the
764 /// "volatile" qualifier set, without looking through typedefs that may have
765 /// added "volatile" at a different level.
766 bool isLocalVolatileQualified() const {
767 return (getLocalFastQualifiers() & Qualifiers::Volatile);
768 }
769
770 /// Determine whether this type is volatile-qualified.
771 bool isVolatileQualified() const;
772
773 /// Determine whether this particular QualType instance has any
774 /// qualifiers, without looking through any typedefs that might add
775 /// qualifiers at a different level.
776 bool hasLocalQualifiers() const {
777 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
778 }
779
780 /// Determine whether this type has any qualifiers.
781 bool hasQualifiers() const;
782
783 /// Determine whether this particular QualType instance has any
784 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
785 /// instance.
786 bool hasLocalNonFastQualifiers() const {
787 return Value.getPointer().is<const ExtQuals*>();
788 }
789
790 /// Retrieve the set of qualifiers local to this particular QualType
791 /// instance, not including any qualifiers acquired through typedefs or
792 /// other sugar.
793 Qualifiers getLocalQualifiers() const;
794
795 /// Retrieve the set of qualifiers applied to this type.
796 Qualifiers getQualifiers() const;
797
798 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
799 /// local to this particular QualType instance, not including any qualifiers
800 /// acquired through typedefs or other sugar.
801 unsigned getLocalCVRQualifiers() const {
802 return getLocalFastQualifiers();
803 }
804
805 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
806 /// applied to this type.
807 unsigned getCVRQualifiers() const;
808
809 bool isConstant(const ASTContext& Ctx) const {
810 return QualType::isConstant(*this, Ctx);
811 }
812
813 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
814 bool isPODType(const ASTContext &Context) const;
815
816 /// Return true if this is a POD type according to the rules of the C++98
817 /// standard, regardless of the current compilation's language.
818 bool isCXX98PODType(const ASTContext &Context) const;
819
820 /// Return true if this is a POD type according to the more relaxed rules
821 /// of the C++11 standard, regardless of the current compilation's language.
822 /// (C++0x [basic.types]p9). Note that, unlike
823 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
824 bool isCXX11PODType(const ASTContext &Context) const;
825
826 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
827 bool isTrivialType(const ASTContext &Context) const;
828
829 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
830 bool isTriviallyCopyableType(const ASTContext &Context) const;
831
832
833 /// Returns true if it is a class and it might be dynamic.
834 bool mayBeDynamicClass() const;
835
836 /// Returns true if it is not a class or if the class might not be dynamic.
837 bool mayBeNotDynamicClass() const;
838
839 // Don't promise in the API that anything besides 'const' can be
840 // easily added.
841
842 /// Add the `const` type qualifier to this QualType.
843 void addConst() {
844 addFastQualifiers(Qualifiers::Const);
845 }
846 QualType withConst() const {
847 return withFastQualifiers(Qualifiers::Const);
848 }
849
850 /// Add the `volatile` type qualifier to this QualType.
851 void addVolatile() {
852 addFastQualifiers(Qualifiers::Volatile);
853 }
854 QualType withVolatile() const {
855 return withFastQualifiers(Qualifiers::Volatile);
856 }
857
858 /// Add the `restrict` qualifier to this QualType.
859 void addRestrict() {
860 addFastQualifiers(Qualifiers::Restrict);
861 }
862 QualType withRestrict() const {
863 return withFastQualifiers(Qualifiers::Restrict);
864 }
865
866 QualType withCVRQualifiers(unsigned CVR) const {
867 return withFastQualifiers(CVR);
868 }
869
870 void addFastQualifiers(unsigned TQs) {
871 assert(!(TQs & ~Qualifiers::FastMask)(static_cast <bool> (!(TQs & ~Qualifiers::FastMask)
&& "non-fast qualifier bits set in mask!") ? void (0
) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "clang/include/clang/AST/Type.h", 872, __extension__ __PRETTY_FUNCTION__
))
872 && "non-fast qualifier bits set in mask!")(static_cast <bool> (!(TQs & ~Qualifiers::FastMask)
&& "non-fast qualifier bits set in mask!") ? void (0
) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "clang/include/clang/AST/Type.h", 872, __extension__ __PRETTY_FUNCTION__
))
;
873 Value.setInt(Value.getInt() | TQs);
874 }
875
876 void removeLocalConst();
877 void removeLocalVolatile();
878 void removeLocalRestrict();
879 void removeLocalCVRQualifiers(unsigned Mask);
880
881 void removeLocalFastQualifiers() { Value.setInt(0); }
882 void removeLocalFastQualifiers(unsigned Mask) {
883 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")(static_cast <bool> (!(Mask & ~Qualifiers::FastMask
) && "mask has non-fast qualifiers") ? void (0) : __assert_fail
("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "clang/include/clang/AST/Type.h", 883, __extension__ __PRETTY_FUNCTION__
))
;
884 Value.setInt(Value.getInt() & ~Mask);
885 }
886
887 // Creates a type with the given qualifiers in addition to any
888 // qualifiers already on this type.
889 QualType withFastQualifiers(unsigned TQs) const {
890 QualType T = *this;
891 T.addFastQualifiers(TQs);
892 return T;
893 }
894
895 // Creates a type with exactly the given fast qualifiers, removing
896 // any existing fast qualifiers.
897 QualType withExactLocalFastQualifiers(unsigned TQs) const {
898 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
899 }
900
901 // Removes fast qualifiers, but leaves any extended qualifiers in place.
902 QualType withoutLocalFastQualifiers() const {
903 QualType T = *this;
904 T.removeLocalFastQualifiers();
905 return T;
906 }
907
908 QualType getCanonicalType() const;
909
910 /// Return this type with all of the instance-specific qualifiers
911 /// removed, but without removing any qualifiers that may have been applied
912 /// through typedefs.
913 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
914
915 /// Retrieve the unqualified variant of the given type,
916 /// removing as little sugar as possible.
917 ///
918 /// This routine looks through various kinds of sugar to find the
919 /// least-desugared type that is unqualified. For example, given:
920 ///
921 /// \code
922 /// typedef int Integer;
923 /// typedef const Integer CInteger;
924 /// typedef CInteger DifferenceType;
925 /// \endcode
926 ///
927 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
928 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
929 ///
930 /// The resulting type might still be qualified if it's sugar for an array
931 /// type. To strip qualifiers even from within a sugared array type, use
932 /// ASTContext::getUnqualifiedArrayType.
933 inline QualType getUnqualifiedType() const;
934
935 /// Retrieve the unqualified variant of the given type, removing as little
936 /// sugar as possible.
937 ///
938 /// Like getUnqualifiedType(), but also returns the set of
939 /// qualifiers that were built up.
940 ///
941 /// The resulting type might still be qualified if it's sugar for an array
942 /// type. To strip qualifiers even from within a sugared array type, use
943 /// ASTContext::getUnqualifiedArrayType.
944 inline SplitQualType getSplitUnqualifiedType() const;
945
946 /// Determine whether this type is more qualified than the other
947 /// given type, requiring exact equality for non-CVR qualifiers.
948 bool isMoreQualifiedThan(QualType Other) const;
949
950 /// Determine whether this type is at least as qualified as the other
951 /// given type, requiring exact equality for non-CVR qualifiers.
952 bool isAtLeastAsQualifiedAs(QualType Other) const;
953
954 QualType getNonReferenceType() const;
955
956 /// Determine the type of a (typically non-lvalue) expression with the
957 /// specified result type.
958 ///
959 /// This routine should be used for expressions for which the return type is
960 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
961 /// an lvalue. It removes a top-level reference (since there are no
962 /// expressions of reference type) and deletes top-level cvr-qualifiers
963 /// from non-class types (in C++) or all types (in C).
964 QualType getNonLValueExprType(const ASTContext &Context) const;
965
966 /// Remove an outer pack expansion type (if any) from this type. Used as part
967 /// of converting the type of a declaration to the type of an expression that
968 /// references that expression. It's meaningless for an expression to have a
969 /// pack expansion type.
970 QualType getNonPackExpansionType() const;
971
972 /// Return the specified type with any "sugar" removed from
973 /// the type. This takes off typedefs, typeof's etc. If the outer level of
974 /// the type is already concrete, it returns it unmodified. This is similar
975 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
976 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
977 /// concrete.
978 ///
979 /// Qualifiers are left in place.
980 QualType getDesugaredType(const ASTContext &Context) const {
981 return getDesugaredType(*this, Context);
982 }
983
984 SplitQualType getSplitDesugaredType() const {
985 return getSplitDesugaredType(*this);
986 }
987
988 /// Return the specified type with one level of "sugar" removed from
989 /// the type.
990 ///
991 /// This routine takes off the first typedef, typeof, etc. If the outer level
992 /// of the type is already concrete, it returns it unmodified.
993 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
994 return getSingleStepDesugaredTypeImpl(*this, Context);
995 }
996
997 /// Returns the specified type after dropping any
998 /// outer-level parentheses.
999 QualType IgnoreParens() const {
1000 if (isa<ParenType>(*this))
1001 return QualType::IgnoreParens(*this);
1002 return *this;
1003 }
1004
1005 /// Indicate whether the specified types and qualifiers are identical.
1006 friend bool operator==(const QualType &LHS, const QualType &RHS) {
1007 return LHS.Value == RHS.Value;
1008 }
1009 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1010 return LHS.Value != RHS.Value;
1011 }
1012 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1013 return LHS.Value < RHS.Value;
1014 }
1015
1016 static std::string getAsString(SplitQualType split,
1017 const PrintingPolicy &Policy) {
1018 return getAsString(split.Ty, split.Quals, Policy);
1019 }
1020 static std::string getAsString(const Type *ty, Qualifiers qs,
1021 const PrintingPolicy &Policy);
1022
1023 std::string getAsString() const;
1024 std::string getAsString(const PrintingPolicy &Policy) const;
1025
1026 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1027 const Twine &PlaceHolder = Twine(),
1028 unsigned Indentation = 0) const;
1029
1030 static void print(SplitQualType split, raw_ostream &OS,
1031 const PrintingPolicy &policy, const Twine &PlaceHolder,
1032 unsigned Indentation = 0) {
1033 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1034 }
1035
1036 static void print(const Type *ty, Qualifiers qs,
1037 raw_ostream &OS, const PrintingPolicy &policy,
1038 const Twine &PlaceHolder,
1039 unsigned Indentation = 0);
1040
1041 void getAsStringInternal(std::string &Str,
1042 const PrintingPolicy &Policy) const;
1043
1044 static void getAsStringInternal(SplitQualType split, std::string &out,
1045 const PrintingPolicy &policy) {
1046 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1047 }
1048
1049 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1050 std::string &out,
1051 const PrintingPolicy &policy);
1052
1053 class StreamedQualTypeHelper {
1054 const QualType &T;
1055 const PrintingPolicy &Policy;
1056 const Twine &PlaceHolder;
1057 unsigned Indentation;
1058
1059 public:
1060 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1061 const Twine &PlaceHolder, unsigned Indentation)
1062 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1063 Indentation(Indentation) {}
1064
1065 friend raw_ostream &operator<<(raw_ostream &OS,
1066 const StreamedQualTypeHelper &SQT) {
1067 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1068 return OS;
1069 }
1070 };
1071
1072 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1073 const Twine &PlaceHolder = Twine(),
1074 unsigned Indentation = 0) const {
1075 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1076 }
1077
1078 void dump(const char *s) const;
1079 void dump() const;
1080 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1081
1082 void Profile(llvm::FoldingSetNodeID &ID) const {
1083 ID.AddPointer(getAsOpaquePtr());
1084 }
1085
1086 /// Check if this type has any address space qualifier.
1087 inline bool hasAddressSpace() const;
1088
1089 /// Return the address space of this type.
1090 inline LangAS getAddressSpace() const;
1091
1092 /// Returns true if address space qualifiers overlap with T address space
1093 /// qualifiers.
1094 /// OpenCL C defines conversion rules for pointers to different address spaces
1095 /// and notion of overlapping address spaces.
1096 /// CL1.1 or CL1.2:
1097 /// address spaces overlap iff they are they same.
1098 /// OpenCL C v2.0 s6.5.5 adds:
1099 /// __generic overlaps with any address space except for __constant.
1100 bool isAddressSpaceOverlapping(QualType T) const {
1101 Qualifiers Q = getQualifiers();
1102 Qualifiers TQ = T.getQualifiers();
1103 // Address spaces overlap if at least one of them is a superset of another
1104 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1105 }
1106
1107 /// Returns gc attribute of this type.
1108 inline Qualifiers::GC getObjCGCAttr() const;
1109
1110 /// true when Type is objc's weak.
1111 bool isObjCGCWeak() const {
1112 return getObjCGCAttr() == Qualifiers::Weak;
1113 }
1114
1115 /// true when Type is objc's strong.
1116 bool isObjCGCStrong() const {
1117 return getObjCGCAttr() == Qualifiers::Strong;
1118 }
1119
1120 /// Returns lifetime attribute of this type.
1121 Qualifiers::ObjCLifetime getObjCLifetime() const {
1122 return getQualifiers().getObjCLifetime();
1123 }
1124
1125 bool hasNonTrivialObjCLifetime() const {
1126 return getQualifiers().hasNonTrivialObjCLifetime();
1127 }
1128
1129 bool hasStrongOrWeakObjCLifetime() const {
1130 return getQualifiers().hasStrongOrWeakObjCLifetime();
1131 }
1132
1133 // true when Type is objc's weak and weak is enabled but ARC isn't.
1134 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1135
1136 enum PrimitiveDefaultInitializeKind {
1137 /// The type does not fall into any of the following categories. Note that
1138 /// this case is zero-valued so that values of this enum can be used as a
1139 /// boolean condition for non-triviality.
1140 PDIK_Trivial,
1141
1142 /// The type is an Objective-C retainable pointer type that is qualified
1143 /// with the ARC __strong qualifier.
1144 PDIK_ARCStrong,
1145
1146 /// The type is an Objective-C retainable pointer type that is qualified
1147 /// with the ARC __weak qualifier.
1148 PDIK_ARCWeak,
1149
1150 /// The type is a struct containing a field whose type is not PCK_Trivial.
1151 PDIK_Struct
1152 };
1153
1154 /// Functions to query basic properties of non-trivial C struct types.
1155
1156 /// Check if this is a non-trivial type that would cause a C struct
1157 /// transitively containing this type to be non-trivial to default initialize
1158 /// and return the kind.
1159 PrimitiveDefaultInitializeKind
1160 isNonTrivialToPrimitiveDefaultInitialize() const;
1161
1162 enum PrimitiveCopyKind {
1163 /// The type does not fall into any of the following categories. Note that
1164 /// this case is zero-valued so that values of this enum can be used as a
1165 /// boolean condition for non-triviality.
1166 PCK_Trivial,
1167
1168 /// The type would be trivial except that it is volatile-qualified. Types
1169 /// that fall into one of the other non-trivial cases may additionally be
1170 /// volatile-qualified.
1171 PCK_VolatileTrivial,
1172
1173 /// The type is an Objective-C retainable pointer type that is qualified
1174 /// with the ARC __strong qualifier.
1175 PCK_ARCStrong,
1176
1177 /// The type is an Objective-C retainable pointer type that is qualified
1178 /// with the ARC __weak qualifier.
1179 PCK_ARCWeak,
1180
1181 /// The type is a struct containing a field whose type is neither
1182 /// PCK_Trivial nor PCK_VolatileTrivial.
1183 /// Note that a C++ struct type does not necessarily match this; C++ copying
1184 /// semantics are too complex to express here, in part because they depend
1185 /// on the exact constructor or assignment operator that is chosen by
1186 /// overload resolution to do the copy.
1187 PCK_Struct
1188 };
1189
1190 /// Check if this is a non-trivial type that would cause a C struct
1191 /// transitively containing this type to be non-trivial to copy and return the
1192 /// kind.
1193 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1194
1195 /// Check if this is a non-trivial type that would cause a C struct
1196 /// transitively containing this type to be non-trivial to destructively
1197 /// move and return the kind. Destructive move in this context is a C++-style
1198 /// move in which the source object is placed in a valid but unspecified state
1199 /// after it is moved, as opposed to a truly destructive move in which the
1200 /// source object is placed in an uninitialized state.
1201 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1202
1203 enum DestructionKind {
1204 DK_none,
1205 DK_cxx_destructor,
1206 DK_objc_strong_lifetime,
1207 DK_objc_weak_lifetime,
1208 DK_nontrivial_c_struct
1209 };
1210
1211 /// Returns a nonzero value if objects of this type require
1212 /// non-trivial work to clean up after. Non-zero because it's
1213 /// conceivable that qualifiers (objc_gc(weak)?) could make
1214 /// something require destruction.
1215 DestructionKind isDestructedType() const {
1216 return isDestructedTypeImpl(*this);
1217 }
1218
1219 /// Check if this is or contains a C union that is non-trivial to
1220 /// default-initialize, which is a union that has a member that is non-trivial
1221 /// to default-initialize. If this returns true,
1222 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1223 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1224
1225 /// Check if this is or contains a C union that is non-trivial to destruct,
1226 /// which is a union that has a member that is non-trivial to destruct. If
1227 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1228 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1229
1230 /// Check if this is or contains a C union that is non-trivial to copy, which
1231 /// is a union that has a member that is non-trivial to copy. If this returns
1232 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1233 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1234
1235 /// Determine whether expressions of the given type are forbidden
1236 /// from being lvalues in C.
1237 ///
1238 /// The expression types that are forbidden to be lvalues are:
1239 /// - 'void', but not qualified void
1240 /// - function types
1241 ///
1242 /// The exact rule here is C99 6.3.2.1:
1243 /// An lvalue is an expression with an object type or an incomplete
1244 /// type other than void.
1245 bool isCForbiddenLValueType() const;
1246
1247 /// Substitute type arguments for the Objective-C type parameters used in the
1248 /// subject type.
1249 ///
1250 /// \param ctx ASTContext in which the type exists.
1251 ///
1252 /// \param typeArgs The type arguments that will be substituted for the
1253 /// Objective-C type parameters in the subject type, which are generally
1254 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1255 /// parameters will be replaced with their bounds or id/Class, as appropriate
1256 /// for the context.
1257 ///
1258 /// \param context The context in which the subject type was written.
1259 ///
1260 /// \returns the resulting type.
1261 QualType substObjCTypeArgs(ASTContext &ctx,
1262 ArrayRef<QualType> typeArgs,
1263 ObjCSubstitutionContext context) const;
1264
1265 /// Substitute type arguments from an object type for the Objective-C type
1266 /// parameters used in the subject type.
1267 ///
1268 /// This operation combines the computation of type arguments for
1269 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1270 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1271 /// callers that need to perform a single substitution in isolation.
1272 ///
1273 /// \param objectType The type of the object whose member type we're
1274 /// substituting into. For example, this might be the receiver of a message
1275 /// or the base of a property access.
1276 ///
1277 /// \param dc The declaration context from which the subject type was
1278 /// retrieved, which indicates (for example) which type parameters should
1279 /// be substituted.
1280 ///
1281 /// \param context The context in which the subject type was written.
1282 ///
1283 /// \returns the subject type after replacing all of the Objective-C type
1284 /// parameters with their corresponding arguments.
1285 QualType substObjCMemberType(QualType objectType,
1286 const DeclContext *dc,
1287 ObjCSubstitutionContext context) const;
1288
1289 /// Strip Objective-C "__kindof" types from the given type.
1290 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1291
1292 /// Remove all qualifiers including _Atomic.
1293 QualType getAtomicUnqualifiedType() const;
1294
1295private:
1296 // These methods are implemented in a separate translation unit;
1297 // "static"-ize them to avoid creating temporary QualTypes in the
1298 // caller.
1299 static bool isConstant(QualType T, const ASTContext& Ctx);
1300 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1301 static SplitQualType getSplitDesugaredType(QualType T);
1302 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1303 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1304 const ASTContext &C);
1305 static QualType IgnoreParens(QualType T);
1306 static DestructionKind isDestructedTypeImpl(QualType type);
1307
1308 /// Check if \param RD is or contains a non-trivial C union.
1309 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1310 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1311 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1312};
1313
1314} // namespace clang
1315
1316namespace llvm {
1317
1318/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1319/// to a specific Type class.
1320template<> struct simplify_type< ::clang::QualType> {
1321 using SimpleType = const ::clang::Type *;
1322
1323 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1324 return Val.getTypePtr();
1325 }
1326};
1327
1328// Teach SmallPtrSet that QualType is "basically a pointer".
1329template<>
1330struct PointerLikeTypeTraits<clang::QualType> {
1331 static inline void *getAsVoidPointer(clang::QualType P) {
1332 return P.getAsOpaquePtr();
1333 }
1334
1335 static inline clang::QualType getFromVoidPointer(void *P) {
1336 return clang::QualType::getFromOpaquePtr(P);
1337 }
1338
1339 // Various qualifiers go in low bits.
1340 static constexpr int NumLowBitsAvailable = 0;
1341};
1342
1343} // namespace llvm
1344
1345namespace clang {
1346
1347/// Base class that is common to both the \c ExtQuals and \c Type
1348/// classes, which allows \c QualType to access the common fields between the
1349/// two.
1350class ExtQualsTypeCommonBase {
1351 friend class ExtQuals;
1352 friend class QualType;
1353 friend class Type;
1354
1355 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1356 /// a self-referential pointer (for \c Type).
1357 ///
1358 /// This pointer allows an efficient mapping from a QualType to its
1359 /// underlying type pointer.
1360 const Type *const BaseType;
1361
1362 /// The canonical type of this type. A QualType.
1363 QualType CanonicalType;
1364
1365 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1366 : BaseType(baseType), CanonicalType(canon) {}
1367};
1368
1369/// We can encode up to four bits in the low bits of a
1370/// type pointer, but there are many more type qualifiers that we want
1371/// to be able to apply to an arbitrary type. Therefore we have this
1372/// struct, intended to be heap-allocated and used by QualType to
1373/// store qualifiers.
1374///
1375/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1376/// in three low bits on the QualType pointer; a fourth bit records whether
1377/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1378/// Objective-C GC attributes) are much more rare.
1379class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1380 // NOTE: changing the fast qualifiers should be straightforward as
1381 // long as you don't make 'const' non-fast.
1382 // 1. Qualifiers:
1383 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1384 // Fast qualifiers must occupy the low-order bits.
1385 // b) Update Qualifiers::FastWidth and FastMask.
1386 // 2. QualType:
1387 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1388 // b) Update remove{Volatile,Restrict}, defined near the end of
1389 // this header.
1390 // 3. ASTContext:
1391 // a) Update get{Volatile,Restrict}Type.
1392
1393 /// The immutable set of qualifiers applied by this node. Always contains
1394 /// extended qualifiers.
1395 Qualifiers Quals;
1396
1397 ExtQuals *this_() { return this; }
1398
1399public:
1400 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1401 : ExtQualsTypeCommonBase(baseType,
1402 canon.isNull() ? QualType(this_(), 0) : canon),
1403 Quals(quals) {
1404 assert(Quals.hasNonFastQualifiers()(static_cast <bool> (Quals.hasNonFastQualifiers() &&
"ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail
("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1405, __extension__ __PRETTY_FUNCTION__
))
1405 && "ExtQuals created with no fast qualifiers")(static_cast <bool> (Quals.hasNonFastQualifiers() &&
"ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail
("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1405, __extension__ __PRETTY_FUNCTION__
))
;
1406 assert(!Quals.hasFastQualifiers()(static_cast <bool> (!Quals.hasFastQualifiers() &&
"ExtQuals created with fast qualifiers") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1407, __extension__ __PRETTY_FUNCTION__
))
1407 && "ExtQuals created with fast qualifiers")(static_cast <bool> (!Quals.hasFastQualifiers() &&
"ExtQuals created with fast qualifiers") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1407, __extension__ __PRETTY_FUNCTION__
))
;
1408 }
1409
1410 Qualifiers getQualifiers() const { return Quals; }
1411
1412 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1413 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1414
1415 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1416 Qualifiers::ObjCLifetime getObjCLifetime() const {
1417 return Quals.getObjCLifetime();
1418 }
1419
1420 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1421 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1422
1423 const Type *getBaseType() const { return BaseType; }
1424
1425public:
1426 void Profile(llvm::FoldingSetNodeID &ID) const {
1427 Profile(ID, getBaseType(), Quals);
1428 }
1429
1430 static void Profile(llvm::FoldingSetNodeID &ID,
1431 const Type *BaseType,
1432 Qualifiers Quals) {
1433 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")(static_cast <bool> (!Quals.hasFastQualifiers() &&
"fast qualifiers in ExtQuals hash!") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "clang/include/clang/AST/Type.h", 1433, __extension__ __PRETTY_FUNCTION__
))
;
1434 ID.AddPointer(BaseType);
1435 Quals.Profile(ID);
1436 }
1437};
1438
1439/// The kind of C++11 ref-qualifier associated with a function type.
1440/// This determines whether a member function's "this" object can be an
1441/// lvalue, rvalue, or neither.
1442enum RefQualifierKind {
1443 /// No ref-qualifier was provided.
1444 RQ_None = 0,
1445
1446 /// An lvalue ref-qualifier was provided (\c &).
1447 RQ_LValue,
1448
1449 /// An rvalue ref-qualifier was provided (\c &&).
1450 RQ_RValue
1451};
1452
1453/// Which keyword(s) were used to create an AutoType.
1454enum class AutoTypeKeyword {
1455 /// auto
1456 Auto,
1457
1458 /// decltype(auto)
1459 DecltypeAuto,
1460
1461 /// __auto_type (GNU extension)
1462 GNUAutoType
1463};
1464
1465/// The base class of the type hierarchy.
1466///
1467/// A central concept with types is that each type always has a canonical
1468/// type. A canonical type is the type with any typedef names stripped out
1469/// of it or the types it references. For example, consider:
1470///
1471/// typedef int foo;
1472/// typedef foo* bar;
1473/// 'int *' 'foo *' 'bar'
1474///
1475/// There will be a Type object created for 'int'. Since int is canonical, its
1476/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1477/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1478/// there is a PointerType that represents 'int*', which, like 'int', is
1479/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1480/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1481/// is also 'int*'.
1482///
1483/// Non-canonical types are useful for emitting diagnostics, without losing
1484/// information about typedefs being used. Canonical types are useful for type
1485/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1486/// about whether something has a particular form (e.g. is a function type),
1487/// because they implicitly, recursively, strip all typedefs out of a type.
1488///
1489/// Types, once created, are immutable.
1490///
1491class alignas(8) Type : public ExtQualsTypeCommonBase {
1492public:
1493 enum TypeClass {
1494#define TYPE(Class, Base) Class,
1495#define LAST_TYPE(Class) TypeLast = Class
1496#define ABSTRACT_TYPE(Class, Base)
1497#include "clang/AST/TypeNodes.inc"
1498 };
1499
1500private:
1501 /// Bitfields required by the Type class.
1502 class TypeBitfields {
1503 friend class Type;
1504 template <class T> friend class TypePropertyCache;
1505
1506 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1507 unsigned TC : 8;
1508
1509 /// Store information on the type dependency.
1510 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1511
1512 /// True if the cache (i.e. the bitfields here starting with
1513 /// 'Cache') is valid.
1514 mutable unsigned CacheValid : 1;
1515
1516 /// Linkage of this type.
1517 mutable unsigned CachedLinkage : 3;
1518
1519 /// Whether this type involves and local or unnamed types.
1520 mutable unsigned CachedLocalOrUnnamed : 1;
1521
1522 /// Whether this type comes from an AST file.
1523 mutable unsigned FromAST : 1;
1524
1525 bool isCacheValid() const {
1526 return CacheValid;
1527 }
1528
1529 Linkage getLinkage() const {
1530 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache"
) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "clang/include/clang/AST/Type.h", 1530, __extension__ __PRETTY_FUNCTION__
))
;
1531 return static_cast<Linkage>(CachedLinkage);
1532 }
1533
1534 bool hasLocalOrUnnamedType() const {
1535 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache"
) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "clang/include/clang/AST/Type.h", 1535, __extension__ __PRETTY_FUNCTION__
))
;
1536 return CachedLocalOrUnnamed;
1537 }
1538 };
1539 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1540
1541protected:
1542 // These classes allow subclasses to somewhat cleanly pack bitfields
1543 // into Type.
1544
1545 class ArrayTypeBitfields {
1546 friend class ArrayType;
1547
1548 unsigned : NumTypeBits;
1549
1550 /// CVR qualifiers from declarations like
1551 /// 'int X[static restrict 4]'. For function parameters only.
1552 unsigned IndexTypeQuals : 3;
1553
1554 /// Storage class qualifiers from declarations like
1555 /// 'int X[static restrict 4]'. For function parameters only.
1556 /// Actually an ArrayType::ArraySizeModifier.
1557 unsigned SizeModifier : 3;
1558 };
1559
1560 class ConstantArrayTypeBitfields {
1561 friend class ConstantArrayType;
1562
1563 unsigned : NumTypeBits + 3 + 3;
1564
1565 /// Whether we have a stored size expression.
1566 unsigned HasStoredSizeExpr : 1;
1567 };
1568
1569 class BuiltinTypeBitfields {
1570 friend class BuiltinType;
1571
1572 unsigned : NumTypeBits;
1573
1574 /// The kind (BuiltinType::Kind) of builtin type this is.
1575 unsigned Kind : 8;
1576 };
1577
1578 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1579 /// Only common bits are stored here. Additional uncommon bits are stored
1580 /// in a trailing object after FunctionProtoType.
1581 class FunctionTypeBitfields {
1582 friend class FunctionProtoType;
1583 friend class FunctionType;
1584
1585 unsigned : NumTypeBits;
1586
1587 /// Extra information which affects how the function is called, like
1588 /// regparm and the calling convention.
1589 unsigned ExtInfo : 13;
1590
1591 /// The ref-qualifier associated with a \c FunctionProtoType.
1592 ///
1593 /// This is a value of type \c RefQualifierKind.
1594 unsigned RefQualifier : 2;
1595
1596 /// Used only by FunctionProtoType, put here to pack with the
1597 /// other bitfields.
1598 /// The qualifiers are part of FunctionProtoType because...
1599 ///
1600 /// C++ 8.3.5p4: The return type, the parameter type list and the
1601 /// cv-qualifier-seq, [...], are part of the function type.
1602 unsigned FastTypeQuals : Qualifiers::FastWidth;
1603 /// Whether this function has extended Qualifiers.
1604 unsigned HasExtQuals : 1;
1605
1606 /// The number of parameters this function has, not counting '...'.
1607 /// According to [implimits] 8 bits should be enough here but this is
1608 /// somewhat easy to exceed with metaprogramming and so we would like to
1609 /// keep NumParams as wide as reasonably possible.
1610 unsigned NumParams : 16;
1611
1612 /// The type of exception specification this function has.
1613 unsigned ExceptionSpecType : 4;
1614
1615 /// Whether this function has extended parameter information.
1616 unsigned HasExtParameterInfos : 1;
1617
1618 /// Whether the function is variadic.
1619 unsigned Variadic : 1;
1620
1621 /// Whether this function has a trailing return type.
1622 unsigned HasTrailingReturn : 1;
1623 };
1624
1625 class ObjCObjectTypeBitfields {
1626 friend class ObjCObjectType;
1627
1628 unsigned : NumTypeBits;
1629
1630 /// The number of type arguments stored directly on this object type.
1631 unsigned NumTypeArgs : 7;
1632
1633 /// The number of protocols stored directly on this object type.
1634 unsigned NumProtocols : 6;
1635
1636 /// Whether this is a "kindof" type.
1637 unsigned IsKindOf : 1;
1638 };
1639
1640 class ReferenceTypeBitfields {
1641 friend class ReferenceType;
1642
1643 unsigned : NumTypeBits;
1644
1645 /// True if the type was originally spelled with an lvalue sigil.
1646 /// This is never true of rvalue references but can also be false
1647 /// on lvalue references because of C++0x [dcl.typedef]p9,
1648 /// as follows:
1649 ///
1650 /// typedef int &ref; // lvalue, spelled lvalue
1651 /// typedef int &&rvref; // rvalue
1652 /// ref &a; // lvalue, inner ref, spelled lvalue
1653 /// ref &&a; // lvalue, inner ref
1654 /// rvref &a; // lvalue, inner ref, spelled lvalue
1655 /// rvref &&a; // rvalue, inner ref
1656 unsigned SpelledAsLValue : 1;
1657
1658 /// True if the inner type is a reference type. This only happens
1659 /// in non-canonical forms.
1660 unsigned InnerRef : 1;
1661 };
1662
1663 class TypeWithKeywordBitfields {
1664 friend class TypeWithKeyword;
1665
1666 unsigned : NumTypeBits;
1667
1668 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1669 unsigned Keyword : 8;
1670 };
1671
1672 enum { NumTypeWithKeywordBits = 8 };
1673
1674 class ElaboratedTypeBitfields {
1675 friend class ElaboratedType;
1676
1677 unsigned : NumTypeBits;
1678 unsigned : NumTypeWithKeywordBits;
1679
1680 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1681 unsigned HasOwnedTagDecl : 1;
1682 };
1683
1684 class VectorTypeBitfields {
1685 friend class VectorType;
1686 friend class DependentVectorType;
1687
1688 unsigned : NumTypeBits;
1689
1690 /// The kind of vector, either a generic vector type or some
1691 /// target-specific vector type such as for AltiVec or Neon.
1692 unsigned VecKind : 3;
1693 /// The number of elements in the vector.
1694 uint32_t NumElements;
1695 };
1696
1697 class AttributedTypeBitfields {
1698 friend class AttributedType;
1699
1700 unsigned : NumTypeBits;
1701
1702 /// An AttributedType::Kind
1703 unsigned AttrKind : 32 - NumTypeBits;
1704 };
1705
1706 class AutoTypeBitfields {
1707 friend class AutoType;
1708
1709 unsigned : NumTypeBits;
1710
1711 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1712 /// or '__auto_type'? AutoTypeKeyword value.
1713 unsigned Keyword : 2;
1714
1715 /// The number of template arguments in the type-constraints, which is
1716 /// expected to be able to hold at least 1024 according to [implimits].
1717 /// However as this limit is somewhat easy to hit with template
1718 /// metaprogramming we'd prefer to keep it as large as possible.
1719 /// At the moment it has been left as a non-bitfield since this type
1720 /// safely fits in 64 bits as an unsigned, so there is no reason to
1721 /// introduce the performance impact of a bitfield.
1722 unsigned NumArgs;
1723 };
1724
1725 class SubstTemplateTypeParmPackTypeBitfields {
1726 friend class SubstTemplateTypeParmPackType;
1727
1728 unsigned : NumTypeBits;
1729
1730 /// The number of template arguments in \c Arguments, which is
1731 /// expected to be able to hold at least 1024 according to [implimits].
1732 /// However as this limit is somewhat easy to hit with template
1733 /// metaprogramming we'd prefer to keep it as large as possible.
1734 /// At the moment it has been left as a non-bitfield since this type
1735 /// safely fits in 64 bits as an unsigned, so there is no reason to
1736 /// introduce the performance impact of a bitfield.
1737 unsigned NumArgs;
1738 };
1739
1740 class TemplateSpecializationTypeBitfields {
1741 friend class TemplateSpecializationType;
1742
1743 unsigned : NumTypeBits;
1744
1745 /// Whether this template specialization type is a substituted type alias.
1746 unsigned TypeAlias : 1;
1747
1748 /// The number of template arguments named in this class template
1749 /// specialization, which is expected to be able to hold at least 1024
1750 /// according to [implimits]. However, as this limit is somewhat easy to
1751 /// hit with template metaprogramming we'd prefer to keep it as large
1752 /// as possible. At the moment it has been left as a non-bitfield since
1753 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1754 /// to introduce the performance impact of a bitfield.
1755 unsigned NumArgs;
1756 };
1757
1758 class DependentTemplateSpecializationTypeBitfields {
1759 friend class DependentTemplateSpecializationType;
1760
1761 unsigned : NumTypeBits;
1762 unsigned : NumTypeWithKeywordBits;
1763
1764 /// The number of template arguments named in this class template
1765 /// specialization, which is expected to be able to hold at least 1024
1766 /// according to [implimits]. However, as this limit is somewhat easy to
1767 /// hit with template metaprogramming we'd prefer to keep it as large
1768 /// as possible. At the moment it has been left as a non-bitfield since
1769 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1770 /// to introduce the performance impact of a bitfield.
1771 unsigned NumArgs;
1772 };
1773
1774 class PackExpansionTypeBitfields {
1775 friend class PackExpansionType;
1776
1777 unsigned : NumTypeBits;
1778
1779 /// The number of expansions that this pack expansion will
1780 /// generate when substituted (+1), which is expected to be able to
1781 /// hold at least 1024 according to [implimits]. However, as this limit
1782 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1783 /// keep it as large as possible. At the moment it has been left as a
1784 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1785 /// there is no reason to introduce the performance impact of a bitfield.
1786 ///
1787 /// This field will only have a non-zero value when some of the parameter
1788 /// packs that occur within the pattern have been substituted but others
1789 /// have not.
1790 unsigned NumExpansions;
1791 };
1792
1793 union {
1794 TypeBitfields TypeBits;
1795 ArrayTypeBitfields ArrayTypeBits;
1796 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1797 AttributedTypeBitfields AttributedTypeBits;
1798 AutoTypeBitfields AutoTypeBits;
1799 BuiltinTypeBitfields BuiltinTypeBits;
1800 FunctionTypeBitfields FunctionTypeBits;
1801 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1802 ReferenceTypeBitfields ReferenceTypeBits;
1803 TypeWithKeywordBitfields TypeWithKeywordBits;
1804 ElaboratedTypeBitfields ElaboratedTypeBits;
1805 VectorTypeBitfields VectorTypeBits;
1806 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1807 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1808 DependentTemplateSpecializationTypeBitfields
1809 DependentTemplateSpecializationTypeBits;
1810 PackExpansionTypeBitfields PackExpansionTypeBits;
1811 };
1812
1813private:
1814 template <class T> friend class TypePropertyCache;
1815
1816 /// Set whether this type comes from an AST file.
1817 void setFromAST(bool V = true) const {
1818 TypeBits.FromAST = V;
1819 }
1820
1821protected:
1822 friend class ASTContext;
1823
1824 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1825 : ExtQualsTypeCommonBase(this,
1826 canon.isNull() ? QualType(this_(), 0) : canon) {
1827 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1828 "changing bitfields changed sizeof(Type)!");
1829 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1830 "Insufficient alignment!");
1831 TypeBits.TC = tc;
1832 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1833 TypeBits.CacheValid = false;
1834 TypeBits.CachedLocalOrUnnamed = false;
1835 TypeBits.CachedLinkage = NoLinkage;
1836 TypeBits.FromAST = false;
1837 }
1838
1839 // silence VC++ warning C4355: 'this' : used in base member initializer list
1840 Type *this_() { return this; }
1841
1842 void setDependence(TypeDependence D) {
1843 TypeBits.Dependence = static_cast<unsigned>(D);
1844 }
1845
1846 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1847
1848public:
1849 friend class ASTReader;
1850 friend class ASTWriter;
1851 template <class T> friend class serialization::AbstractTypeReader;
1852 template <class T> friend class serialization::AbstractTypeWriter;
1853
1854 Type(const Type &) = delete;
1855 Type(Type &&) = delete;
1856 Type &operator=(const Type &) = delete;
1857 Type &operator=(Type &&) = delete;
1858
1859 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1860
1861 /// Whether this type comes from an AST file.
1862 bool isFromAST() const { return TypeBits.FromAST; }
1863
1864 /// Whether this type is or contains an unexpanded parameter
1865 /// pack, used to support C++0x variadic templates.
1866 ///
1867 /// A type that contains a parameter pack shall be expanded by the
1868 /// ellipsis operator at some point. For example, the typedef in the
1869 /// following example contains an unexpanded parameter pack 'T':
1870 ///
1871 /// \code
1872 /// template<typename ...T>
1873 /// struct X {
1874 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1875 /// };
1876 /// \endcode
1877 ///
1878 /// Note that this routine does not specify which
1879 bool containsUnexpandedParameterPack() const {
1880 return getDependence() & TypeDependence::UnexpandedPack;
1881 }
1882
1883 /// Determines if this type would be canonical if it had no further
1884 /// qualification.
1885 bool isCanonicalUnqualified() const {
1886 return CanonicalType == QualType(this, 0);
1887 }
1888
1889 /// Pull a single level of sugar off of this locally-unqualified type.
1890 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1891 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1892 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1893
1894 /// As an extension, we classify types as one of "sized" or "sizeless";
1895 /// every type is one or the other. Standard types are all sized;
1896 /// sizeless types are purely an extension.
1897 ///
1898 /// Sizeless types contain data with no specified size, alignment,
1899 /// or layout.
1900 bool isSizelessType() const;
1901 bool isSizelessBuiltinType() const;
1902
1903 /// Determines if this is a sizeless type supported by the
1904 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1905 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1906 bool isVLSTBuiltinType() const;
1907
1908 /// Returns the representative type for the element of an SVE builtin type.
1909 /// This is used to represent fixed-length SVE vectors created with the
1910 /// 'arm_sve_vector_bits' type attribute as VectorType.
1911 QualType getSveEltType(const ASTContext &Ctx) const;
1912
1913 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1914 /// object types, function types, and incomplete types.
1915
1916 /// Return true if this is an incomplete type.
1917 /// A type that can describe objects, but which lacks information needed to
1918 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1919 /// routine will need to determine if the size is actually required.
1920 ///
1921 /// Def If non-null, and the type refers to some kind of declaration
1922 /// that can be completed (such as a C struct, C++ class, or Objective-C
1923 /// class), will be set to the declaration.
1924 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1925
1926 /// Return true if this is an incomplete or object
1927 /// type, in other words, not a function type.
1928 bool isIncompleteOrObjectType() const {
1929 return !isFunctionType();
1930 }
1931
1932 /// Determine whether this type is an object type.
1933 bool isObjectType() const {
1934 // C++ [basic.types]p8:
1935 // An object type is a (possibly cv-qualified) type that is not a
1936 // function type, not a reference type, and not a void type.
1937 return !isReferenceType() && !isFunctionType() && !isVoidType();
1938 }
1939
1940 /// Return true if this is a literal type
1941 /// (C++11 [basic.types]p10)
1942 bool isLiteralType(const ASTContext &Ctx) const;
1943
1944 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1945 bool isStructuralType() const;
1946
1947 /// Test if this type is a standard-layout type.
1948 /// (C++0x [basic.type]p9)
1949 bool isStandardLayoutType() const;
1950
1951 /// Helper methods to distinguish type categories. All type predicates
1952 /// operate on the canonical type, ignoring typedefs and qualifiers.
1953
1954 /// Returns true if the type is a builtin type.
1955 bool isBuiltinType() const;
1956
1957 /// Test for a particular builtin type.
1958 bool isSpecificBuiltinType(unsigned K) const;
1959
1960 /// Test for a type which does not represent an actual type-system type but
1961 /// is instead used as a placeholder for various convenient purposes within
1962 /// Clang. All such types are BuiltinTypes.
1963 bool isPlaceholderType() const;
1964 const BuiltinType *getAsPlaceholderType() const;
1965
1966 /// Test for a specific placeholder type.
1967 bool isSpecificPlaceholderType(unsigned K) const;
1968
1969 /// Test for a placeholder type other than Overload; see
1970 /// BuiltinType::isNonOverloadPlaceholderType.
1971 bool isNonOverloadPlaceholderType() const;
1972
1973 /// isIntegerType() does *not* include complex integers (a GCC extension).
1974 /// isComplexIntegerType() can be used to test for complex integers.
1975 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1976 bool isEnumeralType() const;
1977
1978 /// Determine whether this type is a scoped enumeration type.
1979 bool isScopedEnumeralType() const;
1980 bool isBooleanType() const;
1981 bool isCharType() const;
1982 bool isWideCharType() const;
1983 bool isChar8Type() const;
1984 bool isChar16Type() const;
1985 bool isChar32Type() const;
1986 bool isAnyCharacterType() const;
1987 bool isIntegralType(const ASTContext &Ctx) const;
1988
1989 /// Determine whether this type is an integral or enumeration type.
1990 bool isIntegralOrEnumerationType() const;
1991
1992 /// Determine whether this type is an integral or unscoped enumeration type.
1993 bool isIntegralOrUnscopedEnumerationType() const;
1994 bool isUnscopedEnumerationType() const;
1995
1996 /// Floating point categories.
1997 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1998 /// isComplexType() does *not* include complex integers (a GCC extension).
1999 /// isComplexIntegerType() can be used to test for complex integers.
2000 bool isComplexType() const; // C99 6.2.5p11 (complex)
2001 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2002 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2003 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2004 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2005 bool isBFloat16Type() const;
2006 bool isFloat128Type() const;
2007 bool isIbm128Type() const;
2008 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2009 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2010 bool isVoidType() const; // C99 6.2.5p19
2011 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2012 bool isAggregateType() const;
2013 bool isFundamentalType() const;
2014 bool isCompoundType() const;
2015
2016 // Type Predicates: Check to see if this type is structurally the specified
2017 // type, ignoring typedefs and qualifiers.
2018 bool isFunctionType() const;
2019 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2020 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2021 bool isPointerType() const;
2022 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2023 bool isBlockPointerType() const;
2024 bool isVoidPointerType() const;
2025 bool isReferenceType() const;
2026 bool isLValueReferenceType() const;
2027 bool isRValueReferenceType() const;
2028 bool isObjectPointerType() const;
2029 bool isFunctionPointerType() const;
2030 bool isFunctionReferenceType() const;
2031 bool isMemberPointerType() const;
2032 bool isMemberFunctionPointerType() const;
2033 bool isMemberDataPointerType() const;
2034 bool isArrayType() const;
2035 bool isConstantArrayType() const;
2036 bool isIncompleteArrayType() const;
2037 bool isVariableArrayType() const;
2038 bool isDependentSizedArrayType() const;
2039 bool isRecordType() const;
2040 bool isClassType() const;
2041 bool isStructureType() const;
2042 bool isObjCBoxableRecordType() const;
2043 bool isInterfaceType() const;
2044 bool isStructureOrClassType() const;
2045 bool isUnionType() const;
2046 bool isComplexIntegerType() const; // GCC _Complex integer type.
2047 bool isVectorType() const; // GCC vector type.
2048 bool isExtVectorType() const; // Extended vector type.
2049 bool isMatrixType() const; // Matrix type.
2050 bool isConstantMatrixType() const; // Constant matrix type.
2051 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2052 bool isObjCObjectPointerType() const; // pointer to ObjC object
2053 bool isObjCRetainableType() const; // ObjC object or block pointer
2054 bool isObjCLifetimeType() const; // (array of)* retainable type
2055 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2056 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2057 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2058 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2059 // for the common case.
2060 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2061 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2062 bool isObjCQualifiedIdType() const; // id<foo>
2063 bool isObjCQualifiedClassType() const; // Class<foo>
2064 bool isObjCObjectOrInterfaceType() const;
2065 bool isObjCIdType() const; // id
2066 bool isDecltypeType() const;
2067 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2068 /// qualifier?
2069 ///
2070 /// This approximates the answer to the following question: if this
2071 /// translation unit were compiled in ARC, would this type be qualified
2072 /// with __unsafe_unretained?
2073 bool isObjCInertUnsafeUnretainedType() const {
2074 return hasAttr(attr::ObjCInertUnsafeUnretained);
2075 }
2076
2077 /// Whether the type is Objective-C 'id' or a __kindof type of an
2078 /// object type, e.g., __kindof NSView * or __kindof id
2079 /// <NSCopying>.
2080 ///
2081 /// \param bound Will be set to the bound on non-id subtype types,
2082 /// which will be (possibly specialized) Objective-C class type, or
2083 /// null for 'id.
2084 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2085 const ObjCObjectType *&bound) const;
2086
2087 bool isObjCClassType() const; // Class
2088
2089 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2090 /// Class type, e.g., __kindof Class <NSCopying>.
2091 ///
2092 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2093 /// here because Objective-C's type system cannot express "a class
2094 /// object for a subclass of NSFoo".
2095 bool isObjCClassOrClassKindOfType() const;
2096
2097 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2098 bool isObjCSelType() const; // Class
2099 bool isObjCBuiltinType() const; // 'id' or 'Class'
2100 bool isObjCARCBridgableType() const;
2101 bool isCARCBridgableType() const;
2102 bool isTemplateTypeParmType() const; // C++ template type parameter
2103 bool isNullPtrType() const; // C++11 std::nullptr_t
2104 bool isNothrowT() const; // C++ std::nothrow_t
2105 bool isAlignValT() const; // C++17 std::align_val_t
2106 bool isStdByteType() const; // C++17 std::byte
2107 bool isAtomicType() const; // C11 _Atomic()
2108 bool isUndeducedAutoType() const; // C++11 auto or
2109 // C++14 decltype(auto)
2110 bool isTypedefNameType() const; // typedef or alias template
2111
2112#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2113 bool is##Id##Type() const;
2114#include "clang/Basic/OpenCLImageTypes.def"
2115
2116 bool isImageType() const; // Any OpenCL image type
2117
2118 bool isSamplerT() const; // OpenCL sampler_t
2119 bool isEventT() const; // OpenCL event_t
2120 bool isClkEventT() const; // OpenCL clk_event_t
2121 bool isQueueT() const; // OpenCL queue_t
2122 bool isReserveIDT() const; // OpenCL reserve_id_t
2123
2124#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2125 bool is##Id##Type() const;
2126#include "clang/Basic/OpenCLExtensionTypes.def"
2127 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2128 bool isOCLIntelSubgroupAVCType() const;
2129 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2130
2131 bool isPipeType() const; // OpenCL pipe type
2132 bool isBitIntType() const; // Bit-precise integer type
2133 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2134
2135 /// Determines if this type, which must satisfy
2136 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2137 /// than implicitly __strong.
2138 bool isObjCARCImplicitlyUnretainedType() const;
2139
2140 /// Check if the type is the CUDA device builtin surface type.
2141 bool isCUDADeviceBuiltinSurfaceType() const;
2142 /// Check if the type is the CUDA device builtin texture type.
2143 bool isCUDADeviceBuiltinTextureType() const;
2144
2145 /// Return the implicit lifetime for this type, which must not be dependent.
2146 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2147
2148 enum ScalarTypeKind {
2149 STK_CPointer,
2150 STK_BlockPointer,
2151 STK_ObjCObjectPointer,
2152 STK_MemberPointer,
2153 STK_Bool,
2154 STK_Integral,
2155 STK_Floating,
2156 STK_IntegralComplex,
2157 STK_FloatingComplex,
2158 STK_FixedPoint
2159 };
2160
2161 /// Given that this is a scalar type, classify it.
2162 ScalarTypeKind getScalarTypeKind() const;
2163
2164 TypeDependence getDependence() const {
2165 return static_cast<TypeDependence>(TypeBits.Dependence);
2166 }
2167
2168 /// Whether this type is an error type.
2169 bool containsErrors() const {
2170 return getDependence() & TypeDependence::Error;
2171 }
2172
2173 /// Whether this type is a dependent type, meaning that its definition
2174 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2175 bool isDependentType() const {
2176 return getDependence() & TypeDependence::Dependent;
2177 }
2178
2179 /// Determine whether this type is an instantiation-dependent type,
2180 /// meaning that the type involves a template parameter (even if the
2181 /// definition does not actually depend on the type substituted for that
2182 /// template parameter).
2183 bool isInstantiationDependentType() const {
2184 return getDependence() & TypeDependence::Instantiation;
2185 }
2186
2187 /// Determine whether this type is an undeduced type, meaning that
2188 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2189 /// deduced.
2190 bool isUndeducedType() const;
2191
2192 /// Whether this type is a variably-modified type (C99 6.7.5).
2193 bool isVariablyModifiedType() const {
2194 return getDependence() & TypeDependence::VariablyModified;
2195 }
2196
2197 /// Whether this type involves a variable-length array type
2198 /// with a definite size.
2199 bool hasSizedVLAType() const;
2200
2201 /// Whether this type is or contains a local or unnamed type.
2202 bool hasUnnamedOrLocalType() const;
2203
2204 bool isOverloadableType() const;
2205
2206 /// Determine wither this type is a C++ elaborated-type-specifier.
2207 bool isElaboratedTypeSpecifier() const;
2208
2209 bool canDecayToPointerType() const;
2210
2211 /// Whether this type is represented natively as a pointer. This includes
2212 /// pointers, references, block pointers, and Objective-C interface,
2213 /// qualified id, and qualified interface types, as well as nullptr_t.
2214 bool hasPointerRepresentation() const;
2215
2216 /// Whether this type can represent an objective pointer type for the
2217 /// purpose of GC'ability
2218 bool hasObjCPointerRepresentation() const;
2219
2220 /// Determine whether this type has an integer representation
2221 /// of some sort, e.g., it is an integer type or a vector.
2222 bool hasIntegerRepresentation() const;
2223
2224 /// Determine whether this type has an signed integer representation
2225 /// of some sort, e.g., it is an signed integer type or a vector.
2226 bool hasSignedIntegerRepresentation() const;
2227
2228 /// Determine whether this type has an unsigned integer representation
2229 /// of some sort, e.g., it is an unsigned integer type or a vector.
2230 bool hasUnsignedIntegerRepresentation() const;
2231
2232 /// Determine whether this type has a floating-point representation
2233 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2234 bool hasFloatingRepresentation() const;
2235
2236 // Type Checking Functions: Check to see if this type is structurally the
2237 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2238 // the best type we can.
2239 const RecordType *getAsStructureType() const;
2240 /// NOTE: getAs*ArrayType are methods on ASTContext.
2241 const RecordType *getAsUnionType() const;
2242 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2243 const ObjCObjectType *getAsObjCInterfaceType() const;
2244
2245 // The following is a convenience method that returns an ObjCObjectPointerType
2246 // for object declared using an interface.
2247 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2248 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2249 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2250 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2251
2252 /// Retrieves the CXXRecordDecl that this type refers to, either
2253 /// because the type is a RecordType or because it is the injected-class-name
2254 /// type of a class template or class template partial specialization.
2255 CXXRecordDecl *getAsCXXRecordDecl() const;
2256
2257 /// Retrieves the RecordDecl this type refers to.
2258 RecordDecl *getAsRecordDecl() const;
2259
2260 /// Retrieves the TagDecl that this type refers to, either
2261 /// because the type is a TagType or because it is the injected-class-name
2262 /// type of a class template or class template partial specialization.
2263 TagDecl *getAsTagDecl() const;
2264
2265 /// If this is a pointer or reference to a RecordType, return the
2266 /// CXXRecordDecl that the type refers to.
2267 ///
2268 /// If this is not a pointer or reference, or the type being pointed to does
2269 /// not refer to a CXXRecordDecl, returns NULL.
2270 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2271
2272 /// Get the DeducedType whose type will be deduced for a variable with
2273 /// an initializer of this type. This looks through declarators like pointer
2274 /// types, but not through decltype or typedefs.
2275 DeducedType *getContainedDeducedType() const;
2276
2277 /// Get the AutoType whose type will be deduced for a variable with
2278 /// an initializer of this type. This looks through declarators like pointer
2279 /// types, but not through decltype or typedefs.
2280 AutoType *getContainedAutoType() const {
2281 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2282 }
2283
2284 /// Determine whether this type was written with a leading 'auto'
2285 /// corresponding to a trailing return type (possibly for a nested
2286 /// function type within a pointer to function type or similar).
2287 bool hasAutoForTrailingReturnType() const;
2288
2289 /// Member-template getAs<specific type>'. Look through sugar for
2290 /// an instance of \<specific type>. This scheme will eventually
2291 /// replace the specific getAsXXXX methods above.
2292 ///
2293 /// There are some specializations of this member template listed
2294 /// immediately following this class.
2295 template <typename T> const T *getAs() const;
2296
2297 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2298 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2299 /// This is used when you need to walk over sugar nodes that represent some
2300 /// kind of type adjustment from a type that was written as a \<specific type>
2301 /// to another type that is still canonically a \<specific type>.
2302 template <typename T> const T *getAsAdjusted() const;
2303
2304 /// A variant of getAs<> for array types which silently discards
2305 /// qualifiers from the outermost type.
2306 const ArrayType *getAsArrayTypeUnsafe() const;
2307
2308 /// Member-template castAs<specific type>. Look through sugar for
2309 /// the underlying instance of \<specific type>.
2310 ///
2311 /// This method has the same relationship to getAs<T> as cast<T> has
2312 /// to dyn_cast<T>; which is to say, the underlying type *must*
2313 /// have the intended type, and this method will never return null.
2314 template <typename T> const T *castAs() const;
2315
2316 /// A variant of castAs<> for array type which silently discards
2317 /// qualifiers from the outermost type.
2318 const ArrayType *castAsArrayTypeUnsafe() const;
2319
2320 /// Determine whether this type had the specified attribute applied to it
2321 /// (looking through top-level type sugar).
2322 bool hasAttr(attr::Kind AK) const;
2323
2324 /// Get the base element type of this type, potentially discarding type
2325 /// qualifiers. This should never be used when type qualifiers
2326 /// are meaningful.
2327 const Type *getBaseElementTypeUnsafe() const;
2328
2329 /// If this is an array type, return the element type of the array,
2330 /// potentially with type qualifiers missing.
2331 /// This should never be used when type qualifiers are meaningful.
2332 const Type *getArrayElementTypeNoTypeQual() const;
2333
2334 /// If this is a pointer type, return the pointee type.
2335 /// If this is an array type, return the array element type.
2336 /// This should never be used when type qualifiers are meaningful.
2337 const Type *getPointeeOrArrayElementType() const;
2338
2339 /// If this is a pointer, ObjC object pointer, or block
2340 /// pointer, this returns the respective pointee.
2341 QualType getPointeeType() const;
2342
2343 /// Return the specified type with any "sugar" removed from the type,
2344 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2345 const Type *getUnqualifiedDesugaredType() const;
2346
2347 /// More type predicates useful for type checking/promotion
2348 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2349
2350 /// Return true if this is an integer type that is
2351 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2352 /// or an enum decl which has a signed representation.
2353 bool isSignedIntegerType() const;
2354
2355 /// Return true if this is an integer type that is
2356 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2357 /// or an enum decl which has an unsigned representation.
2358 bool isUnsignedIntegerType() const;
2359
2360 /// Determines whether this is an integer type that is signed or an
2361 /// enumeration types whose underlying type is a signed integer type.
2362 bool isSignedIntegerOrEnumerationType() const;
2363
2364 /// Determines whether this is an integer type that is unsigned or an
2365 /// enumeration types whose underlying type is a unsigned integer type.
2366 bool isUnsignedIntegerOrEnumerationType() const;
2367
2368 /// Return true if this is a fixed point type according to
2369 /// ISO/IEC JTC1 SC22 WG14 N1169.
2370 bool isFixedPointType() const;
2371
2372 /// Return true if this is a fixed point or integer type.
2373 bool isFixedPointOrIntegerType() const;
2374
2375 /// Return true if this is a saturated fixed point type according to
2376 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2377 bool isSaturatedFixedPointType() const;
2378
2379 /// Return true if this is a saturated fixed point type according to
2380 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2381 bool isUnsaturatedFixedPointType() const;
2382
2383 /// Return true if this is a fixed point type that is signed according
2384 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2385 bool isSignedFixedPointType() const;
2386
2387 /// Return true if this is a fixed point type that is unsigned according
2388 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2389 bool isUnsignedFixedPointType() const;
2390
2391 /// Return true if this is not a variable sized type,
2392 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2393 /// incomplete types.
2394 bool isConstantSizeType() const;
2395
2396 /// Returns true if this type can be represented by some
2397 /// set of type specifiers.
2398 bool isSpecifierType() const;
2399
2400 /// Determine the linkage of this type.
2401 Linkage getLinkage() const;
2402
2403 /// Determine the visibility of this type.
2404 Visibility getVisibility() const {
2405 return getLinkageAndVisibility().getVisibility();
2406 }
2407
2408 /// Return true if the visibility was explicitly set is the code.
2409 bool isVisibilityExplicit() const {
2410 return getLinkageAndVisibility().isVisibilityExplicit();
2411 }
2412
2413 /// Determine the linkage and visibility of this type.
2414 LinkageInfo getLinkageAndVisibility() const;
2415
2416 /// True if the computed linkage is valid. Used for consistency
2417 /// checking. Should always return true.
2418 bool isLinkageValid() const;
2419
2420 /// Determine the nullability of the given type.
2421 ///
2422 /// Note that nullability is only captured as sugar within the type
2423 /// system, not as part of the canonical type, so nullability will
2424 /// be lost by canonicalization and desugaring.
2425 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2426
2427 /// Determine whether the given type can have a nullability
2428 /// specifier applied to it, i.e., if it is any kind of pointer type.
2429 ///
2430 /// \param ResultIfUnknown The value to return if we don't yet know whether
2431 /// this type can have nullability because it is dependent.
2432 bool canHaveNullability(bool ResultIfUnknown = true) const;
2433
2434 /// Retrieve the set of substitutions required when accessing a member
2435 /// of the Objective-C receiver type that is declared in the given context.
2436 ///
2437 /// \c *this is the type of the object we're operating on, e.g., the
2438 /// receiver for a message send or the base of a property access, and is
2439 /// expected to be of some object or object pointer type.
2440 ///
2441 /// \param dc The declaration context for which we are building up a
2442 /// substitution mapping, which should be an Objective-C class, extension,
2443 /// category, or method within.
2444 ///
2445 /// \returns an array of type arguments that can be substituted for
2446 /// the type parameters of the given declaration context in any type described
2447 /// within that context, or an empty optional to indicate that no
2448 /// substitution is required.
2449 Optional<ArrayRef<QualType>>
2450 getObjCSubstitutions(const DeclContext *dc) const;
2451
2452 /// Determines if this is an ObjC interface type that may accept type
2453 /// parameters.
2454 bool acceptsObjCTypeParams() const;
2455
2456 const char *getTypeClassName() const;
2457
2458 QualType getCanonicalTypeInternal() const {
2459 return CanonicalType;
2460 }
2461
2462 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2463 void dump() const;
2464 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2465};
2466
2467/// This will check for a TypedefType by removing any existing sugar
2468/// until it reaches a TypedefType or a non-sugared type.
2469template <> const TypedefType *Type::getAs() const;
2470
2471/// This will check for a TemplateSpecializationType by removing any
2472/// existing sugar until it reaches a TemplateSpecializationType or a
2473/// non-sugared type.
2474template <> const TemplateSpecializationType *Type::getAs() const;
2475
2476/// This will check for an AttributedType by removing any existing sugar
2477/// until it reaches an AttributedType or a non-sugared type.
2478template <> const AttributedType *Type::getAs() const;
2479
2480// We can do canonical leaf types faster, because we don't have to
2481// worry about preserving child type decoration.
2482#define TYPE(Class, Base)
2483#define LEAF_TYPE(Class) \
2484template <> inline const Class##Type *Type::getAs() const { \
2485 return dyn_cast<Class##Type>(CanonicalType); \
2486} \
2487template <> inline const Class##Type *Type::castAs() const { \
2488 return cast<Class##Type>(CanonicalType); \
2489}
2490#include "clang/AST/TypeNodes.inc"
2491
2492/// This class is used for builtin types like 'int'. Builtin
2493/// types are always canonical and have a literal name field.
2494class BuiltinType : public Type {
2495public:
2496 enum Kind {
2497// OpenCL image types
2498#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2499#include "clang/Basic/OpenCLImageTypes.def"
2500// OpenCL extension types
2501#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2502#include "clang/Basic/OpenCLExtensionTypes.def"
2503// SVE Types
2504#define SVE_TYPE(Name, Id, SingletonId) Id,
2505#include "clang/Basic/AArch64SVEACLETypes.def"
2506// PPC MMA Types
2507#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2508#include "clang/Basic/PPCTypes.def"
2509// RVV Types
2510#define RVV_TYPE(Name, Id, SingletonId) Id,
2511#include "clang/Basic/RISCVVTypes.def"
2512// All other builtin types
2513#define BUILTIN_TYPE(Id, SingletonId) Id,
2514#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2515#include "clang/AST/BuiltinTypes.def"
2516 };
2517
2518private:
2519 friend class ASTContext; // ASTContext creates these.
2520
2521 BuiltinType(Kind K)
2522 : Type(Builtin, QualType(),
2523 K == Dependent ? TypeDependence::DependentInstantiation
2524 : TypeDependence::None) {
2525 BuiltinTypeBits.Kind = K;
2526 }
2527
2528public:
2529 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2530 StringRef getName(const PrintingPolicy &Policy) const;
2531
2532 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2533 // The StringRef is null-terminated.
2534 StringRef str = getName(Policy);
2535 assert(!str.empty() && str.data()[str.size()] == '\0')(static_cast <bool> (!str.empty() && str.data()
[str.size()] == '\0') ? void (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "clang/include/clang/AST/Type.h", 2535, __extension__ __PRETTY_FUNCTION__
))
;
2536 return str.data();
2537 }
2538
2539 bool isSugared() const { return false; }
2540 QualType desugar() const { return QualType(this, 0); }
2541
2542 bool isInteger() const {
2543 return getKind() >= Bool && getKind() <= Int128;
2544 }
2545
2546 bool isSignedInteger() const {
2547 return getKind() >= Char_S && getKind() <= Int128;
2548 }
2549
2550 bool isUnsignedInteger() const {