Bug Summary

File:clang/lib/Sema/SemaExpr.cpp
Warning:line 9077, column 29
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-08-06-171148-17323-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp

/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp

1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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 expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "UsedDeclVisitor.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprOpenMP.h"
27#include "clang/AST/RecursiveASTVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/Builtins.h"
30#include "clang/Basic/FixedPoint.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/LiteralSupport.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Sema/AnalysisBasedWarnings.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/DelayedDiagnostic.h"
39#include "clang/Sema/Designator.h"
40#include "clang/Sema/Initialization.h"
41#include "clang/Sema/Lookup.h"
42#include "clang/Sema/Overload.h"
43#include "clang/Sema/ParsedTemplate.h"
44#include "clang/Sema/Scope.h"
45#include "clang/Sema/ScopeInfo.h"
46#include "clang/Sema/SemaFixItUtils.h"
47#include "clang/Sema/SemaInternal.h"
48#include "clang/Sema/Template.h"
49#include "llvm/Support/ConvertUTF.h"
50#include "llvm/Support/SaveAndRestore.h"
51using namespace clang;
52using namespace sema;
53using llvm::RoundingMode;
54
55/// Determine whether the use of this declaration is valid, without
56/// emitting diagnostics.
57bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58 // See if this is an auto-typed variable whose initializer we are parsing.
59 if (ParsingInitForAutoVars.count(D))
60 return false;
61
62 // See if this is a deleted function.
63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64 if (FD->isDeleted())
65 return false;
66
67 // If the function has a deduced return type, and we can't deduce it,
68 // then we can't use it either.
69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71 return false;
72
73 // See if this is an aligned allocation/deallocation function that is
74 // unavailable.
75 if (TreatUnavailableAsInvalid &&
76 isUnavailableAlignedAllocationFunction(*FD))
77 return false;
78 }
79
80 // See if this function is unavailable.
81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83 return false;
84
85 return true;
86}
87
88static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89 // Warn if this is used but marked unused.
90 if (const auto *A = D->getAttr<UnusedAttr>()) {
91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92 // should diagnose them.
93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96 if (DC && !DC->hasAttr<UnusedAttr>())
97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
98 }
99 }
100}
101
102/// Emit a note explaining that this function is deleted.
103void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104 assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void
> (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 104, __PRETTY_FUNCTION__))
;
105
106 if (Decl->isDefaulted()) {
107 // If the method was explicitly defaulted, point at that declaration.
108 if (!Decl->isImplicit())
109 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110
111 // Try to diagnose why this special member function was implicitly
112 // deleted. This might fail, if that reason no longer applies.
113 DiagnoseDeletedDefaultedFunction(Decl);
114 return;
115 }
116
117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118 if (Ctor && Ctor->isInheritingConstructor())
119 return NoteDeletedInheritingConstructor(Ctor);
120
121 Diag(Decl->getLocation(), diag::note_availability_specified_here)
122 << Decl << 1;
123}
124
125/// Determine whether a FunctionDecl was ever declared with an
126/// explicit storage class.
127static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128 for (auto I : D->redecls()) {
129 if (I->getStorageClass() != SC_None)
130 return true;
131 }
132 return false;
133}
134
135/// Check whether we're in an extern inline function and referring to a
136/// variable or function with internal linkage (C11 6.7.4p3).
137///
138/// This is only a warning because we used to silently accept this code, but
139/// in many cases it will not behave correctly. This is not enabled in C++ mode
140/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141/// and so while there may still be user mistakes, most of the time we can't
142/// prove that there are errors.
143static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144 const NamedDecl *D,
145 SourceLocation Loc) {
146 // This is disabled under C++; there are too many ways for this to fire in
147 // contexts where the warning is a false positive, or where it is technically
148 // correct but benign.
149 if (S.getLangOpts().CPlusPlus)
150 return;
151
152 // Check if this is an inlined function or method.
153 FunctionDecl *Current = S.getCurFunctionDecl();
154 if (!Current)
155 return;
156 if (!Current->isInlined())
157 return;
158 if (!Current->isExternallyVisible())
159 return;
160
161 // Check if the decl has internal linkage.
162 if (D->getFormalLinkage() != InternalLinkage)
163 return;
164
165 // Downgrade from ExtWarn to Extension if
166 // (1) the supposedly external inline function is in the main file,
167 // and probably won't be included anywhere else.
168 // (2) the thing we're referencing is a pure function.
169 // (3) the thing we're referencing is another inline function.
170 // This last can give us false negatives, but it's better than warning on
171 // wrappers for simple C library functions.
172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174 if (!DowngradeWarning && UsedFn)
175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176
177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178 : diag::ext_internal_in_extern_inline)
179 << /*IsVar=*/!UsedFn << D;
180
181 S.MaybeSuggestAddingStaticToDecl(Current);
182
183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184 << D;
185}
186
187void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188 const FunctionDecl *First = Cur->getFirstDecl();
189
190 // Suggest "static" on the function, if possible.
191 if (!hasAnyExplicitStorageClass(First)) {
192 SourceLocation DeclBegin = First->getSourceRange().getBegin();
193 Diag(DeclBegin, diag::note_convert_inline_to_static)
194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195 }
196}
197
198/// Determine whether the use of this declaration is valid, and
199/// emit any corresponding diagnostics.
200///
201/// This routine diagnoses various problems with referencing
202/// declarations that can occur when using a declaration. For example,
203/// it might warn if a deprecated or unavailable declaration is being
204/// used, or produce an error (and return true) if a C++0x deleted
205/// function is being used.
206///
207/// \returns true if there was an error (this declaration cannot be
208/// referenced), false otherwise.
209///
210bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211 const ObjCInterfaceDecl *UnknownObjCClass,
212 bool ObjCPropertyAccess,
213 bool AvoidPartialAvailabilityChecks,
214 ObjCInterfaceDecl *ClassReceiver) {
215 SourceLocation Loc = Locs.front();
216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217 // If there were any diagnostics suppressed by template argument deduction,
218 // emit them now.
219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220 if (Pos != SuppressedDiagnostics.end()) {
221 for (const PartialDiagnosticAt &Suppressed : Pos->second)
222 Diag(Suppressed.first, Suppressed.second);
223
224 // Clear out the list of suppressed diagnostics, so that we don't emit
225 // them again for this specialization. However, we don't obsolete this
226 // entry from the table, because we want to avoid ever emitting these
227 // diagnostics again.
228 Pos->second.clear();
229 }
230
231 // C++ [basic.start.main]p3:
232 // The function 'main' shall not be used within a program.
233 if (cast<FunctionDecl>(D)->isMain())
234 Diag(Loc, diag::ext_main_used);
235
236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237 }
238
239 // See if this is an auto-typed variable whose initializer we are parsing.
240 if (ParsingInitForAutoVars.count(D)) {
241 if (isa<BindingDecl>(D)) {
242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243 << D->getDeclName();
244 } else {
245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246 << D->getDeclName() << cast<VarDecl>(D)->getType();
247 }
248 return true;
249 }
250
251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252 // See if this is a deleted function.
253 if (FD->isDeleted()) {
254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255 if (Ctor && Ctor->isInheritingConstructor())
256 Diag(Loc, diag::err_deleted_inherited_ctor_use)
257 << Ctor->getParent()
258 << Ctor->getInheritedConstructor().getConstructor()->getParent();
259 else
260 Diag(Loc, diag::err_deleted_function_use);
261 NoteDeletedFunction(FD);
262 return true;
263 }
264
265 // [expr.prim.id]p4
266 // A program that refers explicitly or implicitly to a function with a
267 // trailing requires-clause whose constraint-expression is not satisfied,
268 // other than to declare it, is ill-formed. [...]
269 //
270 // See if this is a function with constraints that need to be satisfied.
271 // Check this before deducing the return type, as it might instantiate the
272 // definition.
273 if (FD->getTrailingRequiresClause()) {
274 ConstraintSatisfaction Satisfaction;
275 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276 // A diagnostic will have already been generated (non-constant
277 // constraint expression, for example)
278 return true;
279 if (!Satisfaction.IsSatisfied) {
280 Diag(Loc,
281 diag::err_reference_to_function_with_unsatisfied_constraints)
282 << D;
283 DiagnoseUnsatisfiedConstraint(Satisfaction);
284 return true;
285 }
286 }
287
288 // If the function has a deduced return type, and we can't deduce it,
289 // then we can't use it either.
290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291 DeduceReturnType(FD, Loc))
292 return true;
293
294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295 return true;
296
297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298 return true;
299 }
300
301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302 // Lambdas are only default-constructible or assignable in C++2a onwards.
303 if (MD->getParent()->isLambda() &&
304 ((isa<CXXConstructorDecl>(MD) &&
305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308 << !isa<CXXConstructorDecl>(MD);
309 }
310 }
311
312 auto getReferencedObjCProp = [](const NamedDecl *D) ->
313 const ObjCPropertyDecl * {
314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315 return MD->findPropertyDecl();
316 return nullptr;
317 };
318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320 return true;
321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322 return true;
323 }
324
325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326 // Only the variables omp_in and omp_out are allowed in the combiner.
327 // Only the variables omp_priv and omp_orig are allowed in the
328 // initializer-clause.
329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331 isa<VarDecl>(D)) {
332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333 << getCurFunction()->HasOMPDeclareReductionCombiner;
334 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335 return true;
336 }
337
338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339 // List-items in map clauses on this construct may only refer to the declared
340 // variable var and entities that could be referenced by a procedure defined
341 // at the same location
342 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
343 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346 << DMD->getVarName().getAsString();
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352 AvoidPartialAvailabilityChecks, ClassReceiver);
353
354 DiagnoseUnusedOfDecl(*this, D, Loc);
355
356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357
358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
359 if (const auto *VD = dyn_cast<ValueDecl>(D))
360 checkDeviceDecl(VD, Loc);
361
362 if (!Context.getTargetInfo().isTLSSupported())
363 if (const auto *VD = dyn_cast<VarDecl>(D))
364 if (VD->getTLSKind() != VarDecl::TLS_None)
365 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
366 }
367
368 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
369 !isUnevaluatedContext()) {
370 // C++ [expr.prim.req.nested] p3
371 // A local parameter shall only appear as an unevaluated operand
372 // (Clause 8) within the constraint-expression.
373 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
374 << D;
375 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
376 return true;
377 }
378
379 return false;
380}
381
382/// DiagnoseSentinelCalls - This routine checks whether a call or
383/// message-send is to a declaration with the sentinel attribute, and
384/// if so, it checks that the requirements of the sentinel are
385/// satisfied.
386void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
387 ArrayRef<Expr *> Args) {
388 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
389 if (!attr)
390 return;
391
392 // The number of formal parameters of the declaration.
393 unsigned numFormalParams;
394
395 // The kind of declaration. This is also an index into a %select in
396 // the diagnostic.
397 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
398
399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
400 numFormalParams = MD->param_size();
401 calleeType = CT_Method;
402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
403 numFormalParams = FD->param_size();
404 calleeType = CT_Function;
405 } else if (isa<VarDecl>(D)) {
406 QualType type = cast<ValueDecl>(D)->getType();
407 const FunctionType *fn = nullptr;
408 if (const PointerType *ptr = type->getAs<PointerType>()) {
409 fn = ptr->getPointeeType()->getAs<FunctionType>();
410 if (!fn) return;
411 calleeType = CT_Function;
412 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
413 fn = ptr->getPointeeType()->castAs<FunctionType>();
414 calleeType = CT_Block;
415 } else {
416 return;
417 }
418
419 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
420 numFormalParams = proto->getNumParams();
421 } else {
422 numFormalParams = 0;
423 }
424 } else {
425 return;
426 }
427
428 // "nullPos" is the number of formal parameters at the end which
429 // effectively count as part of the variadic arguments. This is
430 // useful if you would prefer to not have *any* formal parameters,
431 // but the language forces you to have at least one.
432 unsigned nullPos = attr->getNullPos();
433 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"
) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 433, __PRETTY_FUNCTION__))
;
434 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
435
436 // The number of arguments which should follow the sentinel.
437 unsigned numArgsAfterSentinel = attr->getSentinel();
438
439 // If there aren't enough arguments for all the formal parameters,
440 // the sentinel, and the args after the sentinel, complain.
441 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
442 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
443 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
444 return;
445 }
446
447 // Otherwise, find the sentinel expression.
448 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
449 if (!sentinelExpr) return;
450 if (sentinelExpr->isValueDependent()) return;
451 if (Context.isSentinelNullExpr(sentinelExpr)) return;
452
453 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
454 // or 'NULL' if those are actually defined in the context. Only use
455 // 'nil' for ObjC methods, where it's much more likely that the
456 // variadic arguments form a list of object pointers.
457 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
458 std::string NullValue;
459 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
460 NullValue = "nil";
461 else if (getLangOpts().CPlusPlus11)
462 NullValue = "nullptr";
463 else if (PP.isMacroDefined("NULL"))
464 NullValue = "NULL";
465 else
466 NullValue = "(void*) 0";
467
468 if (MissingNilLoc.isInvalid())
469 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
470 else
471 Diag(MissingNilLoc, diag::warn_missing_sentinel)
472 << int(calleeType)
473 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
474 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
475}
476
477SourceRange Sema::getExprRange(Expr *E) const {
478 return E ? E->getSourceRange() : SourceRange();
479}
480
481//===----------------------------------------------------------------------===//
482// Standard Promotions and Conversions
483//===----------------------------------------------------------------------===//
484
485/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
486ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
487 // Handle any placeholder expressions which made it here.
488 if (E->getType()->isPlaceholderType()) {
489 ExprResult result = CheckPlaceholderExpr(E);
490 if (result.isInvalid()) return ExprError();
491 E = result.get();
492 }
493
494 QualType Ty = E->getType();
495 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 495, __PRETTY_FUNCTION__))
;
496
497 if (Ty->isFunctionType()) {
498 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
499 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
500 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
501 return ExprError();
502
503 E = ImpCastExprToType(E, Context.getPointerType(Ty),
504 CK_FunctionToPointerDecay).get();
505 } else if (Ty->isArrayType()) {
506 // In C90 mode, arrays only promote to pointers if the array expression is
507 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
508 // type 'array of type' is converted to an expression that has type 'pointer
509 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
510 // that has type 'array of type' ...". The relevant change is "an lvalue"
511 // (C90) to "an expression" (C99).
512 //
513 // C++ 4.2p1:
514 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
515 // T" can be converted to an rvalue of type "pointer to T".
516 //
517 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
518 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
519 CK_ArrayToPointerDecay).get();
520 }
521 return E;
522}
523
524static void CheckForNullPointerDereference(Sema &S, Expr *E) {
525 // Check to see if we are dereferencing a null pointer. If so,
526 // and if not volatile-qualified, this is undefined behavior that the
527 // optimizer will delete, so warn about it. People sometimes try to use this
528 // to get a deterministic trap and are surprised by clang's behavior. This
529 // only handles the pattern "*null", which is a very syntactic check.
530 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
531 if (UO && UO->getOpcode() == UO_Deref &&
532 UO->getSubExpr()->getType()->isPointerType()) {
533 const LangAS AS =
534 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
535 if ((!isTargetAddressSpace(AS) ||
536 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
537 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
538 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
539 !UO->getType().isVolatileQualified()) {
540 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
541 S.PDiag(diag::warn_indirection_through_null)
542 << UO->getSubExpr()->getSourceRange());
543 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
544 S.PDiag(diag::note_indirection_through_null));
545 }
546 }
547}
548
549static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
550 SourceLocation AssignLoc,
551 const Expr* RHS) {
552 const ObjCIvarDecl *IV = OIRE->getDecl();
553 if (!IV)
554 return;
555
556 DeclarationName MemberName = IV->getDeclName();
557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
558 if (!Member || !Member->isStr("isa"))
559 return;
560
561 const Expr *Base = OIRE->getBase();
562 QualType BaseType = Base->getType();
563 if (OIRE->isArrow())
564 BaseType = BaseType->getPointeeType();
565 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
566 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
567 ObjCInterfaceDecl *ClassDeclared = nullptr;
568 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
569 if (!ClassDeclared->getSuperClass()
570 && (*ClassDeclared->ivar_begin()) == IV) {
571 if (RHS) {
572 NamedDecl *ObjectSetClass =
573 S.LookupSingleName(S.TUScope,
574 &S.Context.Idents.get("object_setClass"),
575 SourceLocation(), S.LookupOrdinaryName);
576 if (ObjectSetClass) {
577 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580 "object_setClass(")
581 << FixItHint::CreateReplacement(
582 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
583 << FixItHint::CreateInsertion(RHSLocEnd, ")");
584 }
585 else
586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
587 } else {
588 NamedDecl *ObjectGetClass =
589 S.LookupSingleName(S.TUScope,
590 &S.Context.Idents.get("object_getClass"),
591 SourceLocation(), S.LookupOrdinaryName);
592 if (ObjectGetClass)
593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595 "object_getClass(")
596 << FixItHint::CreateReplacement(
597 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
598 else
599 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
600 }
601 S.Diag(IV->getLocation(), diag::note_ivar_decl);
602 }
603 }
604}
605
606ExprResult Sema::DefaultLvalueConversion(Expr *E) {
607 // Handle any placeholder expressions which made it here.
608 if (E->getType()->isPlaceholderType()) {
609 ExprResult result = CheckPlaceholderExpr(E);
610 if (result.isInvalid()) return ExprError();
611 E = result.get();
612 }
613
614 // C++ [conv.lval]p1:
615 // A glvalue of a non-function, non-array type T can be
616 // converted to a prvalue.
617 if (!E->isGLValue()) return E;
618
619 QualType T = E->getType();
620 assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?"
) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 620, __PRETTY_FUNCTION__))
;
621
622 // lvalue-to-rvalue conversion cannot be applied to function or array types.
623 if (T->isFunctionType() || T->isArrayType())
624 return E;
625
626 // We don't want to throw lvalue-to-rvalue casts on top of
627 // expressions of certain types in C++.
628 if (getLangOpts().CPlusPlus &&
629 (E->getType() == Context.OverloadTy ||
630 T->isDependentType() ||
631 T->isRecordType()))
632 return E;
633
634 // The C standard is actually really unclear on this point, and
635 // DR106 tells us what the result should be but not why. It's
636 // generally best to say that void types just doesn't undergo
637 // lvalue-to-rvalue at all. Note that expressions of unqualified
638 // 'void' type are never l-values, but qualified void can be.
639 if (T->isVoidType())
640 return E;
641
642 // OpenCL usually rejects direct accesses to values of 'half' type.
643 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
644 T->isHalfType()) {
645 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
646 << 0 << T;
647 return ExprError();
648 }
649
650 CheckForNullPointerDereference(*this, E);
651 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
652 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
653 &Context.Idents.get("object_getClass"),
654 SourceLocation(), LookupOrdinaryName);
655 if (ObjectGetClass)
656 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
657 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
658 << FixItHint::CreateReplacement(
659 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
660 else
661 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
662 }
663 else if (const ObjCIvarRefExpr *OIRE =
664 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
665 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
666
667 // C++ [conv.lval]p1:
668 // [...] If T is a non-class type, the type of the prvalue is the
669 // cv-unqualified version of T. Otherwise, the type of the
670 // rvalue is T.
671 //
672 // C99 6.3.2.1p2:
673 // If the lvalue has qualified type, the value has the unqualified
674 // version of the type of the lvalue; otherwise, the value has the
675 // type of the lvalue.
676 if (T.hasQualifiers())
677 T = T.getUnqualifiedType();
678
679 // Under the MS ABI, lock down the inheritance model now.
680 if (T->isMemberPointerType() &&
681 Context.getTargetInfo().getCXXABI().isMicrosoft())
682 (void)isCompleteType(E->getExprLoc(), T);
683
684 ExprResult Res = CheckLValueToRValueConversionOperand(E);
685 if (Res.isInvalid())
686 return Res;
687 E = Res.get();
688
689 // Loading a __weak object implicitly retains the value, so we need a cleanup to
690 // balance that.
691 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
692 Cleanup.setExprNeedsCleanups(true);
693
694 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
695 Cleanup.setExprNeedsCleanups(true);
696
697 // C++ [conv.lval]p3:
698 // If T is cv std::nullptr_t, the result is a null pointer constant.
699 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
700 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
701
702 // C11 6.3.2.1p2:
703 // ... if the lvalue has atomic type, the value has the non-atomic version
704 // of the type of the lvalue ...
705 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
706 T = Atomic->getValueType().getUnqualifiedType();
707 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
708 nullptr, VK_RValue);
709 }
710
711 return Res;
712}
713
714ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
715 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
716 if (Res.isInvalid())
717 return ExprError();
718 Res = DefaultLvalueConversion(Res.get());
719 if (Res.isInvalid())
720 return ExprError();
721 return Res;
722}
723
724/// CallExprUnaryConversions - a special case of an unary conversion
725/// performed on a function designator of a call expression.
726ExprResult Sema::CallExprUnaryConversions(Expr *E) {
727 QualType Ty = E->getType();
728 ExprResult Res = E;
729 // Only do implicit cast for a function type, but not for a pointer
730 // to function type.
731 if (Ty->isFunctionType()) {
732 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
733 CK_FunctionToPointerDecay);
734 if (Res.isInvalid())
735 return ExprError();
736 }
737 Res = DefaultLvalueConversion(Res.get());
738 if (Res.isInvalid())
739 return ExprError();
740 return Res.get();
741}
742
743/// UsualUnaryConversions - Performs various conversions that are common to most
744/// operators (C99 6.3). The conversions of array and function types are
745/// sometimes suppressed. For example, the array->pointer conversion doesn't
746/// apply if the array is an argument to the sizeof or address (&) operators.
747/// In these instances, this routine should *not* be called.
748ExprResult Sema::UsualUnaryConversions(Expr *E) {
749 // First, convert to an r-value.
750 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
751 if (Res.isInvalid())
752 return ExprError();
753 E = Res.get();
754
755 QualType Ty = E->getType();
756 assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 756, __PRETTY_FUNCTION__))
;
757
758 // Half FP have to be promoted to float unless it is natively supported
759 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
760 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
761
762 // Try to perform integral promotions if the object has a theoretically
763 // promotable type.
764 if (Ty->isIntegralOrUnscopedEnumerationType()) {
765 // C99 6.3.1.1p2:
766 //
767 // The following may be used in an expression wherever an int or
768 // unsigned int may be used:
769 // - an object or expression with an integer type whose integer
770 // conversion rank is less than or equal to the rank of int
771 // and unsigned int.
772 // - A bit-field of type _Bool, int, signed int, or unsigned int.
773 //
774 // If an int can represent all values of the original type, the
775 // value is converted to an int; otherwise, it is converted to an
776 // unsigned int. These are called the integer promotions. All
777 // other types are unchanged by the integer promotions.
778
779 QualType PTy = Context.isPromotableBitField(E);
780 if (!PTy.isNull()) {
781 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
782 return E;
783 }
784 if (Ty->isPromotableIntegerType()) {
785 QualType PT = Context.getPromotedIntegerType(Ty);
786 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
787 return E;
788 }
789 }
790 return E;
791}
792
793/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
794/// do not have a prototype. Arguments that have type float or __fp16
795/// are promoted to double. All other argument types are converted by
796/// UsualUnaryConversions().
797ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
798 QualType Ty = E->getType();
799 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 799, __PRETTY_FUNCTION__))
;
800
801 ExprResult Res = UsualUnaryConversions(E);
802 if (Res.isInvalid())
803 return ExprError();
804 E = Res.get();
805
806 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
807 // promote to double.
808 // Note that default argument promotion applies only to float (and
809 // half/fp16); it does not apply to _Float16.
810 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
811 if (BTy && (BTy->getKind() == BuiltinType::Half ||
812 BTy->getKind() == BuiltinType::Float)) {
813 if (getLangOpts().OpenCL &&
814 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
815 if (BTy->getKind() == BuiltinType::Half) {
816 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
817 }
818 } else {
819 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
820 }
821 }
822
823 // C++ performs lvalue-to-rvalue conversion as a default argument
824 // promotion, even on class types, but note:
825 // C++11 [conv.lval]p2:
826 // When an lvalue-to-rvalue conversion occurs in an unevaluated
827 // operand or a subexpression thereof the value contained in the
828 // referenced object is not accessed. Otherwise, if the glvalue
829 // has a class type, the conversion copy-initializes a temporary
830 // of type T from the glvalue and the result of the conversion
831 // is a prvalue for the temporary.
832 // FIXME: add some way to gate this entire thing for correctness in
833 // potentially potentially evaluated contexts.
834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
835 ExprResult Temp = PerformCopyInitialization(
836 InitializedEntity::InitializeTemporary(E->getType()),
837 E->getExprLoc(), E);
838 if (Temp.isInvalid())
839 return ExprError();
840 E = Temp.get();
841 }
842
843 return E;
844}
845
846/// Determine the degree of POD-ness for an expression.
847/// Incomplete types are considered POD, since this check can be performed
848/// when we're in an unevaluated context.
849Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
850 if (Ty->isIncompleteType()) {
851 // C++11 [expr.call]p7:
852 // After these conversions, if the argument does not have arithmetic,
853 // enumeration, pointer, pointer to member, or class type, the program
854 // is ill-formed.
855 //
856 // Since we've already performed array-to-pointer and function-to-pointer
857 // decay, the only such type in C++ is cv void. This also handles
858 // initializer lists as variadic arguments.
859 if (Ty->isVoidType())
860 return VAK_Invalid;
861
862 if (Ty->isObjCObjectType())
863 return VAK_Invalid;
864 return VAK_Valid;
865 }
866
867 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
868 return VAK_Invalid;
869
870 if (Ty.isCXX98PODType(Context))
871 return VAK_Valid;
872
873 // C++11 [expr.call]p7:
874 // Passing a potentially-evaluated argument of class type (Clause 9)
875 // having a non-trivial copy constructor, a non-trivial move constructor,
876 // or a non-trivial destructor, with no corresponding parameter,
877 // is conditionally-supported with implementation-defined semantics.
878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880 if (!Record->hasNonTrivialCopyConstructor() &&
881 !Record->hasNonTrivialMoveConstructor() &&
882 !Record->hasNonTrivialDestructor())
883 return VAK_ValidInCXX11;
884
885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
886 return VAK_Valid;
887
888 if (Ty->isObjCObjectType())
889 return VAK_Invalid;
890
891 if (getLangOpts().MSVCCompat)
892 return VAK_MSVCUndefined;
893
894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895 // permitted to reject them. We should consider doing so.
896 return VAK_Undefined;
897}
898
899void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900 // Don't allow one to pass an Objective-C interface to a vararg.
901 const QualType &Ty = E->getType();
902 VarArgKind VAK = isValidVarArgType(Ty);
903
904 // Complain about passing non-POD types through varargs.
905 switch (VAK) {
906 case VAK_ValidInCXX11:
907 DiagRuntimeBehavior(
908 E->getBeginLoc(), nullptr,
909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
910 LLVM_FALLTHROUGH[[gnu::fallthrough]];
911 case VAK_Valid:
912 if (Ty->isRecordType()) {
913 // This is unlikely to be what the user intended. If the class has a
914 // 'c_str' member function, the user probably meant to call that.
915 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
916 PDiag(diag::warn_pass_class_arg_to_vararg)
917 << Ty << CT << hasCStrMethod(E) << ".c_str()");
918 }
919 break;
920
921 case VAK_Undefined:
922 case VAK_MSVCUndefined:
923 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
924 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
925 << getLangOpts().CPlusPlus11 << Ty << CT);
926 break;
927
928 case VAK_Invalid:
929 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
930 Diag(E->getBeginLoc(),
931 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
932 << Ty << CT;
933 else if (Ty->isObjCObjectType())
934 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
935 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
936 << Ty << CT);
937 else
938 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
939 << isa<InitListExpr>(E) << Ty << CT;
940 break;
941 }
942}
943
944/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
945/// will create a trap if the resulting type is not a POD type.
946ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
947 FunctionDecl *FDecl) {
948 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
949 // Strip the unbridged-cast placeholder expression off, if applicable.
950 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
951 (CT == VariadicMethod ||
952 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
953 E = stripARCUnbridgedCast(E);
954
955 // Otherwise, do normal placeholder checking.
956 } else {
957 ExprResult ExprRes = CheckPlaceholderExpr(E);
958 if (ExprRes.isInvalid())
959 return ExprError();
960 E = ExprRes.get();
961 }
962 }
963
964 ExprResult ExprRes = DefaultArgumentPromotion(E);
965 if (ExprRes.isInvalid())
966 return ExprError();
967
968 // Copy blocks to the heap.
969 if (ExprRes.get()->getType()->isBlockPointerType())
970 maybeExtendBlockObject(ExprRes);
971
972 E = ExprRes.get();
973
974 // Diagnostics regarding non-POD argument types are
975 // emitted along with format string checking in Sema::CheckFunctionCall().
976 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
977 // Turn this into a trap.
978 CXXScopeSpec SS;
979 SourceLocation TemplateKWLoc;
980 UnqualifiedId Name;
981 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
982 E->getBeginLoc());
983 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
984 /*HasTrailingLParen=*/true,
985 /*IsAddressOfOperand=*/false);
986 if (TrapFn.isInvalid())
987 return ExprError();
988
989 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
990 None, E->getEndLoc());
991 if (Call.isInvalid())
992 return ExprError();
993
994 ExprResult Comma =
995 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
996 if (Comma.isInvalid())
997 return ExprError();
998 return Comma.get();
999 }
1000
1001 if (!getLangOpts().CPlusPlus &&
1002 RequireCompleteType(E->getExprLoc(), E->getType(),
1003 diag::err_call_incomplete_argument))
1004 return ExprError();
1005
1006 return E;
1007}
1008
1009/// Converts an integer to complex float type. Helper function of
1010/// UsualArithmeticConversions()
1011///
1012/// \return false if the integer expression is an integer type and is
1013/// successfully converted to the complex type.
1014static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1015 ExprResult &ComplexExpr,
1016 QualType IntTy,
1017 QualType ComplexTy,
1018 bool SkipCast) {
1019 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1020 if (SkipCast) return false;
1021 if (IntTy->isIntegerType()) {
1022 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1025 CK_FloatingRealToComplex);
1026 } else {
1027 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1027, __PRETTY_FUNCTION__))
;
1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1029 CK_IntegralComplexToFloatingComplex);
1030 }
1031 return false;
1032}
1033
1034/// Handle arithmetic conversion with complex types. Helper function of
1035/// UsualArithmeticConversions()
1036static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1037 ExprResult &RHS, QualType LHSType,
1038 QualType RHSType,
1039 bool IsCompAssign) {
1040 // if we have an integer operand, the result is the complex type.
1041 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1042 /*skipCast*/false))
1043 return LHSType;
1044 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1045 /*skipCast*/IsCompAssign))
1046 return RHSType;
1047
1048 // This handles complex/complex, complex/float, or float/complex.
1049 // When both operands are complex, the shorter operand is converted to the
1050 // type of the longer, and that is the type of the result. This corresponds
1051 // to what is done when combining two real floating-point operands.
1052 // The fun begins when size promotion occur across type domains.
1053 // From H&S 6.3.4: When one operand is complex and the other is a real
1054 // floating-point type, the less precise type is converted, within it's
1055 // real or complex domain, to the precision of the other type. For example,
1056 // when combining a "long double" with a "double _Complex", the
1057 // "double _Complex" is promoted to "long double _Complex".
1058
1059 // Compute the rank of the two types, regardless of whether they are complex.
1060 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061
1062 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1063 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1064 QualType LHSElementType =
1065 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1066 QualType RHSElementType =
1067 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1068
1069 QualType ResultType = S.Context.getComplexType(LHSElementType);
1070 if (Order < 0) {
1071 // Promote the precision of the LHS if not an assignment.
1072 ResultType = S.Context.getComplexType(RHSElementType);
1073 if (!IsCompAssign) {
1074 if (LHSComplexType)
1075 LHS =
1076 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1077 else
1078 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1079 }
1080 } else if (Order > 0) {
1081 // Promote the precision of the RHS.
1082 if (RHSComplexType)
1083 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1084 else
1085 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1086 }
1087 return ResultType;
1088}
1089
1090/// Handle arithmetic conversion from integer to float. Helper function
1091/// of UsualArithmeticConversions()
1092static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1093 ExprResult &IntExpr,
1094 QualType FloatTy, QualType IntTy,
1095 bool ConvertFloat, bool ConvertInt) {
1096 if (IntTy->isIntegerType()) {
1097 if (ConvertInt)
1098 // Convert intExpr to the lhs floating point type.
1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1100 CK_IntegralToFloating);
1101 return FloatTy;
1102 }
1103
1104 // Convert both sides to the appropriate complex float.
1105 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1105, __PRETTY_FUNCTION__))
;
1106 QualType result = S.Context.getComplexType(FloatTy);
1107
1108 // _Complex int -> _Complex float
1109 if (ConvertInt)
1110 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1111 CK_IntegralComplexToFloatingComplex);
1112
1113 // float -> _Complex float
1114 if (ConvertFloat)
1115 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1116 CK_FloatingRealToComplex);
1117
1118 return result;
1119}
1120
1121/// Handle arithmethic conversion with floating point types. Helper
1122/// function of UsualArithmeticConversions()
1123static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1124 ExprResult &RHS, QualType LHSType,
1125 QualType RHSType, bool IsCompAssign) {
1126 bool LHSFloat = LHSType->isRealFloatingType();
1127 bool RHSFloat = RHSType->isRealFloatingType();
1128
1129 // If we have two real floating types, convert the smaller operand
1130 // to the bigger result.
1131 if (LHSFloat && RHSFloat) {
1132 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1133 if (order > 0) {
1134 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1135 return LHSType;
1136 }
1137
1138 assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast
<void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1138, __PRETTY_FUNCTION__))
;
1139 if (!IsCompAssign)
1140 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1141 return RHSType;
1142 }
1143
1144 if (LHSFloat) {
1145 // Half FP has to be promoted to float unless it is natively supported
1146 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1147 LHSType = S.Context.FloatTy;
1148
1149 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1150 /*ConvertFloat=*/!IsCompAssign,
1151 /*ConvertInt=*/ true);
1152 }
1153 assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1153, __PRETTY_FUNCTION__))
;
1154 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1155 /*convertInt=*/ true,
1156 /*convertFloat=*/!IsCompAssign);
1157}
1158
1159/// Diagnose attempts to convert between __float128 and long double if
1160/// there is no support for such conversion. Helper function of
1161/// UsualArithmeticConversions().
1162static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1163 QualType RHSType) {
1164 /* No issue converting if at least one of the types is not a floating point
1165 type or the two types have the same rank.
1166 */
1167 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
32
Assuming the condition is false
33
Assuming the condition is false
35
Taking false branch
1168 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
34
Assuming the condition is false
1169 return false;
1170
1171 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1172, __PRETTY_FUNCTION__))
36
Assuming the condition is true
37
Assuming the condition is true
38
'?' condition is true
1172 "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1172, __PRETTY_FUNCTION__))
;
1173
1174 auto *LHSComplex = LHSType->getAs<ComplexType>();
39
Assuming the object is not a 'ComplexType'
1175 auto *RHSComplex = RHSType->getAs<ComplexType>();
40
Assuming the object is not a 'ComplexType'
1176
1177 QualType LHSElemType = LHSComplex
40.1
'LHSComplex' is null
40.1
'LHSComplex' is null
40.1
'LHSComplex' is null
40.1
'LHSComplex' is null
?
41
'?' condition is false
1178 LHSComplex->getElementType() : LHSType;
1179 QualType RHSElemType = RHSComplex
41.1
'RHSComplex' is null
41.1
'RHSComplex' is null
41.1
'RHSComplex' is null
41.1
'RHSComplex' is null
?
42
'?' condition is false
1180 RHSComplex->getElementType() : RHSType;
1181
1182 // No issue if the two types have the same representation
1183 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
43
Assuming the condition is false
44
Taking false branch
1184 &S.Context.getFloatTypeSemantics(RHSElemType))
1185 return false;
1186
1187 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1188 RHSElemType == S.Context.LongDoubleTy);
1189 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1190 RHSElemType == S.Context.Float128Ty);
1191
1192 // We've handled the situation where __float128 and long double have the same
1193 // representation. We allow all conversions for all possible long double types
1194 // except PPC's double double.
1195 return Float128AndLongDouble
44.1
'Float128AndLongDouble' is false
44.1
'Float128AndLongDouble' is false
44.1
'Float128AndLongDouble' is false
44.1
'Float128AndLongDouble' is false
&&
45
Returning zero, which participates in a condition later
1196 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1197 &llvm::APFloat::PPCDoubleDouble());
1198}
1199
1200typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1201
1202namespace {
1203/// These helper callbacks are placed in an anonymous namespace to
1204/// permit their use as function template parameters.
1205ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1206 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1207}
1208
1209ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1210 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1211 CK_IntegralComplexCast);
1212}
1213}
1214
1215/// Handle integer arithmetic conversions. Helper function of
1216/// UsualArithmeticConversions()
1217template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1218static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1219 ExprResult &RHS, QualType LHSType,
1220 QualType RHSType, bool IsCompAssign) {
1221 // The rules for this case are in C99 6.3.1.8
1222 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1223 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1224 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1225 if (LHSSigned == RHSSigned) {
1226 // Same signedness; use the higher-ranked type
1227 if (order >= 0) {
1228 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1229 return LHSType;
1230 } else if (!IsCompAssign)
1231 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1232 return RHSType;
1233 } else if (order != (LHSSigned ? 1 : -1)) {
1234 // The unsigned type has greater than or equal rank to the
1235 // signed type, so use the unsigned type
1236 if (RHSSigned) {
1237 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1238 return LHSType;
1239 } else if (!IsCompAssign)
1240 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1241 return RHSType;
1242 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1243 // The two types are different widths; if we are here, that
1244 // means the signed type is larger than the unsigned type, so
1245 // use the signed type.
1246 if (LHSSigned) {
1247 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1248 return LHSType;
1249 } else if (!IsCompAssign)
1250 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1251 return RHSType;
1252 } else {
1253 // The signed type is higher-ranked than the unsigned type,
1254 // but isn't actually any bigger (like unsigned int and long
1255 // on most 32-bit systems). Use the unsigned type corresponding
1256 // to the signed type.
1257 QualType result =
1258 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1259 RHS = (*doRHSCast)(S, RHS.get(), result);
1260 if (!IsCompAssign)
1261 LHS = (*doLHSCast)(S, LHS.get(), result);
1262 return result;
1263 }
1264}
1265
1266/// Handle conversions with GCC complex int extension. Helper function
1267/// of UsualArithmeticConversions()
1268static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1269 ExprResult &RHS, QualType LHSType,
1270 QualType RHSType,
1271 bool IsCompAssign) {
1272 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1273 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1274
1275 if (LHSComplexInt && RHSComplexInt) {
1276 QualType LHSEltType = LHSComplexInt->getElementType();
1277 QualType RHSEltType = RHSComplexInt->getElementType();
1278 QualType ScalarType =
1279 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1280 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1281
1282 return S.Context.getComplexType(ScalarType);
1283 }
1284
1285 if (LHSComplexInt) {
1286 QualType LHSEltType = LHSComplexInt->getElementType();
1287 QualType ScalarType =
1288 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1289 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1290 QualType ComplexType = S.Context.getComplexType(ScalarType);
1291 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1292 CK_IntegralRealToComplex);
1293
1294 return ComplexType;
1295 }
1296
1297 assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail
("RHSComplexInt", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1297, __PRETTY_FUNCTION__))
;
1298
1299 QualType RHSEltType = RHSComplexInt->getElementType();
1300 QualType ScalarType =
1301 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1302 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1303 QualType ComplexType = S.Context.getComplexType(ScalarType);
1304
1305 if (!IsCompAssign)
1306 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1307 CK_IntegralRealToComplex);
1308 return ComplexType;
1309}
1310
1311/// Return the rank of a given fixed point or integer type. The value itself
1312/// doesn't matter, but the values must be increasing with proper increasing
1313/// rank as described in N1169 4.1.1.
1314static unsigned GetFixedPointRank(QualType Ty) {
1315 const auto *BTy = Ty->getAs<BuiltinType>();
1316 assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast<
void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1316, __PRETTY_FUNCTION__))
;
1317
1318 switch (BTy->getKind()) {
1319 case BuiltinType::ShortFract:
1320 case BuiltinType::UShortFract:
1321 case BuiltinType::SatShortFract:
1322 case BuiltinType::SatUShortFract:
1323 return 1;
1324 case BuiltinType::Fract:
1325 case BuiltinType::UFract:
1326 case BuiltinType::SatFract:
1327 case BuiltinType::SatUFract:
1328 return 2;
1329 case BuiltinType::LongFract:
1330 case BuiltinType::ULongFract:
1331 case BuiltinType::SatLongFract:
1332 case BuiltinType::SatULongFract:
1333 return 3;
1334 case BuiltinType::ShortAccum:
1335 case BuiltinType::UShortAccum:
1336 case BuiltinType::SatShortAccum:
1337 case BuiltinType::SatUShortAccum:
1338 return 4;
1339 case BuiltinType::Accum:
1340 case BuiltinType::UAccum:
1341 case BuiltinType::SatAccum:
1342 case BuiltinType::SatUAccum:
1343 return 5;
1344 case BuiltinType::LongAccum:
1345 case BuiltinType::ULongAccum:
1346 case BuiltinType::SatLongAccum:
1347 case BuiltinType::SatULongAccum:
1348 return 6;
1349 default:
1350 if (BTy->isInteger())
1351 return 0;
1352 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1352)
;
1353 }
1354}
1355
1356/// handleFixedPointConversion - Fixed point operations between fixed
1357/// point types and integers or other fixed point types do not fall under
1358/// usual arithmetic conversion since these conversions could result in loss
1359/// of precsision (N1169 4.1.4). These operations should be calculated with
1360/// the full precision of their result type (N1169 4.1.6.2.1).
1361static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1362 QualType RHSTy) {
1363 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1364, __PRETTY_FUNCTION__))
1364 "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1364, __PRETTY_FUNCTION__))
;
1365 assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1368, __PRETTY_FUNCTION__))
1366 RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1368, __PRETTY_FUNCTION__))
1367 "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1368, __PRETTY_FUNCTION__))
1368 "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1368, __PRETTY_FUNCTION__))
;
1369
1370 // If one operand has signed fixed-point type and the other operand has
1371 // unsigned fixed-point type, then the unsigned fixed-point operand is
1372 // converted to its corresponding signed fixed-point type and the resulting
1373 // type is the type of the converted operand.
1374 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1375 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1376 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1377 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1378
1379 // The result type is the type with the highest rank, whereby a fixed-point
1380 // conversion rank is always greater than an integer conversion rank; if the
1381 // type of either of the operands is a saturating fixedpoint type, the result
1382 // type shall be the saturating fixed-point type corresponding to the type
1383 // with the highest rank; the resulting value is converted (taking into
1384 // account rounding and overflow) to the precision of the resulting type.
1385 // Same ranks between signed and unsigned types are resolved earlier, so both
1386 // types are either signed or both unsigned at this point.
1387 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1388 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1389
1390 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1391
1392 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1393 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1394
1395 return ResultTy;
1396}
1397
1398/// Check that the usual arithmetic conversions can be performed on this pair of
1399/// expressions that might be of enumeration type.
1400static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1401 SourceLocation Loc,
1402 Sema::ArithConvKind ACK) {
1403 // C++2a [expr.arith.conv]p1:
1404 // If one operand is of enumeration type and the other operand is of a
1405 // different enumeration type or a floating-point type, this behavior is
1406 // deprecated ([depr.arith.conv.enum]).
1407 //
1408 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1409 // Eventually we will presumably reject these cases (in C++23 onwards?).
1410 QualType L = LHS->getType(), R = RHS->getType();
1411 bool LEnum = L->isUnscopedEnumerationType(),
1412 REnum = R->isUnscopedEnumerationType();
1413 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1414 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1415 (REnum && L->isFloatingType())) {
1416 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1417 ? diag::warn_arith_conv_enum_float_cxx20
1418 : diag::warn_arith_conv_enum_float)
1419 << LHS->getSourceRange() << RHS->getSourceRange()
1420 << (int)ACK << LEnum << L << R;
1421 } else if (!IsCompAssign && LEnum && REnum &&
1422 !S.Context.hasSameUnqualifiedType(L, R)) {
1423 unsigned DiagID;
1424 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1425 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1426 // If either enumeration type is unnamed, it's less likely that the
1427 // user cares about this, but this situation is still deprecated in
1428 // C++2a. Use a different warning group.
1429 DiagID = S.getLangOpts().CPlusPlus20
1430 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1431 : diag::warn_arith_conv_mixed_anon_enum_types;
1432 } else if (ACK == Sema::ACK_Conditional) {
1433 // Conditional expressions are separated out because they have
1434 // historically had a different warning flag.
1435 DiagID = S.getLangOpts().CPlusPlus20
1436 ? diag::warn_conditional_mixed_enum_types_cxx20
1437 : diag::warn_conditional_mixed_enum_types;
1438 } else if (ACK == Sema::ACK_Comparison) {
1439 // Comparison expressions are separated out because they have
1440 // historically had a different warning flag.
1441 DiagID = S.getLangOpts().CPlusPlus20
1442 ? diag::warn_comparison_mixed_enum_types_cxx20
1443 : diag::warn_comparison_mixed_enum_types;
1444 } else {
1445 DiagID = S.getLangOpts().CPlusPlus20
1446 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1447 : diag::warn_arith_conv_mixed_enum_types;
1448 }
1449 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1450 << (int)ACK << L << R;
1451 }
1452}
1453
1454/// UsualArithmeticConversions - Performs various conversions that are common to
1455/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1456/// routine returns the first non-arithmetic type found. The client is
1457/// responsible for emitting appropriate error diagnostics.
1458QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1459 SourceLocation Loc,
1460 ArithConvKind ACK) {
1461 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1462
1463 if (ACK != ACK_CompAssign) {
1464 LHS = UsualUnaryConversions(LHS.get());
1465 if (LHS.isInvalid())
1466 return QualType();
1467 }
1468
1469 RHS = UsualUnaryConversions(RHS.get());
1470 if (RHS.isInvalid())
1471 return QualType();
1472
1473 // For conversion purposes, we ignore any qualifiers.
1474 // For example, "const float" and "float" are equivalent.
1475 QualType LHSType =
1476 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1477 QualType RHSType =
1478 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1479
1480 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1481 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1482 LHSType = AtomicLHS->getValueType();
1483
1484 // If both types are identical, no conversion is needed.
1485 if (LHSType == RHSType)
1486 return LHSType;
1487
1488 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1489 // The caller can deal with this (e.g. pointer + int).
1490 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1491 return QualType();
1492
1493 // Apply unary and bitfield promotions to the LHS's type.
1494 QualType LHSUnpromotedType = LHSType;
1495 if (LHSType->isPromotableIntegerType())
1496 LHSType = Context.getPromotedIntegerType(LHSType);
1497 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1498 if (!LHSBitfieldPromoteTy.isNull())
1499 LHSType = LHSBitfieldPromoteTy;
1500 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1501 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1502
1503 // If both types are identical, no conversion is needed.
1504 if (LHSType == RHSType)
1505 return LHSType;
1506
1507 // ExtInt types aren't subject to conversions between them or normal integers,
1508 // so this fails.
1509 if(LHSType->isExtIntType() || RHSType->isExtIntType())
1510 return QualType();
1511
1512 // At this point, we have two different arithmetic types.
1513
1514 // Diagnose attempts to convert between __float128 and long double where
1515 // such conversions currently can't be handled.
1516 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1517 return QualType();
1518
1519 // Handle complex types first (C99 6.3.1.8p1).
1520 if (LHSType->isComplexType() || RHSType->isComplexType())
1521 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1522 ACK == ACK_CompAssign);
1523
1524 // Now handle "real" floating types (i.e. float, double, long double).
1525 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1526 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1527 ACK == ACK_CompAssign);
1528
1529 // Handle GCC complex int extension.
1530 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1531 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1532 ACK == ACK_CompAssign);
1533
1534 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1535 return handleFixedPointConversion(*this, LHSType, RHSType);
1536
1537 // Finally, we have two differing integer types.
1538 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1539 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1540}
1541
1542//===----------------------------------------------------------------------===//
1543// Semantic Analysis for various Expression Types
1544//===----------------------------------------------------------------------===//
1545
1546
1547ExprResult
1548Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1549 SourceLocation DefaultLoc,
1550 SourceLocation RParenLoc,
1551 Expr *ControllingExpr,
1552 ArrayRef<ParsedType> ArgTypes,
1553 ArrayRef<Expr *> ArgExprs) {
1554 unsigned NumAssocs = ArgTypes.size();
1555 assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0)
: __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1555, __PRETTY_FUNCTION__))
;
1556
1557 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1558 for (unsigned i = 0; i < NumAssocs; ++i) {
1559 if (ArgTypes[i])
1560 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1561 else
1562 Types[i] = nullptr;
1563 }
1564
1565 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1566 ControllingExpr,
1567 llvm::makeArrayRef(Types, NumAssocs),
1568 ArgExprs);
1569 delete [] Types;
1570 return ER;
1571}
1572
1573ExprResult
1574Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1575 SourceLocation DefaultLoc,
1576 SourceLocation RParenLoc,
1577 Expr *ControllingExpr,
1578 ArrayRef<TypeSourceInfo *> Types,
1579 ArrayRef<Expr *> Exprs) {
1580 unsigned NumAssocs = Types.size();
1581 assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail
("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1581, __PRETTY_FUNCTION__))
;
1582
1583 // Decay and strip qualifiers for the controlling expression type, and handle
1584 // placeholder type replacement. See committee discussion from WG14 DR423.
1585 {
1586 EnterExpressionEvaluationContext Unevaluated(
1587 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1588 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1589 if (R.isInvalid())
1590 return ExprError();
1591 ControllingExpr = R.get();
1592 }
1593
1594 // The controlling expression is an unevaluated operand, so side effects are
1595 // likely unintended.
1596 if (!inTemplateInstantiation() &&
1597 ControllingExpr->HasSideEffects(Context, false))
1598 Diag(ControllingExpr->getExprLoc(),
1599 diag::warn_side_effects_unevaluated_context);
1600
1601 bool TypeErrorFound = false,
1602 IsResultDependent = ControllingExpr->isTypeDependent(),
1603 ContainsUnexpandedParameterPack
1604 = ControllingExpr->containsUnexpandedParameterPack();
1605
1606 for (unsigned i = 0; i < NumAssocs; ++i) {
1607 if (Exprs[i]->containsUnexpandedParameterPack())
1608 ContainsUnexpandedParameterPack = true;
1609
1610 if (Types[i]) {
1611 if (Types[i]->getType()->containsUnexpandedParameterPack())
1612 ContainsUnexpandedParameterPack = true;
1613
1614 if (Types[i]->getType()->isDependentType()) {
1615 IsResultDependent = true;
1616 } else {
1617 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1618 // complete object type other than a variably modified type."
1619 unsigned D = 0;
1620 if (Types[i]->getType()->isIncompleteType())
1621 D = diag::err_assoc_type_incomplete;
1622 else if (!Types[i]->getType()->isObjectType())
1623 D = diag::err_assoc_type_nonobject;
1624 else if (Types[i]->getType()->isVariablyModifiedType())
1625 D = diag::err_assoc_type_variably_modified;
1626
1627 if (D != 0) {
1628 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1629 << Types[i]->getTypeLoc().getSourceRange()
1630 << Types[i]->getType();
1631 TypeErrorFound = true;
1632 }
1633
1634 // C11 6.5.1.1p2 "No two generic associations in the same generic
1635 // selection shall specify compatible types."
1636 for (unsigned j = i+1; j < NumAssocs; ++j)
1637 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1638 Context.typesAreCompatible(Types[i]->getType(),
1639 Types[j]->getType())) {
1640 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1641 diag::err_assoc_compatible_types)
1642 << Types[j]->getTypeLoc().getSourceRange()
1643 << Types[j]->getType()
1644 << Types[i]->getType();
1645 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1646 diag::note_compat_assoc)
1647 << Types[i]->getTypeLoc().getSourceRange()
1648 << Types[i]->getType();
1649 TypeErrorFound = true;
1650 }
1651 }
1652 }
1653 }
1654 if (TypeErrorFound)
1655 return ExprError();
1656
1657 // If we determined that the generic selection is result-dependent, don't
1658 // try to compute the result expression.
1659 if (IsResultDependent)
1660 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1661 Exprs, DefaultLoc, RParenLoc,
1662 ContainsUnexpandedParameterPack);
1663
1664 SmallVector<unsigned, 1> CompatIndices;
1665 unsigned DefaultIndex = -1U;
1666 for (unsigned i = 0; i < NumAssocs; ++i) {
1667 if (!Types[i])
1668 DefaultIndex = i;
1669 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1670 Types[i]->getType()))
1671 CompatIndices.push_back(i);
1672 }
1673
1674 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1675 // type compatible with at most one of the types named in its generic
1676 // association list."
1677 if (CompatIndices.size() > 1) {
1678 // We strip parens here because the controlling expression is typically
1679 // parenthesized in macro definitions.
1680 ControllingExpr = ControllingExpr->IgnoreParens();
1681 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1682 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1683 << (unsigned)CompatIndices.size();
1684 for (unsigned I : CompatIndices) {
1685 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1686 diag::note_compat_assoc)
1687 << Types[I]->getTypeLoc().getSourceRange()
1688 << Types[I]->getType();
1689 }
1690 return ExprError();
1691 }
1692
1693 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1694 // its controlling expression shall have type compatible with exactly one of
1695 // the types named in its generic association list."
1696 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1697 // We strip parens here because the controlling expression is typically
1698 // parenthesized in macro definitions.
1699 ControllingExpr = ControllingExpr->IgnoreParens();
1700 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1701 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1702 return ExprError();
1703 }
1704
1705 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1706 // type name that is compatible with the type of the controlling expression,
1707 // then the result expression of the generic selection is the expression
1708 // in that generic association. Otherwise, the result expression of the
1709 // generic selection is the expression in the default generic association."
1710 unsigned ResultIndex =
1711 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1712
1713 return GenericSelectionExpr::Create(
1714 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1715 ContainsUnexpandedParameterPack, ResultIndex);
1716}
1717
1718/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1719/// location of the token and the offset of the ud-suffix within it.
1720static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1721 unsigned Offset) {
1722 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1723 S.getLangOpts());
1724}
1725
1726/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1727/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1728static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1729 IdentifierInfo *UDSuffix,
1730 SourceLocation UDSuffixLoc,
1731 ArrayRef<Expr*> Args,
1732 SourceLocation LitEndLoc) {
1733 assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator"
) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1733, __PRETTY_FUNCTION__))
;
1734
1735 QualType ArgTy[2];
1736 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1737 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1738 if (ArgTy[ArgIdx]->isArrayType())
1739 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1740 }
1741
1742 DeclarationName OpName =
1743 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1744 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1745 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1746
1747 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1748 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1749 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1750 /*AllowStringTemplate*/ false,
1751 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1752 return ExprError();
1753
1754 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1755}
1756
1757/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1758/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1759/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1760/// multiple tokens. However, the common case is that StringToks points to one
1761/// string.
1762///
1763ExprResult
1764Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1765 assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!"
) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1765, __PRETTY_FUNCTION__))
;
1766
1767 StringLiteralParser Literal(StringToks, PP);
1768 if (Literal.hadError)
1769 return ExprError();
1770
1771 SmallVector<SourceLocation, 4> StringTokLocs;
1772 for (const Token &Tok : StringToks)
1773 StringTokLocs.push_back(Tok.getLocation());
1774
1775 QualType CharTy = Context.CharTy;
1776 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1777 if (Literal.isWide()) {
1778 CharTy = Context.getWideCharType();
1779 Kind = StringLiteral::Wide;
1780 } else if (Literal.isUTF8()) {
1781 if (getLangOpts().Char8)
1782 CharTy = Context.Char8Ty;
1783 Kind = StringLiteral::UTF8;
1784 } else if (Literal.isUTF16()) {
1785 CharTy = Context.Char16Ty;
1786 Kind = StringLiteral::UTF16;
1787 } else if (Literal.isUTF32()) {
1788 CharTy = Context.Char32Ty;
1789 Kind = StringLiteral::UTF32;
1790 } else if (Literal.isPascal()) {
1791 CharTy = Context.UnsignedCharTy;
1792 }
1793
1794 // Warn on initializing an array of char from a u8 string literal; this
1795 // becomes ill-formed in C++2a.
1796 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1797 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1798 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1799
1800 // Create removals for all 'u8' prefixes in the string literal(s). This
1801 // ensures C++2a compatibility (but may change the program behavior when
1802 // built by non-Clang compilers for which the execution character set is
1803 // not always UTF-8).
1804 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1805 SourceLocation RemovalDiagLoc;
1806 for (const Token &Tok : StringToks) {
1807 if (Tok.getKind() == tok::utf8_string_literal) {
1808 if (RemovalDiagLoc.isInvalid())
1809 RemovalDiagLoc = Tok.getLocation();
1810 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1811 Tok.getLocation(),
1812 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1813 getSourceManager(), getLangOpts())));
1814 }
1815 }
1816 Diag(RemovalDiagLoc, RemovalDiag);
1817 }
1818
1819 QualType StrTy =
1820 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1821
1822 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1823 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1824 Kind, Literal.Pascal, StrTy,
1825 &StringTokLocs[0],
1826 StringTokLocs.size());
1827 if (Literal.getUDSuffix().empty())
1828 return Lit;
1829
1830 // We're building a user-defined literal.
1831 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1832 SourceLocation UDSuffixLoc =
1833 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1834 Literal.getUDSuffixOffset());
1835
1836 // Make sure we're allowed user-defined literals here.
1837 if (!UDLScope)
1838 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1839
1840 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1841 // operator "" X (str, len)
1842 QualType SizeType = Context.getSizeType();
1843
1844 DeclarationName OpName =
1845 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1846 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1847 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1848
1849 QualType ArgTy[] = {
1850 Context.getArrayDecayedType(StrTy), SizeType
1851 };
1852
1853 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1854 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1855 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1856 /*AllowStringTemplate*/ true,
1857 /*DiagnoseMissing*/ true)) {
1858
1859 case LOLR_Cooked: {
1860 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1861 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1862 StringTokLocs[0]);
1863 Expr *Args[] = { Lit, LenArg };
1864
1865 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1866 }
1867
1868 case LOLR_StringTemplate: {
1869 TemplateArgumentListInfo ExplicitArgs;
1870
1871 unsigned CharBits = Context.getIntWidth(CharTy);
1872 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1873 llvm::APSInt Value(CharBits, CharIsUnsigned);
1874
1875 TemplateArgument TypeArg(CharTy);
1876 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1877 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1878
1879 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1880 Value = Lit->getCodeUnit(I);
1881 TemplateArgument Arg(Context, Value, CharTy);
1882 TemplateArgumentLocInfo ArgInfo;
1883 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1884 }
1885 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1886 &ExplicitArgs);
1887 }
1888 case LOLR_Raw:
1889 case LOLR_Template:
1890 case LOLR_ErrorNoDiagnostic:
1891 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1891)
;
1892 case LOLR_Error:
1893 return ExprError();
1894 }
1895 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 1895)
;
1896}
1897
1898DeclRefExpr *
1899Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1900 SourceLocation Loc,
1901 const CXXScopeSpec *SS) {
1902 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1903 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1904}
1905
1906DeclRefExpr *
1907Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1908 const DeclarationNameInfo &NameInfo,
1909 const CXXScopeSpec *SS, NamedDecl *FoundD,
1910 SourceLocation TemplateKWLoc,
1911 const TemplateArgumentListInfo *TemplateArgs) {
1912 NestedNameSpecifierLoc NNS =
1913 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1914 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1915 TemplateArgs);
1916}
1917
1918NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1919 // A declaration named in an unevaluated operand never constitutes an odr-use.
1920 if (isUnevaluatedContext())
1921 return NOUR_Unevaluated;
1922
1923 // C++2a [basic.def.odr]p4:
1924 // A variable x whose name appears as a potentially-evaluated expression e
1925 // is odr-used by e unless [...] x is a reference that is usable in
1926 // constant expressions.
1927 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1928 if (VD->getType()->isReferenceType() &&
1929 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1930 VD->isUsableInConstantExpressions(Context))
1931 return NOUR_Constant;
1932 }
1933
1934 // All remaining non-variable cases constitute an odr-use. For variables, we
1935 // need to wait and see how the expression is used.
1936 return NOUR_None;
1937}
1938
1939/// BuildDeclRefExpr - Build an expression that references a
1940/// declaration that does not require a closure capture.
1941DeclRefExpr *
1942Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1943 const DeclarationNameInfo &NameInfo,
1944 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1945 SourceLocation TemplateKWLoc,
1946 const TemplateArgumentListInfo *TemplateArgs) {
1947 bool RefersToCapturedVariable =
1948 isa<VarDecl>(D) &&
1949 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1950
1951 DeclRefExpr *E = DeclRefExpr::Create(
1952 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1953 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1954 MarkDeclRefReferenced(E);
1955
1956 // C++ [except.spec]p17:
1957 // An exception-specification is considered to be needed when:
1958 // - in an expression, the function is the unique lookup result or
1959 // the selected member of a set of overloaded functions.
1960 //
1961 // We delay doing this until after we've built the function reference and
1962 // marked it as used so that:
1963 // a) if the function is defaulted, we get errors from defining it before /
1964 // instead of errors from computing its exception specification, and
1965 // b) if the function is a defaulted comparison, we can use the body we
1966 // build when defining it as input to the exception specification
1967 // computation rather than computing a new body.
1968 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1969 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1970 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1971 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1972 }
1973 }
1974
1975 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1976 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1977 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1978 getCurFunction()->recordUseOfWeak(E);
1979
1980 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1981 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1982 FD = IFD->getAnonField();
1983 if (FD) {
1984 UnusedPrivateFields.remove(FD);
1985 // Just in case we're building an illegal pointer-to-member.
1986 if (FD->isBitField())
1987 E->setObjectKind(OK_BitField);
1988 }
1989
1990 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1991 // designates a bit-field.
1992 if (auto *BD = dyn_cast<BindingDecl>(D))
1993 if (auto *BE = BD->getBinding())
1994 E->setObjectKind(BE->getObjectKind());
1995
1996 return E;
1997}
1998
1999/// Decomposes the given name into a DeclarationNameInfo, its location, and
2000/// possibly a list of template arguments.
2001///
2002/// If this produces template arguments, it is permitted to call
2003/// DecomposeTemplateName.
2004///
2005/// This actually loses a lot of source location information for
2006/// non-standard name kinds; we should consider preserving that in
2007/// some way.
2008void
2009Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2010 TemplateArgumentListInfo &Buffer,
2011 DeclarationNameInfo &NameInfo,
2012 const TemplateArgumentListInfo *&TemplateArgs) {
2013 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2014 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2015 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2016
2017 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2018 Id.TemplateId->NumArgs);
2019 translateTemplateArguments(TemplateArgsPtr, Buffer);
2020
2021 TemplateName TName = Id.TemplateId->Template.get();
2022 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2023 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2024 TemplateArgs = &Buffer;
2025 } else {
2026 NameInfo = GetNameFromUnqualifiedId(Id);
2027 TemplateArgs = nullptr;
2028 }
2029}
2030
2031static void emitEmptyLookupTypoDiagnostic(
2032 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2033 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2034 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2035 DeclContext *Ctx =
2036 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2037 if (!TC) {
2038 // Emit a special diagnostic for failed member lookups.
2039 // FIXME: computing the declaration context might fail here (?)
2040 if (Ctx)
2041 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2042 << SS.getRange();
2043 else
2044 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2045 return;
2046 }
2047
2048 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2049 bool DroppedSpecifier =
2050 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2051 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2052 ? diag::note_implicit_param_decl
2053 : diag::note_previous_decl;
2054 if (!Ctx)
2055 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2056 SemaRef.PDiag(NoteID));
2057 else
2058 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2059 << Typo << Ctx << DroppedSpecifier
2060 << SS.getRange(),
2061 SemaRef.PDiag(NoteID));
2062}
2063
2064/// Diagnose an empty lookup.
2065///
2066/// \return false if new lookup candidates were found
2067bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2068 CorrectionCandidateCallback &CCC,
2069 TemplateArgumentListInfo *ExplicitTemplateArgs,
2070 ArrayRef<Expr *> Args, TypoExpr **Out) {
2071 DeclarationName Name = R.getLookupName();
2072
2073 unsigned diagnostic = diag::err_undeclared_var_use;
2074 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2075 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2076 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2077 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2078 diagnostic = diag::err_undeclared_use;
2079 diagnostic_suggest = diag::err_undeclared_use_suggest;
2080 }
2081
2082 // If the original lookup was an unqualified lookup, fake an
2083 // unqualified lookup. This is useful when (for example) the
2084 // original lookup would not have found something because it was a
2085 // dependent name.
2086 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2087 while (DC) {
2088 if (isa<CXXRecordDecl>(DC)) {
2089 LookupQualifiedName(R, DC);
2090
2091 if (!R.empty()) {
2092 // Don't give errors about ambiguities in this lookup.
2093 R.suppressDiagnostics();
2094
2095 // During a default argument instantiation the CurContext points
2096 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2097 // function parameter list, hence add an explicit check.
2098 bool isDefaultArgument =
2099 !CodeSynthesisContexts.empty() &&
2100 CodeSynthesisContexts.back().Kind ==
2101 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2102 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2103 bool isInstance = CurMethod &&
2104 CurMethod->isInstance() &&
2105 DC == CurMethod->getParent() && !isDefaultArgument;
2106
2107 // Give a code modification hint to insert 'this->'.
2108 // TODO: fixit for inserting 'Base<T>::' in the other cases.
2109 // Actually quite difficult!
2110 if (getLangOpts().MSVCCompat)
2111 diagnostic = diag::ext_found_via_dependent_bases_lookup;
2112 if (isInstance) {
2113 Diag(R.getNameLoc(), diagnostic) << Name
2114 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2115 CheckCXXThisCapture(R.getNameLoc());
2116 } else {
2117 Diag(R.getNameLoc(), diagnostic) << Name;
2118 }
2119
2120 // Do we really want to note all of these?
2121 for (NamedDecl *D : R)
2122 Diag(D->getLocation(), diag::note_dependent_var_use);
2123
2124 // Return true if we are inside a default argument instantiation
2125 // and the found name refers to an instance member function, otherwise
2126 // the function calling DiagnoseEmptyLookup will try to create an
2127 // implicit member call and this is wrong for default argument.
2128 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2129 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2130 return true;
2131 }
2132
2133 // Tell the callee to try to recover.
2134 return false;
2135 }
2136
2137 R.clear();
2138 }
2139
2140 DC = DC->getLookupParent();
2141 }
2142
2143 // We didn't find anything, so try to correct for a typo.
2144 TypoCorrection Corrected;
2145 if (S && Out) {
2146 SourceLocation TypoLoc = R.getNameLoc();
2147 assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2148, __PRETTY_FUNCTION__))
2148 "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2148, __PRETTY_FUNCTION__))
;
2149 *Out = CorrectTypoDelayed(
2150 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2151 [=](const TypoCorrection &TC) {
2152 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2153 diagnostic, diagnostic_suggest);
2154 },
2155 nullptr, CTK_ErrorRecovery);
2156 if (*Out)
2157 return true;
2158 } else if (S &&
2159 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2160 S, &SS, CCC, CTK_ErrorRecovery))) {
2161 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2162 bool DroppedSpecifier =
2163 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2164 R.setLookupName(Corrected.getCorrection());
2165
2166 bool AcceptableWithRecovery = false;
2167 bool AcceptableWithoutRecovery = false;
2168 NamedDecl *ND = Corrected.getFoundDecl();
2169 if (ND) {
2170 if (Corrected.isOverloaded()) {
2171 OverloadCandidateSet OCS(R.getNameLoc(),
2172 OverloadCandidateSet::CSK_Normal);
2173 OverloadCandidateSet::iterator Best;
2174 for (NamedDecl *CD : Corrected) {
2175 if (FunctionTemplateDecl *FTD =
2176 dyn_cast<FunctionTemplateDecl>(CD))
2177 AddTemplateOverloadCandidate(
2178 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2179 Args, OCS);
2180 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2181 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2182 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2183 Args, OCS);
2184 }
2185 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2186 case OR_Success:
2187 ND = Best->FoundDecl;
2188 Corrected.setCorrectionDecl(ND);
2189 break;
2190 default:
2191 // FIXME: Arbitrarily pick the first declaration for the note.
2192 Corrected.setCorrectionDecl(ND);
2193 break;
2194 }
2195 }
2196 R.addDecl(ND);
2197 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2198 CXXRecordDecl *Record = nullptr;
2199 if (Corrected.getCorrectionSpecifier()) {
2200 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2201 Record = Ty->getAsCXXRecordDecl();
2202 }
2203 if (!Record)
2204 Record = cast<CXXRecordDecl>(
2205 ND->getDeclContext()->getRedeclContext());
2206 R.setNamingClass(Record);
2207 }
2208
2209 auto *UnderlyingND = ND->getUnderlyingDecl();
2210 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2211 isa<FunctionTemplateDecl>(UnderlyingND);
2212 // FIXME: If we ended up with a typo for a type name or
2213 // Objective-C class name, we're in trouble because the parser
2214 // is in the wrong place to recover. Suggest the typo
2215 // correction, but don't make it a fix-it since we're not going
2216 // to recover well anyway.
2217 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2218 getAsTypeTemplateDecl(UnderlyingND) ||
2219 isa<ObjCInterfaceDecl>(UnderlyingND);
2220 } else {
2221 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2222 // because we aren't able to recover.
2223 AcceptableWithoutRecovery = true;
2224 }
2225
2226 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2227 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2228 ? diag::note_implicit_param_decl
2229 : diag::note_previous_decl;
2230 if (SS.isEmpty())
2231 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2232 PDiag(NoteID), AcceptableWithRecovery);
2233 else
2234 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2235 << Name << computeDeclContext(SS, false)
2236 << DroppedSpecifier << SS.getRange(),
2237 PDiag(NoteID), AcceptableWithRecovery);
2238
2239 // Tell the callee whether to try to recover.
2240 return !AcceptableWithRecovery;
2241 }
2242 }
2243 R.clear();
2244
2245 // Emit a special diagnostic for failed member lookups.
2246 // FIXME: computing the declaration context might fail here (?)
2247 if (!SS.isEmpty()) {
2248 Diag(R.getNameLoc(), diag::err_no_member)
2249 << Name << computeDeclContext(SS, false)
2250 << SS.getRange();
2251 return true;
2252 }
2253
2254 // Give up, we can't recover.
2255 Diag(R.getNameLoc(), diagnostic) << Name;
2256 return true;
2257}
2258
2259/// In Microsoft mode, if we are inside a template class whose parent class has
2260/// dependent base classes, and we can't resolve an unqualified identifier, then
2261/// assume the identifier is a member of a dependent base class. We can only
2262/// recover successfully in static methods, instance methods, and other contexts
2263/// where 'this' is available. This doesn't precisely match MSVC's
2264/// instantiation model, but it's close enough.
2265static Expr *
2266recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2267 DeclarationNameInfo &NameInfo,
2268 SourceLocation TemplateKWLoc,
2269 const TemplateArgumentListInfo *TemplateArgs) {
2270 // Only try to recover from lookup into dependent bases in static methods or
2271 // contexts where 'this' is available.
2272 QualType ThisType = S.getCurrentThisType();
2273 const CXXRecordDecl *RD = nullptr;
2274 if (!ThisType.isNull())
2275 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2276 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2277 RD = MD->getParent();
2278 if (!RD || !RD->hasAnyDependentBases())
2279 return nullptr;
2280
2281 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2282 // is available, suggest inserting 'this->' as a fixit.
2283 SourceLocation Loc = NameInfo.getLoc();
2284 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2285 DB << NameInfo.getName() << RD;
2286
2287 if (!ThisType.isNull()) {
2288 DB << FixItHint::CreateInsertion(Loc, "this->");
2289 return CXXDependentScopeMemberExpr::Create(
2290 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2291 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2292 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2293 }
2294
2295 // Synthesize a fake NNS that points to the derived class. This will
2296 // perform name lookup during template instantiation.
2297 CXXScopeSpec SS;
2298 auto *NNS =
2299 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2300 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2301 return DependentScopeDeclRefExpr::Create(
2302 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2303 TemplateArgs);
2304}
2305
2306ExprResult
2307Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2308 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2309 bool HasTrailingLParen, bool IsAddressOfOperand,
2310 CorrectionCandidateCallback *CCC,
2311 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2312 assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2313, __PRETTY_FUNCTION__))
2313 "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2313, __PRETTY_FUNCTION__))
;
2314 if (SS.isInvalid())
2315 return ExprError();
2316
2317 TemplateArgumentListInfo TemplateArgsBuffer;
2318
2319 // Decompose the UnqualifiedId into the following data.
2320 DeclarationNameInfo NameInfo;
2321 const TemplateArgumentListInfo *TemplateArgs;
2322 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2323
2324 DeclarationName Name = NameInfo.getName();
2325 IdentifierInfo *II = Name.getAsIdentifierInfo();
2326 SourceLocation NameLoc = NameInfo.getLoc();
2327
2328 if (II && II->isEditorPlaceholder()) {
2329 // FIXME: When typed placeholders are supported we can create a typed
2330 // placeholder expression node.
2331 return ExprError();
2332 }
2333
2334 // C++ [temp.dep.expr]p3:
2335 // An id-expression is type-dependent if it contains:
2336 // -- an identifier that was declared with a dependent type,
2337 // (note: handled after lookup)
2338 // -- a template-id that is dependent,
2339 // (note: handled in BuildTemplateIdExpr)
2340 // -- a conversion-function-id that specifies a dependent type,
2341 // -- a nested-name-specifier that contains a class-name that
2342 // names a dependent type.
2343 // Determine whether this is a member of an unknown specialization;
2344 // we need to handle these differently.
2345 bool DependentID = false;
2346 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2347 Name.getCXXNameType()->isDependentType()) {
2348 DependentID = true;
2349 } else if (SS.isSet()) {
2350 if (DeclContext *DC = computeDeclContext(SS, false)) {
2351 if (RequireCompleteDeclContext(SS, DC))
2352 return ExprError();
2353 } else {
2354 DependentID = true;
2355 }
2356 }
2357
2358 if (DependentID)
2359 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2360 IsAddressOfOperand, TemplateArgs);
2361
2362 // Perform the required lookup.
2363 LookupResult R(*this, NameInfo,
2364 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2365 ? LookupObjCImplicitSelfParam
2366 : LookupOrdinaryName);
2367 if (TemplateKWLoc.isValid() || TemplateArgs) {
2368 // Lookup the template name again to correctly establish the context in
2369 // which it was found. This is really unfortunate as we already did the
2370 // lookup to determine that it was a template name in the first place. If
2371 // this becomes a performance hit, we can work harder to preserve those
2372 // results until we get here but it's likely not worth it.
2373 bool MemberOfUnknownSpecialization;
2374 AssumedTemplateKind AssumedTemplate;
2375 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2376 MemberOfUnknownSpecialization, TemplateKWLoc,
2377 &AssumedTemplate))
2378 return ExprError();
2379
2380 if (MemberOfUnknownSpecialization ||
2381 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2382 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2383 IsAddressOfOperand, TemplateArgs);
2384 } else {
2385 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2386 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2387
2388 // If the result might be in a dependent base class, this is a dependent
2389 // id-expression.
2390 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2391 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2392 IsAddressOfOperand, TemplateArgs);
2393
2394 // If this reference is in an Objective-C method, then we need to do
2395 // some special Objective-C lookup, too.
2396 if (IvarLookupFollowUp) {
2397 ExprResult E(LookupInObjCMethod(R, S, II, true));
2398 if (E.isInvalid())
2399 return ExprError();
2400
2401 if (Expr *Ex = E.getAs<Expr>())
2402 return Ex;
2403 }
2404 }
2405
2406 if (R.isAmbiguous())
2407 return ExprError();
2408
2409 // This could be an implicitly declared function reference (legal in C90,
2410 // extension in C99, forbidden in C++).
2411 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2412 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2413 if (D) R.addDecl(D);
2414 }
2415
2416 // Determine whether this name might be a candidate for
2417 // argument-dependent lookup.
2418 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2419
2420 if (R.empty() && !ADL) {
2421 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2422 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2423 TemplateKWLoc, TemplateArgs))
2424 return E;
2425 }
2426
2427 // Don't diagnose an empty lookup for inline assembly.
2428 if (IsInlineAsmIdentifier)
2429 return ExprError();
2430
2431 // If this name wasn't predeclared and if this is not a function
2432 // call, diagnose the problem.
2433 TypoExpr *TE = nullptr;
2434 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2435 : nullptr);
2436 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2437 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2438, __PRETTY_FUNCTION__))
2438 "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2438, __PRETTY_FUNCTION__))
;
2439 if (CCC) {
2440 // Make sure the callback knows what the typo being diagnosed is.
2441 CCC->setTypoName(II);
2442 if (SS.isValid())
2443 CCC->setTypoNNS(SS.getScopeRep());
2444 }
2445 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2446 // a template name, but we happen to have always already looked up the name
2447 // before we get here if it must be a template name.
2448 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2449 None, &TE)) {
2450 if (TE && KeywordReplacement) {
2451 auto &State = getTypoExprState(TE);
2452 auto BestTC = State.Consumer->getNextCorrection();
2453 if (BestTC.isKeyword()) {
2454 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2455 if (State.DiagHandler)
2456 State.DiagHandler(BestTC);
2457 KeywordReplacement->startToken();
2458 KeywordReplacement->setKind(II->getTokenID());
2459 KeywordReplacement->setIdentifierInfo(II);
2460 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2461 // Clean up the state associated with the TypoExpr, since it has
2462 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2463 clearDelayedTypo(TE);
2464 // Signal that a correction to a keyword was performed by returning a
2465 // valid-but-null ExprResult.
2466 return (Expr*)nullptr;
2467 }
2468 State.Consumer->resetCorrectionStream();
2469 }
2470 return TE ? TE : ExprError();
2471 }
2472
2473 assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2474, __PRETTY_FUNCTION__))
2474 "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2474, __PRETTY_FUNCTION__))
;
2475
2476 // If we found an Objective-C instance variable, let
2477 // LookupInObjCMethod build the appropriate expression to
2478 // reference the ivar.
2479 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2480 R.clear();
2481 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2482 // In a hopelessly buggy code, Objective-C instance variable
2483 // lookup fails and no expression will be built to reference it.
2484 if (!E.isInvalid() && !E.get())
2485 return ExprError();
2486 return E;
2487 }
2488 }
2489
2490 // This is guaranteed from this point on.
2491 assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail
("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2491, __PRETTY_FUNCTION__))
;
2492
2493 // Check whether this might be a C++ implicit instance member access.
2494 // C++ [class.mfct.non-static]p3:
2495 // When an id-expression that is not part of a class member access
2496 // syntax and not used to form a pointer to member is used in the
2497 // body of a non-static member function of class X, if name lookup
2498 // resolves the name in the id-expression to a non-static non-type
2499 // member of some class C, the id-expression is transformed into a
2500 // class member access expression using (*this) as the
2501 // postfix-expression to the left of the . operator.
2502 //
2503 // But we don't actually need to do this for '&' operands if R
2504 // resolved to a function or overloaded function set, because the
2505 // expression is ill-formed if it actually works out to be a
2506 // non-static member function:
2507 //
2508 // C++ [expr.ref]p4:
2509 // Otherwise, if E1.E2 refers to a non-static member function. . .
2510 // [t]he expression can be used only as the left-hand operand of a
2511 // member function call.
2512 //
2513 // There are other safeguards against such uses, but it's important
2514 // to get this right here so that we don't end up making a
2515 // spuriously dependent expression if we're inside a dependent
2516 // instance method.
2517 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2518 bool MightBeImplicitMember;
2519 if (!IsAddressOfOperand)
2520 MightBeImplicitMember = true;
2521 else if (!SS.isEmpty())
2522 MightBeImplicitMember = false;
2523 else if (R.isOverloadedResult())
2524 MightBeImplicitMember = false;
2525 else if (R.isUnresolvableResult())
2526 MightBeImplicitMember = true;
2527 else
2528 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2529 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2530 isa<MSPropertyDecl>(R.getFoundDecl());
2531
2532 if (MightBeImplicitMember)
2533 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2534 R, TemplateArgs, S);
2535 }
2536
2537 if (TemplateArgs || TemplateKWLoc.isValid()) {
2538
2539 // In C++1y, if this is a variable template id, then check it
2540 // in BuildTemplateIdExpr().
2541 // The single lookup result must be a variable template declaration.
2542 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2543 Id.TemplateId->Kind == TNK_Var_template) {
2544 assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2545, __PRETTY_FUNCTION__))
2545 "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2545, __PRETTY_FUNCTION__))
;
2546 }
2547
2548 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2549 }
2550
2551 return BuildDeclarationNameExpr(SS, R, ADL);
2552}
2553
2554/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2555/// declaration name, generally during template instantiation.
2556/// There's a large number of things which don't need to be done along
2557/// this path.
2558ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2559 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2560 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2561 DeclContext *DC = computeDeclContext(SS, false);
2562 if (!DC)
2563 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2564 NameInfo, /*TemplateArgs=*/nullptr);
2565
2566 if (RequireCompleteDeclContext(SS, DC))
2567 return ExprError();
2568
2569 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2570 LookupQualifiedName(R, DC);
2571
2572 if (R.isAmbiguous())
2573 return ExprError();
2574
2575 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2576 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2577 NameInfo, /*TemplateArgs=*/nullptr);
2578
2579 if (R.empty()) {
2580 Diag(NameInfo.getLoc(), diag::err_no_member)
2581 << NameInfo.getName() << DC << SS.getRange();
2582 return ExprError();
2583 }
2584
2585 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2586 // Diagnose a missing typename if this resolved unambiguously to a type in
2587 // a dependent context. If we can recover with a type, downgrade this to
2588 // a warning in Microsoft compatibility mode.
2589 unsigned DiagID = diag::err_typename_missing;
2590 if (RecoveryTSI && getLangOpts().MSVCCompat)
2591 DiagID = diag::ext_typename_missing;
2592 SourceLocation Loc = SS.getBeginLoc();
2593 auto D = Diag(Loc, DiagID);
2594 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2595 << SourceRange(Loc, NameInfo.getEndLoc());
2596
2597 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2598 // context.
2599 if (!RecoveryTSI)
2600 return ExprError();
2601
2602 // Only issue the fixit if we're prepared to recover.
2603 D << FixItHint::CreateInsertion(Loc, "typename ");
2604
2605 // Recover by pretending this was an elaborated type.
2606 QualType Ty = Context.getTypeDeclType(TD);
2607 TypeLocBuilder TLB;
2608 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2609
2610 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2611 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2612 QTL.setElaboratedKeywordLoc(SourceLocation());
2613 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2614
2615 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2616
2617 return ExprEmpty();
2618 }
2619
2620 // Defend against this resolving to an implicit member access. We usually
2621 // won't get here if this might be a legitimate a class member (we end up in
2622 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2623 // a pointer-to-member or in an unevaluated context in C++11.
2624 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2625 return BuildPossibleImplicitMemberExpr(SS,
2626 /*TemplateKWLoc=*/SourceLocation(),
2627 R, /*TemplateArgs=*/nullptr, S);
2628
2629 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2630}
2631
2632/// The parser has read a name in, and Sema has detected that we're currently
2633/// inside an ObjC method. Perform some additional checks and determine if we
2634/// should form a reference to an ivar.
2635///
2636/// Ideally, most of this would be done by lookup, but there's
2637/// actually quite a lot of extra work involved.
2638DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2639 IdentifierInfo *II) {
2640 SourceLocation Loc = Lookup.getNameLoc();
2641 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2642
2643 // Check for error condition which is already reported.
2644 if (!CurMethod)
2645 return DeclResult(true);
2646
2647 // There are two cases to handle here. 1) scoped lookup could have failed,
2648 // in which case we should look for an ivar. 2) scoped lookup could have
2649 // found a decl, but that decl is outside the current instance method (i.e.
2650 // a global variable). In these two cases, we do a lookup for an ivar with
2651 // this name, if the lookup sucedes, we replace it our current decl.
2652
2653 // If we're in a class method, we don't normally want to look for
2654 // ivars. But if we don't find anything else, and there's an
2655 // ivar, that's an error.
2656 bool IsClassMethod = CurMethod->isClassMethod();
2657
2658 bool LookForIvars;
2659 if (Lookup.empty())
2660 LookForIvars = true;
2661 else if (IsClassMethod)
2662 LookForIvars = false;
2663 else
2664 LookForIvars = (Lookup.isSingleResult() &&
2665 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2666 ObjCInterfaceDecl *IFace = nullptr;
2667 if (LookForIvars) {
2668 IFace = CurMethod->getClassInterface();
2669 ObjCInterfaceDecl *ClassDeclared;
2670 ObjCIvarDecl *IV = nullptr;
2671 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2672 // Diagnose using an ivar in a class method.
2673 if (IsClassMethod) {
2674 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2675 return DeclResult(true);
2676 }
2677
2678 // Diagnose the use of an ivar outside of the declaring class.
2679 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2680 !declaresSameEntity(ClassDeclared, IFace) &&
2681 !getLangOpts().DebuggerSupport)
2682 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2683
2684 // Success.
2685 return IV;
2686 }
2687 } else if (CurMethod->isInstanceMethod()) {
2688 // We should warn if a local variable hides an ivar.
2689 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2690 ObjCInterfaceDecl *ClassDeclared;
2691 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2692 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2693 declaresSameEntity(IFace, ClassDeclared))
2694 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2695 }
2696 }
2697 } else if (Lookup.isSingleResult() &&
2698 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2699 // If accessing a stand-alone ivar in a class method, this is an error.
2700 if (const ObjCIvarDecl *IV =
2701 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2702 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2703 return DeclResult(true);
2704 }
2705 }
2706
2707 // Didn't encounter an error, didn't find an ivar.
2708 return DeclResult(false);
2709}
2710
2711ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2712 ObjCIvarDecl *IV) {
2713 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2714 assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2715, __PRETTY_FUNCTION__))
2715 "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2715, __PRETTY_FUNCTION__))
;
2716
2717 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2718 assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context"
) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2718, __PRETTY_FUNCTION__))
;
2719
2720 // If we're referencing an invalid decl, just return this as a silent
2721 // error node. The error diagnostic was already emitted on the decl.
2722 if (IV->isInvalidDecl())
2723 return ExprError();
2724
2725 // Check if referencing a field with __attribute__((deprecated)).
2726 if (DiagnoseUseOfDecl(IV, Loc))
2727 return ExprError();
2728
2729 // FIXME: This should use a new expr for a direct reference, don't
2730 // turn this into Self->ivar, just return a BareIVarExpr or something.
2731 IdentifierInfo &II = Context.Idents.get("self");
2732 UnqualifiedId SelfName;
2733 SelfName.setIdentifier(&II, SourceLocation());
2734 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2735 CXXScopeSpec SelfScopeSpec;
2736 SourceLocation TemplateKWLoc;
2737 ExprResult SelfExpr =
2738 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2739 /*HasTrailingLParen=*/false,
2740 /*IsAddressOfOperand=*/false);
2741 if (SelfExpr.isInvalid())
2742 return ExprError();
2743
2744 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2745 if (SelfExpr.isInvalid())
2746 return ExprError();
2747
2748 MarkAnyDeclReferenced(Loc, IV, true);
2749
2750 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2751 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2752 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2753 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2754
2755 ObjCIvarRefExpr *Result = new (Context)
2756 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2757 IV->getLocation(), SelfExpr.get(), true, true);
2758
2759 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2760 if (!isUnevaluatedContext() &&
2761 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2762 getCurFunction()->recordUseOfWeak(Result);
2763 }
2764 if (getLangOpts().ObjCAutoRefCount)
2765 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2766 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2767
2768 return Result;
2769}
2770
2771/// The parser has read a name in, and Sema has detected that we're currently
2772/// inside an ObjC method. Perform some additional checks and determine if we
2773/// should form a reference to an ivar. If so, build an expression referencing
2774/// that ivar.
2775ExprResult
2776Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2777 IdentifierInfo *II, bool AllowBuiltinCreation) {
2778 // FIXME: Integrate this lookup step into LookupParsedName.
2779 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2780 if (Ivar.isInvalid())
2781 return ExprError();
2782 if (Ivar.isUsable())
2783 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2784 cast<ObjCIvarDecl>(Ivar.get()));
2785
2786 if (Lookup.empty() && II && AllowBuiltinCreation)
2787 LookupBuiltin(Lookup);
2788
2789 // Sentinel value saying that we didn't do anything special.
2790 return ExprResult(false);
2791}
2792
2793/// Cast a base object to a member's actual type.
2794///
2795/// Logically this happens in three phases:
2796///
2797/// * First we cast from the base type to the naming class.
2798/// The naming class is the class into which we were looking
2799/// when we found the member; it's the qualifier type if a
2800/// qualifier was provided, and otherwise it's the base type.
2801///
2802/// * Next we cast from the naming class to the declaring class.
2803/// If the member we found was brought into a class's scope by
2804/// a using declaration, this is that class; otherwise it's
2805/// the class declaring the member.
2806///
2807/// * Finally we cast from the declaring class to the "true"
2808/// declaring class of the member. This conversion does not
2809/// obey access control.
2810ExprResult
2811Sema::PerformObjectMemberConversion(Expr *From,
2812 NestedNameSpecifier *Qualifier,
2813 NamedDecl *FoundDecl,
2814 NamedDecl *Member) {
2815 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2816 if (!RD)
2817 return From;
2818
2819 QualType DestRecordType;
2820 QualType DestType;
2821 QualType FromRecordType;
2822 QualType FromType = From->getType();
2823 bool PointerConversions = false;
2824 if (isa<FieldDecl>(Member)) {
2825 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2826 auto FromPtrType = FromType->getAs<PointerType>();
2827 DestRecordType = Context.getAddrSpaceQualType(
2828 DestRecordType, FromPtrType
2829 ? FromType->getPointeeType().getAddressSpace()
2830 : FromType.getAddressSpace());
2831
2832 if (FromPtrType) {
2833 DestType = Context.getPointerType(DestRecordType);
2834 FromRecordType = FromPtrType->getPointeeType();
2835 PointerConversions = true;
2836 } else {
2837 DestType = DestRecordType;
2838 FromRecordType = FromType;
2839 }
2840 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2841 if (Method->isStatic())
2842 return From;
2843
2844 DestType = Method->getThisType();
2845 DestRecordType = DestType->getPointeeType();
2846
2847 if (FromType->getAs<PointerType>()) {
2848 FromRecordType = FromType->getPointeeType();
2849 PointerConversions = true;
2850 } else {
2851 FromRecordType = FromType;
2852 DestType = DestRecordType;
2853 }
2854
2855 LangAS FromAS = FromRecordType.getAddressSpace();
2856 LangAS DestAS = DestRecordType.getAddressSpace();
2857 if (FromAS != DestAS) {
2858 QualType FromRecordTypeWithoutAS =
2859 Context.removeAddrSpaceQualType(FromRecordType);
2860 QualType FromTypeWithDestAS =
2861 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2862 if (PointerConversions)
2863 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2864 From = ImpCastExprToType(From, FromTypeWithDestAS,
2865 CK_AddressSpaceConversion, From->getValueKind())
2866 .get();
2867 }
2868 } else {
2869 // No conversion necessary.
2870 return From;
2871 }
2872
2873 if (DestType->isDependentType() || FromType->isDependentType())
2874 return From;
2875
2876 // If the unqualified types are the same, no conversion is necessary.
2877 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2878 return From;
2879
2880 SourceRange FromRange = From->getSourceRange();
2881 SourceLocation FromLoc = FromRange.getBegin();
2882
2883 ExprValueKind VK = From->getValueKind();
2884
2885 // C++ [class.member.lookup]p8:
2886 // [...] Ambiguities can often be resolved by qualifying a name with its
2887 // class name.
2888 //
2889 // If the member was a qualified name and the qualified referred to a
2890 // specific base subobject type, we'll cast to that intermediate type
2891 // first and then to the object in which the member is declared. That allows
2892 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2893 //
2894 // class Base { public: int x; };
2895 // class Derived1 : public Base { };
2896 // class Derived2 : public Base { };
2897 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2898 //
2899 // void VeryDerived::f() {
2900 // x = 17; // error: ambiguous base subobjects
2901 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2902 // }
2903 if (Qualifier && Qualifier->getAsType()) {
2904 QualType QType = QualType(Qualifier->getAsType(), 0);
2905 assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type"
) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2905, __PRETTY_FUNCTION__))
;
2906
2907 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2908
2909 // In C++98, the qualifier type doesn't actually have to be a base
2910 // type of the object type, in which case we just ignore it.
2911 // Otherwise build the appropriate casts.
2912 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2913 CXXCastPath BasePath;
2914 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2915 FromLoc, FromRange, &BasePath))
2916 return ExprError();
2917
2918 if (PointerConversions)
2919 QType = Context.getPointerType(QType);
2920 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2921 VK, &BasePath).get();
2922
2923 FromType = QType;
2924 FromRecordType = QRecordType;
2925
2926 // If the qualifier type was the same as the destination type,
2927 // we're done.
2928 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2929 return From;
2930 }
2931 }
2932
2933 bool IgnoreAccess = false;
2934
2935 // If we actually found the member through a using declaration, cast
2936 // down to the using declaration's type.
2937 //
2938 // Pointer equality is fine here because only one declaration of a
2939 // class ever has member declarations.
2940 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2941 assert(isa<UsingShadowDecl>(FoundDecl))((isa<UsingShadowDecl>(FoundDecl)) ? static_cast<void
> (0) : __assert_fail ("isa<UsingShadowDecl>(FoundDecl)"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2941, __PRETTY_FUNCTION__))
;
2942 QualType URecordType = Context.getTypeDeclType(
2943 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2944
2945 // We only need to do this if the naming-class to declaring-class
2946 // conversion is non-trivial.
2947 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2948 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType))((IsDerivedFrom(FromLoc, FromRecordType, URecordType)) ? static_cast
<void> (0) : __assert_fail ("IsDerivedFrom(FromLoc, FromRecordType, URecordType)"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 2948, __PRETTY_FUNCTION__))
;
2949 CXXCastPath BasePath;
2950 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2951 FromLoc, FromRange, &BasePath))
2952 return ExprError();
2953
2954 QualType UType = URecordType;
2955 if (PointerConversions)
2956 UType = Context.getPointerType(UType);
2957 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2958 VK, &BasePath).get();
2959 FromType = UType;
2960 FromRecordType = URecordType;
2961 }
2962
2963 // We don't do access control for the conversion from the
2964 // declaring class to the true declaring class.
2965 IgnoreAccess = true;
2966 }
2967
2968 CXXCastPath BasePath;
2969 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2970 FromLoc, FromRange, &BasePath,
2971 IgnoreAccess))
2972 return ExprError();
2973
2974 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2975 VK, &BasePath);
2976}
2977
2978bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2979 const LookupResult &R,
2980 bool HasTrailingLParen) {
2981 // Only when used directly as the postfix-expression of a call.
2982 if (!HasTrailingLParen)
2983 return false;
2984
2985 // Never if a scope specifier was provided.
2986 if (SS.isSet())
2987 return false;
2988
2989 // Only in C++ or ObjC++.
2990 if (!getLangOpts().CPlusPlus)
2991 return false;
2992
2993 // Turn off ADL when we find certain kinds of declarations during
2994 // normal lookup:
2995 for (NamedDecl *D : R) {
2996 // C++0x [basic.lookup.argdep]p3:
2997 // -- a declaration of a class member
2998 // Since using decls preserve this property, we check this on the
2999 // original decl.
3000 if (D->isCXXClassMember())
3001 return false;
3002
3003 // C++0x [basic.lookup.argdep]p3:
3004 // -- a block-scope function declaration that is not a
3005 // using-declaration
3006 // NOTE: we also trigger this for function templates (in fact, we
3007 // don't check the decl type at all, since all other decl types
3008 // turn off ADL anyway).
3009 if (isa<UsingShadowDecl>(D))
3010 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3011 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3012 return false;
3013
3014 // C++0x [basic.lookup.argdep]p3:
3015 // -- a declaration that is neither a function or a function
3016 // template
3017 // And also for builtin functions.
3018 if (isa<FunctionDecl>(D)) {
3019 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3020
3021 // But also builtin functions.
3022 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3023 return false;
3024 } else if (!isa<FunctionTemplateDecl>(D))
3025 return false;
3026 }
3027
3028 return true;
3029}
3030
3031
3032/// Diagnoses obvious problems with the use of the given declaration
3033/// as an expression. This is only actually called for lookups that
3034/// were not overloaded, and it doesn't promise that the declaration
3035/// will in fact be used.
3036static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3037 if (D->isInvalidDecl())
3038 return true;
3039
3040 if (isa<TypedefNameDecl>(D)) {
3041 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3042 return true;
3043 }
3044
3045 if (isa<ObjCInterfaceDecl>(D)) {
3046 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3047 return true;
3048 }
3049
3050 if (isa<NamespaceDecl>(D)) {
3051 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3052 return true;
3053 }
3054
3055 return false;
3056}
3057
3058// Certain multiversion types should be treated as overloaded even when there is
3059// only one result.
3060static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3061 assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result"
) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3061, __PRETTY_FUNCTION__))
;
3062 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3063 return FD &&
3064 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3065}
3066
3067ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3068 LookupResult &R, bool NeedsADL,
3069 bool AcceptInvalidDecl) {
3070 // If this is a single, fully-resolved result and we don't need ADL,
3071 // just build an ordinary singleton decl ref.
3072 if (!NeedsADL && R.isSingleResult() &&
3073 !R.getAsSingle<FunctionTemplateDecl>() &&
3074 !ShouldLookupResultBeMultiVersionOverload(R))
3075 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3076 R.getRepresentativeDecl(), nullptr,
3077 AcceptInvalidDecl);
3078
3079 // We only need to check the declaration if there's exactly one
3080 // result, because in the overloaded case the results can only be
3081 // functions and function templates.
3082 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3083 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3084 return ExprError();
3085
3086 // Otherwise, just build an unresolved lookup expression. Suppress
3087 // any lookup-related diagnostics; we'll hash these out later, when
3088 // we've picked a target.
3089 R.suppressDiagnostics();
3090
3091 UnresolvedLookupExpr *ULE
3092 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3093 SS.getWithLocInContext(Context),
3094 R.getLookupNameInfo(),
3095 NeedsADL, R.isOverloadedResult(),
3096 R.begin(), R.end());
3097
3098 return ULE;
3099}
3100
3101static void
3102diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3103 ValueDecl *var, DeclContext *DC);
3104
3105/// Complete semantic analysis for a reference to the given declaration.
3106ExprResult Sema::BuildDeclarationNameExpr(
3107 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3108 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3109 bool AcceptInvalidDecl) {
3110 assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast
<void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3110, __PRETTY_FUNCTION__))
;
3111 assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3112, __PRETTY_FUNCTION__))
3112 "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3112, __PRETTY_FUNCTION__))
;
3113
3114 SourceLocation Loc = NameInfo.getLoc();
3115 if (CheckDeclInExpr(*this, Loc, D))
3116 return ExprError();
3117
3118 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3119 // Specifically diagnose references to class templates that are missing
3120 // a template argument list.
3121 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3122 return ExprError();
3123 }
3124
3125 // Make sure that we're referring to a value.
3126 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3127 if (!VD) {
3128 Diag(Loc, diag::err_ref_non_value)
3129 << D << SS.getRange();
3130 Diag(D->getLocation(), diag::note_declared_at);
3131 return ExprError();
3132 }
3133
3134 // Check whether this declaration can be used. Note that we suppress
3135 // this check when we're going to perform argument-dependent lookup
3136 // on this function name, because this might not be the function
3137 // that overload resolution actually selects.
3138 if (DiagnoseUseOfDecl(VD, Loc))
3139 return ExprError();
3140
3141 // Only create DeclRefExpr's for valid Decl's.
3142 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3143 return ExprError();
3144
3145 // Handle members of anonymous structs and unions. If we got here,
3146 // and the reference is to a class member indirect field, then this
3147 // must be the subject of a pointer-to-member expression.
3148 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3149 if (!indirectField->isCXXClassMember())
3150 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3151 indirectField);
3152
3153 {
3154 QualType type = VD->getType();
3155 if (type.isNull())
3156 return ExprError();
3157 ExprValueKind valueKind = VK_RValue;
3158
3159 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3160 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3161 // is expanded by some outer '...' in the context of the use.
3162 type = type.getNonPackExpansionType();
3163
3164 switch (D->getKind()) {
3165 // Ignore all the non-ValueDecl kinds.
3166#define ABSTRACT_DECL(kind)
3167#define VALUE(type, base)
3168#define DECL(type, base) \
3169 case Decl::type:
3170#include "clang/AST/DeclNodes.inc"
3171 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3171)
;
3172
3173 // These shouldn't make it here.
3174 case Decl::ObjCAtDefsField:
3175 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3175)
;
3176
3177 // Enum constants are always r-values and never references.
3178 // Unresolved using declarations are dependent.
3179 case Decl::EnumConstant:
3180 case Decl::UnresolvedUsingValue:
3181 case Decl::OMPDeclareReduction:
3182 case Decl::OMPDeclareMapper:
3183 valueKind = VK_RValue;
3184 break;
3185
3186 // Fields and indirect fields that got here must be for
3187 // pointer-to-member expressions; we just call them l-values for
3188 // internal consistency, because this subexpression doesn't really
3189 // exist in the high-level semantics.
3190 case Decl::Field:
3191 case Decl::IndirectField:
3192 case Decl::ObjCIvar:
3193 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3194, __PRETTY_FUNCTION__))
3194 "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3194, __PRETTY_FUNCTION__))
;
3195
3196 // These can't have reference type in well-formed programs, but
3197 // for internal consistency we do this anyway.
3198 type = type.getNonReferenceType();
3199 valueKind = VK_LValue;
3200 break;
3201
3202 // Non-type template parameters are either l-values or r-values
3203 // depending on the type.
3204 case Decl::NonTypeTemplateParm: {
3205 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3206 type = reftype->getPointeeType();
3207 valueKind = VK_LValue; // even if the parameter is an r-value reference
3208 break;
3209 }
3210
3211 // For non-references, we need to strip qualifiers just in case
3212 // the template parameter was declared as 'const int' or whatever.
3213 valueKind = VK_RValue;
3214 type = type.getUnqualifiedType();
3215 break;
3216 }
3217
3218 case Decl::Var:
3219 case Decl::VarTemplateSpecialization:
3220 case Decl::VarTemplatePartialSpecialization:
3221 case Decl::Decomposition:
3222 case Decl::OMPCapturedExpr:
3223 // In C, "extern void blah;" is valid and is an r-value.
3224 if (!getLangOpts().CPlusPlus &&
3225 !type.hasQualifiers() &&
3226 type->isVoidType()) {
3227 valueKind = VK_RValue;
3228 break;
3229 }
3230 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3231
3232 case Decl::ImplicitParam:
3233 case Decl::ParmVar: {
3234 // These are always l-values.
3235 valueKind = VK_LValue;
3236 type = type.getNonReferenceType();
3237
3238 // FIXME: Does the addition of const really only apply in
3239 // potentially-evaluated contexts? Since the variable isn't actually
3240 // captured in an unevaluated context, it seems that the answer is no.
3241 if (!isUnevaluatedContext()) {
3242 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3243 if (!CapturedType.isNull())
3244 type = CapturedType;
3245 }
3246
3247 break;
3248 }
3249
3250 case Decl::Binding: {
3251 // These are always lvalues.
3252 valueKind = VK_LValue;
3253 type = type.getNonReferenceType();
3254 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3255 // decides how that's supposed to work.
3256 auto *BD = cast<BindingDecl>(VD);
3257 if (BD->getDeclContext() != CurContext) {
3258 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3259 if (DD && DD->hasLocalStorage())
3260 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3261 }
3262 break;
3263 }
3264
3265 case Decl::Function: {
3266 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3267 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3268 type = Context.BuiltinFnTy;
3269 valueKind = VK_RValue;
3270 break;
3271 }
3272 }
3273
3274 const FunctionType *fty = type->castAs<FunctionType>();
3275
3276 // If we're referring to a function with an __unknown_anytype
3277 // result type, make the entire expression __unknown_anytype.
3278 if (fty->getReturnType() == Context.UnknownAnyTy) {
3279 type = Context.UnknownAnyTy;
3280 valueKind = VK_RValue;
3281 break;
3282 }
3283
3284 // Functions are l-values in C++.
3285 if (getLangOpts().CPlusPlus) {
3286 valueKind = VK_LValue;
3287 break;
3288 }
3289
3290 // C99 DR 316 says that, if a function type comes from a
3291 // function definition (without a prototype), that type is only
3292 // used for checking compatibility. Therefore, when referencing
3293 // the function, we pretend that we don't have the full function
3294 // type.
3295 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3296 isa<FunctionProtoType>(fty))
3297 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3298 fty->getExtInfo());
3299
3300 // Functions are r-values in C.
3301 valueKind = VK_RValue;
3302 break;
3303 }
3304
3305 case Decl::CXXDeductionGuide:
3306 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3306)
;
3307
3308 case Decl::MSProperty:
3309 case Decl::MSGuid:
3310 // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3311 // or duplicated between host and device?
3312 valueKind = VK_LValue;
3313 break;
3314
3315 case Decl::CXXMethod:
3316 // If we're referring to a method with an __unknown_anytype
3317 // result type, make the entire expression __unknown_anytype.
3318 // This should only be possible with a type written directly.
3319 if (const FunctionProtoType *proto
3320 = dyn_cast<FunctionProtoType>(VD->getType()))
3321 if (proto->getReturnType() == Context.UnknownAnyTy) {
3322 type = Context.UnknownAnyTy;
3323 valueKind = VK_RValue;
3324 break;
3325 }
3326
3327 // C++ methods are l-values if static, r-values if non-static.
3328 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3329 valueKind = VK_LValue;
3330 break;
3331 }
3332 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3333
3334 case Decl::CXXConversion:
3335 case Decl::CXXDestructor:
3336 case Decl::CXXConstructor:
3337 valueKind = VK_RValue;
3338 break;
3339 }
3340
3341 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3342 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3343 TemplateArgs);
3344 }
3345}
3346
3347static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3348 SmallString<32> &Target) {
3349 Target.resize(CharByteWidth * (Source.size() + 1));
3350 char *ResultPtr = &Target[0];
3351 const llvm::UTF8 *ErrorPtr;
3352 bool success =
3353 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3354 (void)success;
3355 assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3355, __PRETTY_FUNCTION__))
;
3356 Target.resize(ResultPtr - &Target[0]);
3357}
3358
3359ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3360 PredefinedExpr::IdentKind IK) {
3361 // Pick the current block, lambda, captured statement or function.
3362 Decl *currentDecl = nullptr;
3363 if (const BlockScopeInfo *BSI = getCurBlock())
3364 currentDecl = BSI->TheDecl;
3365 else if (const LambdaScopeInfo *LSI = getCurLambda())
3366 currentDecl = LSI->CallOperator;
3367 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3368 currentDecl = CSI->TheCapturedDecl;
3369 else
3370 currentDecl = getCurFunctionOrMethodDecl();
3371
3372 if (!currentDecl) {
3373 Diag(Loc, diag::ext_predef_outside_function);
3374 currentDecl = Context.getTranslationUnitDecl();
3375 }
3376
3377 QualType ResTy;
3378 StringLiteral *SL = nullptr;
3379 if (cast<DeclContext>(currentDecl)->isDependentContext())
3380 ResTy = Context.DependentTy;
3381 else {
3382 // Pre-defined identifiers are of type char[x], where x is the length of
3383 // the string.
3384 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3385 unsigned Length = Str.length();
3386
3387 llvm::APInt LengthI(32, Length + 1);
3388 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3389 ResTy =
3390 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3391 SmallString<32> RawChars;
3392 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3393 Str, RawChars);
3394 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3395 ArrayType::Normal,
3396 /*IndexTypeQuals*/ 0);
3397 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3398 /*Pascal*/ false, ResTy, Loc);
3399 } else {
3400 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3401 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3402 ArrayType::Normal,
3403 /*IndexTypeQuals*/ 0);
3404 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3405 /*Pascal*/ false, ResTy, Loc);
3406 }
3407 }
3408
3409 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3410}
3411
3412static std::pair<QualType, StringLiteral *>
3413GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3414 SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3415 std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3416
3417 if (OpType->isDependentType()) {
3418 Result.first = Context.DependentTy;
3419 return Result;
3420 }
3421
3422 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3423 llvm::APInt Length(32, Str.length() + 1);
3424 Result.first =
3425 Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3426 Result.first = Context.getConstantArrayType(
3427 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3428 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3429 /*Pascal*/ false, Result.first, OpLoc);
3430 return Result;
3431}
3432
3433ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3434 TypeSourceInfo *Operand) {
3435 QualType ResultTy;
3436 StringLiteral *SL;
3437 std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3438 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3439
3440 return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3441 PredefinedExpr::UniqueStableNameType, SL,
3442 Operand);
3443}
3444
3445ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3446 Expr *E) {
3447 QualType ResultTy;
3448 StringLiteral *SL;
3449 std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3450 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3451
3452 return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3453 PredefinedExpr::UniqueStableNameExpr, SL, E);
3454}
3455
3456ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3457 SourceLocation L, SourceLocation R,
3458 ParsedType Ty) {
3459 TypeSourceInfo *TInfo = nullptr;
3460 QualType T = GetTypeFromParser(Ty, &TInfo);
3461
3462 if (T.isNull())
3463 return ExprError();
3464 if (!TInfo)
3465 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3466
3467 return BuildUniqueStableName(OpLoc, TInfo);
3468}
3469
3470ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3471 SourceLocation L, SourceLocation R,
3472 Expr *E) {
3473 return BuildUniqueStableName(OpLoc, E);
3474}
3475
3476ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3477 PredefinedExpr::IdentKind IK;
3478
3479 switch (Kind) {
3480 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3480)
;
3481 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3482 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3483 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3484 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3485 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3486 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3487 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3488 }
3489
3490 return BuildPredefinedExpr(Loc, IK);
3491}
3492
3493ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3494 SmallString<16> CharBuffer;
3495 bool Invalid = false;
3496 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3497 if (Invalid)
3498 return ExprError();
3499
3500 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3501 PP, Tok.getKind());
3502 if (Literal.hadError())
3503 return ExprError();
3504
3505 QualType Ty;
3506 if (Literal.isWide())
3507 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3508 else if (Literal.isUTF8() && getLangOpts().Char8)
3509 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3510 else if (Literal.isUTF16())
3511 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3512 else if (Literal.isUTF32())
3513 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3514 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3515 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3516 else
3517 Ty = Context.CharTy; // 'x' -> char in C++
3518
3519 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3520 if (Literal.isWide())
3521 Kind = CharacterLiteral::Wide;
3522 else if (Literal.isUTF16())
3523 Kind = CharacterLiteral::UTF16;
3524 else if (Literal.isUTF32())
3525 Kind = CharacterLiteral::UTF32;
3526 else if (Literal.isUTF8())
3527 Kind = CharacterLiteral::UTF8;
3528
3529 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3530 Tok.getLocation());
3531
3532 if (Literal.getUDSuffix().empty())
3533 return Lit;
3534
3535 // We're building a user-defined literal.
3536 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3537 SourceLocation UDSuffixLoc =
3538 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3539
3540 // Make sure we're allowed user-defined literals here.
3541 if (!UDLScope)
3542 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3543
3544 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3545 // operator "" X (ch)
3546 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3547 Lit, Tok.getLocation());
3548}
3549
3550ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3551 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3552 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3553 Context.IntTy, Loc);
3554}
3555
3556static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3557 QualType Ty, SourceLocation Loc) {
3558 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3559
3560 using llvm::APFloat;
3561 APFloat Val(Format);
3562
3563 APFloat::opStatus result = Literal.GetFloatValue(Val);
3564
3565 // Overflow is always an error, but underflow is only an error if
3566 // we underflowed to zero (APFloat reports denormals as underflow).
3567 if ((result & APFloat::opOverflow) ||
3568 ((result & APFloat::opUnderflow) && Val.isZero())) {
3569 unsigned diagnostic;
3570 SmallString<20> buffer;
3571 if (result & APFloat::opOverflow) {
3572 diagnostic = diag::warn_float_overflow;
3573 APFloat::getLargest(Format).toString(buffer);
3574 } else {
3575 diagnostic = diag::warn_float_underflow;
3576 APFloat::getSmallest(Format).toString(buffer);
3577 }
3578
3579 S.Diag(Loc, diagnostic)
3580 << Ty
3581 << StringRef(buffer.data(), buffer.size());
3582 }
3583
3584 bool isExact = (result == APFloat::opOK);
3585 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3586}
3587
3588bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3589 assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void>
(0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3589, __PRETTY_FUNCTION__))
;
3590
3591 if (E->isValueDependent())
3592 return false;
3593
3594 QualType QT = E->getType();
3595 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3596 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3597 return true;
3598 }
3599
3600 llvm::APSInt ValueAPS;
3601 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3602
3603 if (R.isInvalid())
3604 return true;
3605
3606 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3607 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3608 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3609 << ValueAPS.toString(10) << ValueIsPositive;
3610 return true;
3611 }
3612
3613 return false;
3614}
3615
3616ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3617 // Fast path for a single digit (which is quite common). A single digit
3618 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3619 if (Tok.getLength() == 1) {
3620 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3621 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3622 }
3623
3624 SmallString<128> SpellingBuffer;
3625 // NumericLiteralParser wants to overread by one character. Add padding to
3626 // the buffer in case the token is copied to the buffer. If getSpelling()
3627 // returns a StringRef to the memory buffer, it should have a null char at
3628 // the EOF, so it is also safe.
3629 SpellingBuffer.resize(Tok.getLength() + 1);
3630
3631 // Get the spelling of the token, which eliminates trigraphs, etc.
3632 bool Invalid = false;
3633 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3634 if (Invalid)
3635 return ExprError();
3636
3637 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3638 PP.getSourceManager(), PP.getLangOpts(),
3639 PP.getTargetInfo(), PP.getDiagnostics());
3640 if (Literal.hadError)
3641 return ExprError();
3642
3643 if (Literal.hasUDSuffix()) {
3644 // We're building a user-defined literal.
3645 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3646 SourceLocation UDSuffixLoc =
3647 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3648
3649 // Make sure we're allowed user-defined literals here.
3650 if (!UDLScope)
3651 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3652
3653 QualType CookedTy;
3654 if (Literal.isFloatingLiteral()) {
3655 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3656 // long double, the literal is treated as a call of the form
3657 // operator "" X (f L)
3658 CookedTy = Context.LongDoubleTy;
3659 } else {
3660 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3661 // unsigned long long, the literal is treated as a call of the form
3662 // operator "" X (n ULL)
3663 CookedTy = Context.UnsignedLongLongTy;
3664 }
3665
3666 DeclarationName OpName =
3667 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3668 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3669 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3670
3671 SourceLocation TokLoc = Tok.getLocation();
3672
3673 // Perform literal operator lookup to determine if we're building a raw
3674 // literal or a cooked one.
3675 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3676 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3677 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3678 /*AllowStringTemplate*/ false,
3679 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3680 case LOLR_ErrorNoDiagnostic:
3681 // Lookup failure for imaginary constants isn't fatal, there's still the
3682 // GNU extension producing _Complex types.
3683 break;
3684 case LOLR_Error:
3685 return ExprError();
3686 case LOLR_Cooked: {
3687 Expr *Lit;
3688 if (Literal.isFloatingLiteral()) {
3689 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3690 } else {
3691 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3692 if (Literal.GetIntegerValue(ResultVal))
3693 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3694 << /* Unsigned */ 1;
3695 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3696 Tok.getLocation());
3697 }
3698 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3699 }
3700
3701 case LOLR_Raw: {
3702 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3703 // literal is treated as a call of the form
3704 // operator "" X ("n")
3705 unsigned Length = Literal.getUDSuffixOffset();
3706 QualType StrTy = Context.getConstantArrayType(
3707 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3708 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3709 Expr *Lit = StringLiteral::Create(
3710 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3711 /*Pascal*/false, StrTy, &TokLoc, 1);
3712 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3713 }
3714
3715 case LOLR_Template: {
3716 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3717 // template), L is treated as a call fo the form
3718 // operator "" X <'c1', 'c2', ... 'ck'>()
3719 // where n is the source character sequence c1 c2 ... ck.
3720 TemplateArgumentListInfo ExplicitArgs;
3721 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3722 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3723 llvm::APSInt Value(CharBits, CharIsUnsigned);
3724 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3725 Value = TokSpelling[I];
3726 TemplateArgument Arg(Context, Value, Context.CharTy);
3727 TemplateArgumentLocInfo ArgInfo;
3728 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3729 }
3730 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3731 &ExplicitArgs);
3732 }
3733 case LOLR_StringTemplate:
3734 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3734)
;
3735 }
3736 }
3737
3738 Expr *Res;
3739
3740 if (Literal.isFixedPointLiteral()) {
3741 QualType Ty;
3742
3743 if (Literal.isAccum) {
3744 if (Literal.isHalf) {
3745 Ty = Context.ShortAccumTy;
3746 } else if (Literal.isLong) {
3747 Ty = Context.LongAccumTy;
3748 } else {
3749 Ty = Context.AccumTy;
3750 }
3751 } else if (Literal.isFract) {
3752 if (Literal.isHalf) {
3753 Ty = Context.ShortFractTy;
3754 } else if (Literal.isLong) {
3755 Ty = Context.LongFractTy;
3756 } else {
3757 Ty = Context.FractTy;
3758 }
3759 }
3760
3761 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3762
3763 bool isSigned = !Literal.isUnsigned;
3764 unsigned scale = Context.getFixedPointScale(Ty);
3765 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3766
3767 llvm::APInt Val(bit_width, 0, isSigned);
3768 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3769 bool ValIsZero = Val.isNullValue() && !Overflowed;
3770
3771 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3772 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3773 // Clause 6.4.4 - The value of a constant shall be in the range of
3774 // representable values for its type, with exception for constants of a
3775 // fract type with a value of exactly 1; such a constant shall denote
3776 // the maximal value for the type.
3777 --Val;
3778 else if (Val.ugt(MaxVal) || Overflowed)
3779 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3780
3781 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3782 Tok.getLocation(), scale);
3783 } else if (Literal.isFloatingLiteral()) {
3784 QualType Ty;
3785 if (Literal.isHalf){
3786 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3787 Ty = Context.HalfTy;
3788 else {
3789 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3790 return ExprError();
3791 }
3792 } else if (Literal.isFloat)
3793 Ty = Context.FloatTy;
3794 else if (Literal.isLong)
3795 Ty = Context.LongDoubleTy;
3796 else if (Literal.isFloat16)
3797 Ty = Context.Float16Ty;
3798 else if (Literal.isFloat128)
3799 Ty = Context.Float128Ty;
3800 else
3801 Ty = Context.DoubleTy;
3802
3803 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3804
3805 if (Ty == Context.DoubleTy) {
3806 if (getLangOpts().SinglePrecisionConstants) {
3807 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3808 if (BTy->getKind() != BuiltinType::Float) {
3809 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3810 }
3811 } else if (getLangOpts().OpenCL &&
3812 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3813 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3814 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3815 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3816 }
3817 }
3818 } else if (!Literal.isIntegerLiteral()) {
3819 return ExprError();
3820 } else {
3821 QualType Ty;
3822
3823 // 'long long' is a C99 or C++11 feature.
3824 if (!getLangOpts().C99 && Literal.isLongLong) {
3825 if (getLangOpts().CPlusPlus)
3826 Diag(Tok.getLocation(),
3827 getLangOpts().CPlusPlus11 ?
3828 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3829 else
3830 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3831 }
3832
3833 // Get the value in the widest-possible width.
3834 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3835 llvm::APInt ResultVal(MaxWidth, 0);
3836
3837 if (Literal.GetIntegerValue(ResultVal)) {
3838 // If this value didn't fit into uintmax_t, error and force to ull.
3839 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3840 << /* Unsigned */ 1;
3841 Ty = Context.UnsignedLongLongTy;
3842 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3843, __PRETTY_FUNCTION__))
3843 "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3843, __PRETTY_FUNCTION__))
;
3844 } else {
3845 // If this value fits into a ULL, try to figure out what else it fits into
3846 // according to the rules of C99 6.4.4.1p5.
3847
3848 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3849 // be an unsigned int.
3850 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3851
3852 // Check from smallest to largest, picking the smallest type we can.
3853 unsigned Width = 0;
3854
3855 // Microsoft specific integer suffixes are explicitly sized.
3856 if (Literal.MicrosoftInteger) {
3857 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3858 Width = 8;
3859 Ty = Context.CharTy;
3860 } else {
3861 Width = Literal.MicrosoftInteger;
3862 Ty = Context.getIntTypeForBitwidth(Width,
3863 /*Signed=*/!Literal.isUnsigned);
3864 }
3865 }
3866
3867 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3868 // Are int/unsigned possibilities?
3869 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3870
3871 // Does it fit in a unsigned int?
3872 if (ResultVal.isIntN(IntSize)) {
3873 // Does it fit in a signed int?
3874 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3875 Ty = Context.IntTy;
3876 else if (AllowUnsigned)
3877 Ty = Context.UnsignedIntTy;
3878 Width = IntSize;
3879 }
3880 }
3881
3882 // Are long/unsigned long possibilities?
3883 if (Ty.isNull() && !Literal.isLongLong) {
3884 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3885
3886 // Does it fit in a unsigned long?
3887 if (ResultVal.isIntN(LongSize)) {
3888 // Does it fit in a signed long?
3889 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3890 Ty = Context.LongTy;
3891 else if (AllowUnsigned)
3892 Ty = Context.UnsignedLongTy;
3893 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3894 // is compatible.
3895 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3896 const unsigned LongLongSize =
3897 Context.getTargetInfo().getLongLongWidth();
3898 Diag(Tok.getLocation(),
3899 getLangOpts().CPlusPlus
3900 ? Literal.isLong
3901 ? diag::warn_old_implicitly_unsigned_long_cxx
3902 : /*C++98 UB*/ diag::
3903 ext_old_implicitly_unsigned_long_cxx
3904 : diag::warn_old_implicitly_unsigned_long)
3905 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3906 : /*will be ill-formed*/ 1);
3907 Ty = Context.UnsignedLongTy;
3908 }
3909 Width = LongSize;
3910 }
3911 }
3912
3913 // Check long long if needed.
3914 if (Ty.isNull()) {
3915 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3916
3917 // Does it fit in a unsigned long long?
3918 if (ResultVal.isIntN(LongLongSize)) {
3919 // Does it fit in a signed long long?
3920 // To be compatible with MSVC, hex integer literals ending with the
3921 // LL or i64 suffix are always signed in Microsoft mode.
3922 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3923 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3924 Ty = Context.LongLongTy;
3925 else if (AllowUnsigned)
3926 Ty = Context.UnsignedLongLongTy;
3927 Width = LongLongSize;
3928 }
3929 }
3930
3931 // If we still couldn't decide a type, we probably have something that
3932 // does not fit in a signed long long, but has no U suffix.
3933 if (Ty.isNull()) {
3934 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3935 Ty = Context.UnsignedLongLongTy;
3936 Width = Context.getTargetInfo().getLongLongWidth();
3937 }
3938
3939 if (ResultVal.getBitWidth() != Width)
3940 ResultVal = ResultVal.trunc(Width);
3941 }
3942 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3943 }
3944
3945 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3946 if (Literal.isImaginary) {
3947 Res = new (Context) ImaginaryLiteral(Res,
3948 Context.getComplexType(Res->getType()));
3949
3950 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3951 }
3952 return Res;
3953}
3954
3955ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3956 assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast
<void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3956, __PRETTY_FUNCTION__))
;
3957 return new (Context) ParenExpr(L, R, E);
3958}
3959
3960static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3961 SourceLocation Loc,
3962 SourceRange ArgRange) {
3963 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3964 // scalar or vector data type argument..."
3965 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3966 // type (C99 6.2.5p18) or void.
3967 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3968 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3969 << T << ArgRange;
3970 return true;
3971 }
3972
3973 assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3974, __PRETTY_FUNCTION__))
3974 "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 3974, __PRETTY_FUNCTION__))
;
3975 return false;
3976}
3977
3978static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3979 SourceLocation Loc,
3980 SourceRange ArgRange,
3981 UnaryExprOrTypeTrait TraitKind) {
3982 // Invalid types must be hard errors for SFINAE in C++.
3983 if (S.LangOpts.CPlusPlus)
3984 return true;
3985
3986 // C99 6.5.3.4p1:
3987 if (T->isFunctionType() &&
3988 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3989 TraitKind == UETT_PreferredAlignOf)) {
3990 // sizeof(function)/alignof(function) is allowed as an extension.
3991 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3992 << getTraitSpelling(TraitKind) << ArgRange;
3993 return false;
3994 }
3995
3996 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3997 // this is an error (OpenCL v1.1 s6.3.k)
3998 if (T->isVoidType()) {
3999 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4000 : diag::ext_sizeof_alignof_void_type;
4001 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4002 return false;
4003 }
4004
4005 return true;
4006}
4007
4008static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4009 SourceLocation Loc,
4010 SourceRange ArgRange,
4011 UnaryExprOrTypeTrait TraitKind) {
4012 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4013 // runtime doesn't allow it.
4014 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4015 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4016 << T << (TraitKind == UETT_SizeOf)
4017 << ArgRange;
4018 return true;
4019 }
4020
4021 return false;
4022}
4023
4024/// Check whether E is a pointer from a decayed array type (the decayed
4025/// pointer type is equal to T) and emit a warning if it is.
4026static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4027 Expr *E) {
4028 // Don't warn if the operation changed the type.
4029 if (T != E->getType())
4030 return;
4031
4032 // Now look for array decays.
4033 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4034 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4035 return;
4036
4037 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4038 << ICE->getType()
4039 << ICE->getSubExpr()->getType();
4040}
4041
4042/// Check the constraints on expression operands to unary type expression
4043/// and type traits.
4044///
4045/// Completes any types necessary and validates the constraints on the operand
4046/// expression. The logic mostly mirrors the type-based overload, but may modify
4047/// the expression as it completes the type for that expression through template
4048/// instantiation, etc.
4049bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4050 UnaryExprOrTypeTrait ExprKind) {
4051 QualType ExprTy = E->getType();
4052 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4052, __PRETTY_FUNCTION__))
;
4053
4054 bool IsUnevaluatedOperand =
4055 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4056 ExprKind == UETT_PreferredAlignOf);
4057 if (IsUnevaluatedOperand) {
4058 ExprResult Result = CheckUnevaluatedOperand(E);
4059 if (Result.isInvalid())
4060 return true;
4061 E = Result.get();
4062 }
4063
4064 if (ExprKind == UETT_VecStep)
4065 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4066 E->getSourceRange());
4067
4068 // Explicitly list some types as extensions.
4069 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4070 E->getSourceRange(), ExprKind))
4071 return false;
4072
4073 // 'alignof' applied to an expression only requires the base element type of
4074 // the expression to be complete. 'sizeof' requires the expression's type to
4075 // be complete (and will attempt to complete it if it's an array of unknown
4076 // bound).
4077 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4078 if (RequireCompleteSizedType(
4079 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4080 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4081 getTraitSpelling(ExprKind), E->getSourceRange()))
4082 return true;
4083 } else {
4084 if (RequireCompleteSizedExprType(
4085 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4086 getTraitSpelling(ExprKind), E->getSourceRange()))
4087 return true;
4088 }
4089
4090 // Completing the expression's type may have changed it.
4091 ExprTy = E->getType();
4092 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4092, __PRETTY_FUNCTION__))
;
4093
4094 if (ExprTy->isFunctionType()) {
4095 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4096 << getTraitSpelling(ExprKind) << E->getSourceRange();
4097 return true;
4098 }
4099
4100 // The operand for sizeof and alignof is in an unevaluated expression context,
4101 // so side effects could result in unintended consequences.
4102 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4103 E->HasSideEffects(Context, false))
4104 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4105
4106 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4107 E->getSourceRange(), ExprKind))
4108 return true;
4109
4110 if (ExprKind == UETT_SizeOf) {
4111 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4112 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4113 QualType OType = PVD->getOriginalType();
4114 QualType Type = PVD->getType();
4115 if (Type->isPointerType() && OType->isArrayType()) {
4116 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4117 << Type << OType;
4118 Diag(PVD->getLocation(), diag::note_declared_at);
4119 }
4120 }
4121 }
4122
4123 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4124 // decays into a pointer and returns an unintended result. This is most
4125 // likely a typo for "sizeof(array) op x".
4126 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4127 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4128 BO->getLHS());
4129 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4130 BO->getRHS());
4131 }
4132 }
4133
4134 return false;
4135}
4136
4137/// Check the constraints on operands to unary expression and type
4138/// traits.
4139///
4140/// This will complete any types necessary, and validate the various constraints
4141/// on those operands.
4142///
4143/// The UsualUnaryConversions() function is *not* called by this routine.
4144/// C99 6.3.2.1p[2-4] all state:
4145/// Except when it is the operand of the sizeof operator ...
4146///
4147/// C++ [expr.sizeof]p4
4148/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4149/// standard conversions are not applied to the operand of sizeof.
4150///
4151/// This policy is followed for all of the unary trait expressions.
4152bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4153 SourceLocation OpLoc,
4154 SourceRange ExprRange,
4155 UnaryExprOrTypeTrait ExprKind) {
4156 if (ExprType->isDependentType())
4157 return false;
4158
4159 // C++ [expr.sizeof]p2:
4160 // When applied to a reference or a reference type, the result
4161 // is the size of the referenced type.
4162 // C++11 [expr.alignof]p3:
4163 // When alignof is applied to a reference type, the result
4164 // shall be the alignment of the referenced type.
4165 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4166 ExprType = Ref->getPointeeType();
4167
4168 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4169 // When alignof or _Alignof is applied to an array type, the result
4170 // is the alignment of the element type.
4171 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4172 ExprKind == UETT_OpenMPRequiredSimdAlign)
4173 ExprType = Context.getBaseElementType(ExprType);
4174
4175 if (ExprKind == UETT_VecStep)
4176 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4177
4178 // Explicitly list some types as extensions.
4179 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4180 ExprKind))
4181 return false;
4182
4183 if (RequireCompleteSizedType(
4184 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4185 getTraitSpelling(ExprKind), ExprRange))
4186 return true;
4187
4188 if (ExprType->isFunctionType()) {
4189 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4190 << getTraitSpelling(ExprKind) << ExprRange;
4191 return true;
4192 }
4193
4194 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4195 ExprKind))
4196 return true;
4197
4198 return false;
4199}
4200
4201static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4202 // Cannot know anything else if the expression is dependent.
4203 if (E->isTypeDependent())
4204 return false;
4205
4206 if (E->getObjectKind() == OK_BitField) {
4207 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4208 << 1 << E->getSourceRange();
4209 return true;
4210 }
4211
4212 ValueDecl *D = nullptr;
4213 Expr *Inner = E->IgnoreParens();
4214 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4215 D = DRE->getDecl();
4216 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4217 D = ME->getMemberDecl();
4218 }
4219
4220 // If it's a field, require the containing struct to have a
4221 // complete definition so that we can compute the layout.
4222 //
4223 // This can happen in C++11 onwards, either by naming the member
4224 // in a way that is not transformed into a member access expression
4225 // (in an unevaluated operand, for instance), or by naming the member
4226 // in a trailing-return-type.
4227 //
4228 // For the record, since __alignof__ on expressions is a GCC
4229 // extension, GCC seems to permit this but always gives the
4230 // nonsensical answer 0.
4231 //
4232 // We don't really need the layout here --- we could instead just
4233 // directly check for all the appropriate alignment-lowing
4234 // attributes --- but that would require duplicating a lot of
4235 // logic that just isn't worth duplicating for such a marginal
4236 // use-case.
4237 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4238 // Fast path this check, since we at least know the record has a
4239 // definition if we can find a member of it.
4240 if (!FD->getParent()->isCompleteDefinition()) {
4241 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4242 << E->getSourceRange();
4243 return true;
4244 }
4245
4246 // Otherwise, if it's a field, and the field doesn't have
4247 // reference type, then it must have a complete type (or be a
4248 // flexible array member, which we explicitly want to
4249 // white-list anyway), which makes the following checks trivial.
4250 if (!FD->getType()->isReferenceType())
4251 return false;
4252 }
4253
4254 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4255}
4256
4257bool Sema::CheckVecStepExpr(Expr *E) {
4258 E = E->IgnoreParens();
4259
4260 // Cannot know anything else if the expression is dependent.
4261 if (E->isTypeDependent())
4262 return false;
4263
4264 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4265}
4266
4267static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4268 CapturingScopeInfo *CSI) {
4269 assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> (
0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4269, __PRETTY_FUNCTION__))
;
4270 assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail
("CSI != nullptr", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4270, __PRETTY_FUNCTION__))
;
4271
4272 // We're going to walk down into the type and look for VLA expressions.
4273 do {
4274 const Type *Ty = T.getTypePtr();
4275 switch (Ty->getTypeClass()) {
4276#define TYPE(Class, Base)
4277#define ABSTRACT_TYPE(Class, Base)
4278#define NON_CANONICAL_TYPE(Class, Base)
4279#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4280#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4281#include "clang/AST/TypeNodes.inc"
4282 T = QualType();
4283 break;
4284 // These types are never variably-modified.
4285 case Type::Builtin:
4286 case Type::Complex:
4287 case Type::Vector:
4288 case Type::ExtVector:
4289 case Type::ConstantMatrix:
4290 case Type::Record:
4291 case Type::Enum:
4292 case Type::Elaborated:
4293 case Type::TemplateSpecialization:
4294 case Type::ObjCObject:
4295 case Type::ObjCInterface:
4296 case Type::ObjCObjectPointer:
4297 case Type::ObjCTypeParam:
4298 case Type::Pipe:
4299 case Type::ExtInt:
4300 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4300)
;
4301 case Type::Adjusted:
4302 T = cast<AdjustedType>(Ty)->getOriginalType();
4303 break;
4304 case Type::Decayed:
4305 T = cast<DecayedType>(Ty)->getPointeeType();
4306 break;
4307 case Type::Pointer:
4308 T = cast<PointerType>(Ty)->getPointeeType();
4309 break;
4310 case Type::BlockPointer:
4311 T = cast<BlockPointerType>(Ty)->getPointeeType();
4312 break;
4313 case Type::LValueReference:
4314 case Type::RValueReference:
4315 T = cast<ReferenceType>(Ty)->getPointeeType();
4316 break;
4317 case Type::MemberPointer:
4318 T = cast<MemberPointerType>(Ty)->getPointeeType();
4319 break;
4320 case Type::ConstantArray:
4321 case Type::IncompleteArray:
4322 // Losing element qualification here is fine.
4323 T = cast<ArrayType>(Ty)->getElementType();
4324 break;
4325 case Type::VariableArray: {
4326 // Losing element qualification here is fine.
4327 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4328
4329 // Unknown size indication requires no size computation.
4330 // Otherwise, evaluate and record it.
4331 auto Size = VAT->getSizeExpr();
4332 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4333 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4334 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4335
4336 T = VAT->getElementType();
4337 break;
4338 }
4339 case Type::FunctionProto:
4340 case Type::FunctionNoProto:
4341 T = cast<FunctionType>(Ty)->getReturnType();
4342 break;
4343 case Type::Paren:
4344 case Type::TypeOf:
4345 case Type::UnaryTransform:
4346 case Type::Attributed:
4347 case Type::SubstTemplateTypeParm:
4348 case Type::MacroQualified:
4349 // Keep walking after single level desugaring.
4350 T = T.getSingleStepDesugaredType(Context);
4351 break;
4352 case Type::Typedef:
4353 T = cast<TypedefType>(Ty)->desugar();
4354 break;
4355 case Type::Decltype:
4356 T = cast<DecltypeType>(Ty)->desugar();
4357 break;
4358 case Type::Auto:
4359 case Type::DeducedTemplateSpecialization:
4360 T = cast<DeducedType>(Ty)->getDeducedType();
4361 break;
4362 case Type::TypeOfExpr:
4363 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4364 break;
4365 case Type::Atomic:
4366 T = cast<AtomicType>(Ty)->getValueType();
4367 break;
4368 }
4369 } while (!T.isNull() && T->isVariablyModifiedType());
4370}
4371
4372/// Build a sizeof or alignof expression given a type operand.
4373ExprResult
4374Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4375 SourceLocation OpLoc,
4376 UnaryExprOrTypeTrait ExprKind,
4377 SourceRange R) {
4378 if (!TInfo)
4379 return ExprError();
4380
4381 QualType T = TInfo->getType();
4382
4383 if (!T->isDependentType() &&
4384 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4385 return ExprError();
4386
4387 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4388 if (auto *TT = T->getAs<TypedefType>()) {
4389 for (auto I = FunctionScopes.rbegin(),
4390 E = std::prev(FunctionScopes.rend());
4391 I != E; ++I) {
4392 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4393 if (CSI == nullptr)
4394 break;
4395 DeclContext *DC = nullptr;
4396 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4397 DC = LSI->CallOperator;
4398 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4399 DC = CRSI->TheCapturedDecl;
4400 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4401 DC = BSI->TheDecl;
4402 if (DC) {
4403 if (DC->containsDecl(TT->getDecl()))
4404 break;
4405 captureVariablyModifiedType(Context, T, CSI);
4406 }
4407 }
4408 }
4409 }
4410
4411 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4412 return new (Context) UnaryExprOrTypeTraitExpr(
4413 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4414}
4415
4416/// Build a sizeof or alignof expression given an expression
4417/// operand.
4418ExprResult
4419Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4420 UnaryExprOrTypeTrait ExprKind) {
4421 ExprResult PE = CheckPlaceholderExpr(E);
4422 if (PE.isInvalid())
4423 return ExprError();
4424
4425 E = PE.get();
4426
4427 // Verify that the operand is valid.
4428 bool isInvalid = false;
4429 if (E->isTypeDependent()) {
4430 // Delay type-checking for type-dependent expressions.
4431 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4432 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4433 } else if (ExprKind == UETT_VecStep) {
4434 isInvalid = CheckVecStepExpr(E);
4435 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4436 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4437 isInvalid = true;
4438 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4439 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4440 isInvalid = true;
4441 } else {
4442 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4443 }
4444
4445 if (isInvalid)
4446 return ExprError();
4447
4448 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4449 PE = TransformToPotentiallyEvaluated(E);
4450 if (PE.isInvalid()) return ExprError();
4451 E = PE.get();
4452 }
4453
4454 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4455 return new (Context) UnaryExprOrTypeTraitExpr(
4456 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4457}
4458
4459/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4460/// expr and the same for @c alignof and @c __alignof
4461/// Note that the ArgRange is invalid if isType is false.
4462ExprResult
4463Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4464 UnaryExprOrTypeTrait ExprKind, bool IsType,
4465 void *TyOrEx, SourceRange ArgRange) {
4466 // If error parsing type, ignore.
4467 if (!TyOrEx) return ExprError();
4468
4469 if (IsType) {
4470 TypeSourceInfo *TInfo;
4471 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4472 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4473 }
4474
4475 Expr *ArgEx = (Expr *)TyOrEx;
4476 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4477 return Result;
4478}
4479
4480static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4481 bool IsReal) {
4482 if (V.get()->isTypeDependent())
4483 return S.Context.DependentTy;
4484
4485 // _Real and _Imag are only l-values for normal l-values.
4486 if (V.get()->getObjectKind() != OK_Ordinary) {
4487 V = S.DefaultLvalueConversion(V.get());
4488 if (V.isInvalid())
4489 return QualType();
4490 }
4491
4492 // These operators return the element type of a complex type.
4493 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4494 return CT->getElementType();
4495
4496 // Otherwise they pass through real integer and floating point types here.
4497 if (V.get()->getType()->isArithmeticType())
4498 return V.get()->getType();
4499
4500 // Test for placeholders.
4501 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4502 if (PR.isInvalid()) return QualType();
4503 if (PR.get() != V.get()) {
4504 V = PR;
4505 return CheckRealImagOperand(S, V, Loc, IsReal);
4506 }
4507
4508 // Reject anything else.
4509 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4510 << (IsReal ? "__real" : "__imag");
4511 return QualType();
4512}
4513
4514
4515
4516ExprResult
4517Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4518 tok::TokenKind Kind, Expr *Input) {
4519 UnaryOperatorKind Opc;
4520 switch (Kind) {
4521 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4521)
;
4522 case tok::plusplus: Opc = UO_PostInc; break;
4523 case tok::minusminus: Opc = UO_PostDec; break;
4524 }
4525
4526 // Since this might is a postfix expression, get rid of ParenListExprs.
4527 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4528 if (Result.isInvalid()) return ExprError();
4529 Input = Result.get();
4530
4531 return BuildUnaryOp(S, OpLoc, Opc, Input);
4532}
4533
4534/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4535///
4536/// \return true on error
4537static bool checkArithmeticOnObjCPointer(Sema &S,
4538 SourceLocation opLoc,
4539 Expr *op) {
4540 assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast
<void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4540, __PRETTY_FUNCTION__))
;
4541 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4542 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4543 return false;
4544
4545 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4546 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4547 << op->getSourceRange();
4548 return true;
4549}
4550
4551static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4552 auto *BaseNoParens = Base->IgnoreParens();
4553 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4554 return MSProp->getPropertyDecl()->getType()->isArrayType();
4555 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4556}
4557
4558ExprResult
4559Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4560 Expr *idx, SourceLocation rbLoc) {
4561 if (base && !base->getType().isNull() &&
4562 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4563 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4564 SourceLocation(), /*Length*/ nullptr,
4565 /*Stride=*/nullptr, rbLoc);
4566
4567 // Since this might be a postfix expression, get rid of ParenListExprs.
4568 if (isa<ParenListExpr>(base)) {
4569 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4570 if (result.isInvalid()) return ExprError();
4571 base = result.get();
4572 }
4573
4574 // Check if base and idx form a MatrixSubscriptExpr.
4575 //
4576 // Helper to check for comma expressions, which are not allowed as indices for
4577 // matrix subscript expressions.
4578 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4579 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4580 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4581 << SourceRange(base->getBeginLoc(), rbLoc);
4582 return true;
4583 }
4584 return false;
4585 };
4586 // The matrix subscript operator ([][])is considered a single operator.
4587 // Separating the index expressions by parenthesis is not allowed.
4588 if (base->getType()->isSpecificPlaceholderType(
4589 BuiltinType::IncompleteMatrixIdx) &&
4590 !isa<MatrixSubscriptExpr>(base)) {
4591 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4592 << SourceRange(base->getBeginLoc(), rbLoc);
4593 return ExprError();
4594 }
4595 // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4596 // a new MatrixSubscriptExpr.
4597 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4598 if (matSubscriptE) {
4599 if (CheckAndReportCommaError(idx))
4600 return ExprError();
4601
4602 assert(matSubscriptE->isIncomplete() &&((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript"
) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4603, __PRETTY_FUNCTION__))
4603 "base has to be an incomplete matrix subscript")((matSubscriptE->isIncomplete() && "base has to be an incomplete matrix subscript"
) ? static_cast<void> (0) : __assert_fail ("matSubscriptE->isIncomplete() && \"base has to be an incomplete matrix subscript\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4603, __PRETTY_FUNCTION__))
;
4604 return CreateBuiltinMatrixSubscriptExpr(
4605 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4606 }
4607 Expr *matrixBase = base;
4608 bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4609 if (!IsMSPropertySubscript) {
4610 ExprResult result = CheckPlaceholderExpr(base);
4611 if (!result.isInvalid())
4612 matrixBase = result.get();
4613 }
4614 if (matrixBase->getType()->isMatrixType()) {
4615 if (CheckAndReportCommaError(idx))
4616 return ExprError();
4617
4618 return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4619 }
4620
4621 // A comma-expression as the index is deprecated in C++2a onwards.
4622 if (getLangOpts().CPlusPlus20 &&
4623 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4624 (isa<CXXOperatorCallExpr>(idx) &&
4625 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4626 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4627 << SourceRange(base->getBeginLoc(), rbLoc);
4628 }
4629
4630 // Handle any non-overload placeholder types in the base and index
4631 // expressions. We can't handle overloads here because the other
4632 // operand might be an overloadable type, in which case the overload
4633 // resolution for the operator overload should get the first crack
4634 // at the overload.
4635 if (base->getType()->isNonOverloadPlaceholderType()) {
4636 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4637 if (!IsMSPropertySubscript) {
4638 ExprResult result = CheckPlaceholderExpr(base);
4639 if (result.isInvalid())
4640 return ExprError();
4641 base = result.get();
4642 }
4643 }
4644 if (idx->getType()->isNonOverloadPlaceholderType()) {
4645 ExprResult result = CheckPlaceholderExpr(idx);
4646 if (result.isInvalid()) return ExprError();
4647 idx = result.get();
4648 }
4649
4650 // Build an unanalyzed expression if either operand is type-dependent.
4651 if (getLangOpts().CPlusPlus &&
4652 (base->isTypeDependent() || idx->isTypeDependent())) {
4653 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4654 VK_LValue, OK_Ordinary, rbLoc);
4655 }
4656
4657 // MSDN, property (C++)
4658 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4659 // This attribute can also be used in the declaration of an empty array in a
4660 // class or structure definition. For example:
4661 // __declspec(property(get=GetX, put=PutX)) int x[];
4662 // The above statement indicates that x[] can be used with one or more array
4663 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4664 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4665 if (IsMSPropertySubscript) {
4666 // Build MS property subscript expression if base is MS property reference
4667 // or MS property subscript.
4668 return new (Context) MSPropertySubscriptExpr(
4669 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4670 }
4671
4672 // Use C++ overloaded-operator rules if either operand has record
4673 // type. The spec says to do this if either type is *overloadable*,
4674 // but enum types can't declare subscript operators or conversion
4675 // operators, so there's nothing interesting for overload resolution
4676 // to do if there aren't any record types involved.
4677 //
4678 // ObjC pointers have their own subscripting logic that is not tied
4679 // to overload resolution and so should not take this path.
4680 if (getLangOpts().CPlusPlus &&
4681 (base->getType()->isRecordType() ||
4682 (!base->getType()->isObjCObjectPointerType() &&
4683 idx->getType()->isRecordType()))) {
4684 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4685 }
4686
4687 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4688
4689 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4690 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4691
4692 return Res;
4693}
4694
4695ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4696 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4697 InitializationKind Kind =
4698 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4699 InitializationSequence InitSeq(*this, Entity, Kind, E);
4700 return InitSeq.Perform(*this, Entity, Kind, E);
4701}
4702
4703ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4704 Expr *ColumnIdx,
4705 SourceLocation RBLoc) {
4706 ExprResult BaseR = CheckPlaceholderExpr(Base);
4707 if (BaseR.isInvalid())
4708 return BaseR;
4709 Base = BaseR.get();
4710
4711 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4712 if (RowR.isInvalid())
4713 return RowR;
4714 RowIdx = RowR.get();
4715
4716 if (!ColumnIdx)
4717 return new (Context) MatrixSubscriptExpr(
4718 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4719
4720 // Build an unanalyzed expression if any of the operands is type-dependent.
4721 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4722 ColumnIdx->isTypeDependent())
4723 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4724 Context.DependentTy, RBLoc);
4725
4726 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4727 if (ColumnR.isInvalid())
4728 return ColumnR;
4729 ColumnIdx = ColumnR.get();
4730
4731 // Check that IndexExpr is an integer expression. If it is a constant
4732 // expression, check that it is less than Dim (= the number of elements in the
4733 // corresponding dimension).
4734 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4735 bool IsColumnIdx) -> Expr * {
4736 if (!IndexExpr->getType()->isIntegerType() &&
4737 !IndexExpr->isTypeDependent()) {
4738 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4739 << IsColumnIdx;
4740 return nullptr;
4741 }
4742
4743 if (Optional<llvm::APSInt> Idx =
4744 IndexExpr->getIntegerConstantExpr(Context)) {
4745 if ((*Idx < 0 || *Idx >= Dim)) {
4746 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4747 << IsColumnIdx << Dim;
4748 return nullptr;
4749 }
4750 }
4751
4752 ExprResult ConvExpr =
4753 tryConvertExprToType(IndexExpr, Context.getSizeType());
4754 assert(!ConvExpr.isInvalid() &&((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4755, __PRETTY_FUNCTION__))
4755 "should be able to convert any integer type to size type")((!ConvExpr.isInvalid() && "should be able to convert any integer type to size type"
) ? static_cast<void> (0) : __assert_fail ("!ConvExpr.isInvalid() && \"should be able to convert any integer type to size type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 4755, __PRETTY_FUNCTION__))
;
4756 return ConvExpr.get();
4757 };
4758
4759 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4760 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4761 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4762 if (!RowIdx || !ColumnIdx)
4763 return ExprError();
4764
4765 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4766 MTy->getElementType(), RBLoc);
4767}
4768
4769void Sema::CheckAddressOfNoDeref(const Expr *E) {
4770 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4771 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4772
4773 // For expressions like `&(*s).b`, the base is recorded and what should be
4774 // checked.
4775 const MemberExpr *Member = nullptr;
4776 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4777 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4778
4779 LastRecord.PossibleDerefs.erase(StrippedExpr);
4780}
4781
4782void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4783 QualType ResultTy = E->getType();
4784 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4785
4786 // Bail if the element is an array since it is not memory access.
4787 if (isa<ArrayType>(ResultTy))
4788 return;
4789
4790 if (ResultTy->hasAttr(attr::NoDeref)) {
4791 LastRecord.PossibleDerefs.insert(E);
4792 return;
4793 }
4794
4795 // Check if the base type is a pointer to a member access of a struct
4796 // marked with noderef.
4797 const Expr *Base = E->getBase();
4798 QualType BaseTy = Base->getType();
4799 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4800 // Not a pointer access
4801 return;
4802
4803 const MemberExpr *Member = nullptr;
4804 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4805 Member->isArrow())
4806 Base = Member->getBase();
4807
4808 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4809 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4810 LastRecord.PossibleDerefs.insert(E);
4811 }
4812}
4813
4814ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4815 Expr *LowerBound,
4816 SourceLocation ColonLocFirst,
4817 SourceLocation ColonLocSecond,
4818 Expr *Length, Expr *Stride,
4819 SourceLocation RBLoc) {
4820 if (Base->getType()->isPlaceholderType() &&
4821 !Base->getType()->isSpecificPlaceholderType(
4822 BuiltinType::OMPArraySection)) {
4823 ExprResult Result = CheckPlaceholderExpr(Base);
4824 if (Result.isInvalid())
4825 return ExprError();
4826 Base = Result.get();
4827 }
4828 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4829 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4830 if (Result.isInvalid())
4831 return ExprError();
4832 Result = DefaultLvalueConversion(Result.get());
4833 if (Result.isInvalid())
4834 return ExprError();
4835 LowerBound = Result.get();
4836 }
4837 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4838 ExprResult Result = CheckPlaceholderExpr(Length);
4839 if (Result.isInvalid())
4840 return ExprError();
4841 Result = DefaultLvalueConversion(Result.get());
4842 if (Result.isInvalid())
4843 return ExprError();
4844 Length = Result.get();
4845 }
4846 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4847 ExprResult Result = CheckPlaceholderExpr(Stride);
4848 if (Result.isInvalid())
4849 return ExprError();
4850 Result = DefaultLvalueConversion(Result.get());
4851 if (Result.isInvalid())
4852 return ExprError();
4853 Stride = Result.get();
4854 }
4855
4856 // Build an unanalyzed expression if either operand is type-dependent.
4857 if (Base->isTypeDependent() ||
4858 (LowerBound &&
4859 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4860 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4861 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4862 return new (Context) OMPArraySectionExpr(
4863 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4864 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4865 }
4866
4867 // Perform default conversions.
4868 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4869 QualType ResultTy;
4870 if (OriginalTy->isAnyPointerType()) {
4871 ResultTy = OriginalTy->getPointeeType();
4872 } else if (OriginalTy->isArrayType()) {
4873 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4874 } else {
4875 return ExprError(
4876 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4877 << Base->getSourceRange());
4878 }
4879 // C99 6.5.2.1p1
4880 if (LowerBound) {
4881 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4882 LowerBound);
4883 if (Res.isInvalid())
4884 return ExprError(Diag(LowerBound->getExprLoc(),
4885 diag::err_omp_typecheck_section_not_integer)
4886 << 0 << LowerBound->getSourceRange());
4887 LowerBound = Res.get();
4888
4889 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4890 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4891 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4892 << 0 << LowerBound->getSourceRange();
4893 }
4894 if (Length) {
4895 auto Res =
4896 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4897 if (Res.isInvalid())
4898 return ExprError(Diag(Length->getExprLoc(),
4899 diag::err_omp_typecheck_section_not_integer)
4900 << 1 << Length->getSourceRange());
4901 Length = Res.get();
4902
4903 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4904 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4905 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4906 << 1 << Length->getSourceRange();
4907 }
4908 if (Stride) {
4909 ExprResult Res =
4910 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4911 if (Res.isInvalid())
4912 return ExprError(Diag(Stride->getExprLoc(),
4913 diag::err_omp_typecheck_section_not_integer)
4914 << 1 << Stride->getSourceRange());
4915 Stride = Res.get();
4916
4917 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4918 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4919 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4920 << 1 << Stride->getSourceRange();
4921 }
4922
4923 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4924 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4925 // type. Note that functions are not objects, and that (in C99 parlance)
4926 // incomplete types are not object types.
4927 if (ResultTy->isFunctionType()) {
4928 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4929 << ResultTy << Base->getSourceRange();
4930 return ExprError();
4931 }
4932
4933 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4934 diag::err_omp_section_incomplete_type, Base))
4935 return ExprError();
4936
4937 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4938 Expr::EvalResult Result;
4939 if (LowerBound->EvaluateAsInt(Result, Context)) {
4940 // OpenMP 5.0, [2.1.5 Array Sections]
4941 // The array section must be a subset of the original array.
4942 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4943 if (LowerBoundValue.isNegative()) {
4944 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4945 << LowerBound->getSourceRange();
4946 return ExprError();
4947 }
4948 }
4949 }
4950
4951 if (Length) {
4952 Expr::EvalResult Result;
4953 if (Length->EvaluateAsInt(Result, Context)) {
4954 // OpenMP 5.0, [2.1.5 Array Sections]
4955 // The length must evaluate to non-negative integers.
4956 llvm::APSInt LengthValue = Result.Val.getInt();
4957 if (LengthValue.isNegative()) {
4958 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4959 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4960 << Length->getSourceRange();
4961 return ExprError();
4962 }
4963 }
4964 } else if (ColonLocFirst.isValid() &&
4965 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4966 !OriginalTy->isVariableArrayType()))) {
4967 // OpenMP 5.0, [2.1.5 Array Sections]
4968 // When the size of the array dimension is not known, the length must be
4969 // specified explicitly.
4970 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4971 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4972 return ExprError();
4973 }
4974
4975 if (Stride) {
4976 Expr::EvalResult Result;
4977 if (Stride->EvaluateAsInt(Result, Context)) {
4978 // OpenMP 5.0, [2.1.5 Array Sections]
4979 // The stride must evaluate to a positive integer.
4980 llvm::APSInt StrideValue = Result.Val.getInt();
4981 if (!StrideValue.isStrictlyPositive()) {
4982 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4983 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4984 << Stride->getSourceRange();
4985 return ExprError();
4986 }
4987 }
4988 }
4989
4990 if (!Base->getType()->isSpecificPlaceholderType(
4991 BuiltinType::OMPArraySection)) {
4992 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4993 if (Result.isInvalid())
4994 return ExprError();
4995 Base = Result.get();
4996 }
4997 return new (Context) OMPArraySectionExpr(
4998 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
4999 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5000}
5001
5002ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5003 SourceLocation RParenLoc,
5004 ArrayRef<Expr *> Dims,
5005 ArrayRef<SourceRange> Brackets) {
5006 if (Base->getType()->isPlaceholderType()) {
5007 ExprResult Result = CheckPlaceholderExpr(Base);
5008 if (Result.isInvalid())
5009 return ExprError();
5010 Result = DefaultLvalueConversion(Result.get());
5011 if (Result.isInvalid())
5012 return ExprError();
5013 Base = Result.get();
5014 }
5015 QualType BaseTy = Base->getType();
5016 // Delay analysis of the types/expressions if instantiation/specialization is
5017 // required.
5018 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5019 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5020 LParenLoc, RParenLoc, Dims, Brackets);
5021 if (!BaseTy->isPointerType() ||
5022 (!Base->isTypeDependent() &&
5023 BaseTy->getPointeeType()->isIncompleteType()))
5024 return ExprError(Diag(Base->getExprLoc(),
5025 diag::err_omp_non_pointer_type_array_shaping_base)
5026 << Base->getSourceRange());
5027
5028 SmallVector<Expr *, 4> NewDims;
5029 bool ErrorFound = false;
5030 for (Expr *Dim : Dims) {
5031 if (Dim->getType()->isPlaceholderType()) {
5032 ExprResult Result = CheckPlaceholderExpr(Dim);
5033 if (Result.isInvalid()) {
5034 ErrorFound = true;
5035 continue;
5036 }
5037 Result = DefaultLvalueConversion(Result.get());
5038 if (Result.isInvalid()) {
5039 ErrorFound = true;
5040 continue;
5041 }
5042 Dim = Result.get();
5043 }
5044 if (!Dim->isTypeDependent()) {
5045 ExprResult Result =
5046 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5047 if (Result.isInvalid()) {
5048 ErrorFound = true;
5049 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5050 << Dim->getSourceRange();
5051 continue;
5052 }
5053 Dim = Result.get();
5054 Expr::EvalResult EvResult;
5055 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5056 // OpenMP 5.0, [2.1.4 Array Shaping]
5057 // Each si is an integral type expression that must evaluate to a
5058 // positive integer.
5059 llvm::APSInt Value = EvResult.Val.getInt();
5060 if (!Value.isStrictlyPositive()) {
5061 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5062 << Value.toString(/*Radix=*/10, /*Signed=*/true)
5063 << Dim->getSourceRange();
5064 ErrorFound = true;
5065 continue;
5066 }
5067 }
5068 }
5069 NewDims.push_back(Dim);
5070 }
5071 if (ErrorFound)
5072 return ExprError();
5073 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5074 LParenLoc, RParenLoc, NewDims, Brackets);
5075}
5076
5077ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5078 SourceLocation LLoc, SourceLocation RLoc,
5079 ArrayRef<OMPIteratorData> Data) {
5080 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5081 bool IsCorrect = true;
5082 for (const OMPIteratorData &D : Data) {
5083 TypeSourceInfo *TInfo = nullptr;
5084 SourceLocation StartLoc;
5085 QualType DeclTy;
5086 if (!D.Type.getAsOpaquePtr()) {
5087 // OpenMP 5.0, 2.1.6 Iterators
5088 // In an iterator-specifier, if the iterator-type is not specified then
5089 // the type of that iterator is of int type.
5090 DeclTy = Context.IntTy;
5091 StartLoc = D.DeclIdentLoc;
5092 } else {
5093 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5094 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5095 }
5096
5097 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5098 DeclTy->containsUnexpandedParameterPack() ||
5099 DeclTy->isInstantiationDependentType();
5100 if (!IsDeclTyDependent) {
5101 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5102 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5103 // The iterator-type must be an integral or pointer type.
5104 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5105 << DeclTy;
5106 IsCorrect = false;
5107 continue;
5108 }
5109 if (DeclTy.isConstant(Context)) {
5110 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5111 // The iterator-type must not be const qualified.
5112 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5113 << DeclTy;
5114 IsCorrect = false;
5115 continue;
5116 }
5117 }
5118
5119 // Iterator declaration.
5120 assert(D.DeclIdent && "Identifier expected.")((D.DeclIdent && "Identifier expected.") ? static_cast
<void> (0) : __assert_fail ("D.DeclIdent && \"Identifier expected.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5120, __PRETTY_FUNCTION__))
;
5121 // Always try to create iterator declarator to avoid extra error messages
5122 // about unknown declarations use.
5123 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5124 D.DeclIdent, DeclTy, TInfo, SC_None);
5125 VD->setImplicit();
5126 if (S) {
5127 // Check for conflicting previous declaration.
5128 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5129 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5130 ForVisibleRedeclaration);
5131 Previous.suppressDiagnostics();
5132 LookupName(Previous, S);
5133
5134 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5135 /*AllowInlineNamespace=*/false);
5136 if (!Previous.empty()) {
5137 NamedDecl *Old = Previous.getRepresentativeDecl();
5138 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5139 Diag(Old->getLocation(), diag::note_previous_definition);
5140 } else {
5141 PushOnScopeChains(VD, S);
5142 }
5143 } else {
5144 CurContext->addDecl(VD);
5145 }
5146 Expr *Begin = D.Range.Begin;
5147 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5148 ExprResult BeginRes =
5149 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5150 Begin = BeginRes.get();
5151 }
5152 Expr *End = D.Range.End;
5153 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5154 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5155 End = EndRes.get();
5156 }
5157 Expr *Step = D.Range.Step;
5158 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5159 if (!Step->getType()->isIntegralType(Context)) {
5160 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5161 << Step << Step->getSourceRange();
5162 IsCorrect = false;
5163 continue;
5164 }
5165 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5166 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5167 // If the step expression of a range-specification equals zero, the
5168 // behavior is unspecified.
5169 if (Result && Result->isNullValue()) {
5170 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5171 << Step << Step->getSourceRange();
5172 IsCorrect = false;
5173 continue;
5174 }
5175 }
5176 if (!Begin || !End || !IsCorrect) {
5177 IsCorrect = false;
5178 continue;
5179 }
5180 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5181 IDElem.IteratorDecl = VD;
5182 IDElem.AssignmentLoc = D.AssignLoc;
5183 IDElem.Range.Begin = Begin;
5184 IDElem.Range.End = End;
5185 IDElem.Range.Step = Step;
5186 IDElem.ColonLoc = D.ColonLoc;
5187 IDElem.SecondColonLoc = D.SecColonLoc;
5188 }
5189 if (!IsCorrect) {
5190 // Invalidate all created iterator declarations if error is found.
5191 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5192 if (Decl *ID = D.IteratorDecl)
5193 ID->setInvalidDecl();
5194 }
5195 return ExprError();
5196 }
5197 SmallVector<OMPIteratorHelperData, 4> Helpers;
5198 if (!CurContext->isDependentContext()) {
5199 // Build number of ityeration for each iteration range.
5200 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5201 // ((Begini-Stepi-1-Endi) / -Stepi);
5202 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5203 // (Endi - Begini)
5204 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5205 D.Range.Begin);
5206 if(!Res.isUsable()) {
5207 IsCorrect = false;
5208 continue;
5209 }
5210 ExprResult St, St1;
5211 if (D.Range.Step) {
5212 St = D.Range.Step;
5213 // (Endi - Begini) + Stepi
5214 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5215 if (!Res.isUsable()) {
5216 IsCorrect = false;
5217 continue;
5218 }
5219 // (Endi - Begini) + Stepi - 1
5220 Res =
5221 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5222 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5223 if (!Res.isUsable()) {
5224 IsCorrect = false;
5225 continue;
5226 }
5227 // ((Endi - Begini) + Stepi - 1) / Stepi
5228 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5229 if (!Res.isUsable()) {
5230 IsCorrect = false;
5231 continue;
5232 }
5233 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5234 // (Begini - Endi)
5235 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5236 D.Range.Begin, D.Range.End);
5237 if (!Res1.isUsable()) {
5238 IsCorrect = false;
5239 continue;
5240 }
5241 // (Begini - Endi) - Stepi
5242 Res1 =
5243 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5244 if (!Res1.isUsable()) {
5245 IsCorrect = false;
5246 continue;
5247 }
5248 // (Begini - Endi) - Stepi - 1
5249 Res1 =
5250 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5251 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5252 if (!Res1.isUsable()) {
5253 IsCorrect = false;
5254 continue;
5255 }
5256 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5257 Res1 =
5258 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5259 if (!Res1.isUsable()) {
5260 IsCorrect = false;
5261 continue;
5262 }
5263 // Stepi > 0.
5264 ExprResult CmpRes =
5265 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5266 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5267 if (!CmpRes.isUsable()) {
5268 IsCorrect = false;
5269 continue;
5270 }
5271 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5272 Res.get(), Res1.get());
5273 if (!Res.isUsable()) {
5274 IsCorrect = false;
5275 continue;
5276 }
5277 }
5278 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5279 if (!Res.isUsable()) {
5280 IsCorrect = false;
5281 continue;
5282 }
5283
5284 // Build counter update.
5285 // Build counter.
5286 auto *CounterVD =
5287 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5288 D.IteratorDecl->getBeginLoc(), nullptr,
5289 Res.get()->getType(), nullptr, SC_None);
5290 CounterVD->setImplicit();
5291 ExprResult RefRes =
5292 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5293 D.IteratorDecl->getBeginLoc());
5294 // Build counter update.
5295 // I = Begini + counter * Stepi;
5296 ExprResult UpdateRes;
5297 if (D.Range.Step) {
5298 UpdateRes = CreateBuiltinBinOp(
5299 D.AssignmentLoc, BO_Mul,
5300 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5301 } else {
5302 UpdateRes = DefaultLvalueConversion(RefRes.get());
5303 }
5304 if (!UpdateRes.isUsable()) {
5305 IsCorrect = false;
5306 continue;
5307 }
5308 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5309 UpdateRes.get());
5310 if (!UpdateRes.isUsable()) {
5311 IsCorrect = false;
5312 continue;
5313 }
5314 ExprResult VDRes =
5315 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5316 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5317 D.IteratorDecl->getBeginLoc());
5318 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5319 UpdateRes.get());
5320 if (!UpdateRes.isUsable()) {
5321 IsCorrect = false;
5322 continue;
5323 }
5324 UpdateRes =
5325 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5326 if (!UpdateRes.isUsable()) {
5327 IsCorrect = false;
5328 continue;
5329 }
5330 ExprResult CounterUpdateRes =
5331 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5332 if (!CounterUpdateRes.isUsable()) {
5333 IsCorrect = false;
5334 continue;
5335 }
5336 CounterUpdateRes =
5337 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5338 if (!CounterUpdateRes.isUsable()) {
5339 IsCorrect = false;
5340 continue;
5341 }
5342 OMPIteratorHelperData &HD = Helpers.emplace_back();
5343 HD.CounterVD = CounterVD;
5344 HD.Upper = Res.get();
5345 HD.Update = UpdateRes.get();
5346 HD.CounterUpdate = CounterUpdateRes.get();
5347 }
5348 } else {
5349 Helpers.assign(ID.size(), {});
5350 }
5351 if (!IsCorrect) {
5352 // Invalidate all created iterator declarations if error is found.
5353 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5354 if (Decl *ID = D.IteratorDecl)
5355 ID->setInvalidDecl();
5356 }
5357 return ExprError();
5358 }
5359 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5360 LLoc, RLoc, ID, Helpers);
5361}
5362
5363ExprResult
5364Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5365 Expr *Idx, SourceLocation RLoc) {
5366 Expr *LHSExp = Base;
5367 Expr *RHSExp = Idx;
5368
5369 ExprValueKind VK = VK_LValue;
5370 ExprObjectKind OK = OK_Ordinary;
5371
5372 // Per C++ core issue 1213, the result is an xvalue if either operand is
5373 // a non-lvalue array, and an lvalue otherwise.
5374 if (getLangOpts().CPlusPlus11) {
5375 for (auto *Op : {LHSExp, RHSExp}) {
5376 Op = Op->IgnoreImplicit();
5377 if (Op->getType()->isArrayType() && !Op->isLValue())
5378 VK = VK_XValue;
5379 }
5380 }
5381
5382 // Perform default conversions.
5383 if (!LHSExp->getType()->getAs<VectorType>()) {
5384 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5385 if (Result.isInvalid())
5386 return ExprError();
5387 LHSExp = Result.get();
5388 }
5389 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5390 if (Result.isInvalid())
5391 return ExprError();
5392 RHSExp = Result.get();
5393
5394 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5395
5396 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5397 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5398 // in the subscript position. As a result, we need to derive the array base
5399 // and index from the expression types.
5400 Expr *BaseExpr, *IndexExpr;
5401 QualType ResultType;
5402 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5403 BaseExpr = LHSExp;
5404 IndexExpr = RHSExp;
5405 ResultType = Context.DependentTy;
5406 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5407 BaseExpr = LHSExp;
5408 IndexExpr = RHSExp;
5409 ResultType = PTy->getPointeeType();
5410 } else if (const ObjCObjectPointerType *PTy =
5411 LHSTy->getAs<ObjCObjectPointerType>()) {
5412 BaseExpr = LHSExp;
5413 IndexExpr = RHSExp;
5414
5415 // Use custom logic if this should be the pseudo-object subscript
5416 // expression.
5417 if (!LangOpts.isSubscriptPointerArithmetic())
5418 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5419 nullptr);
5420
5421 ResultType = PTy->getPointeeType();
5422 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5423 // Handle the uncommon case of "123[Ptr]".
5424 BaseExpr = RHSExp;
5425 IndexExpr = LHSExp;
5426 ResultType = PTy->getPointeeType();
5427 } else if (const ObjCObjectPointerType *PTy =
5428 RHSTy->getAs<ObjCObjectPointerType>()) {
5429 // Handle the uncommon case of "123[Ptr]".
5430 BaseExpr = RHSExp;
5431 IndexExpr = LHSExp;
5432 ResultType = PTy->getPointeeType();
5433 if (!LangOpts.isSubscriptPointerArithmetic()) {
5434 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5435 << ResultType << BaseExpr->getSourceRange();
5436 return ExprError();
5437 }
5438 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5439 BaseExpr = LHSExp; // vectors: V[123]
5440 IndexExpr = RHSExp;
5441 // We apply C++ DR1213 to vector subscripting too.
5442 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5443 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5444 if (Materialized.isInvalid())
5445 return ExprError();
5446 LHSExp = Materialized.get();
5447 }
5448 VK = LHSExp->getValueKind();
5449 if (VK != VK_RValue)
5450 OK = OK_VectorComponent;
5451
5452 ResultType = VTy->getElementType();
5453 QualType BaseType = BaseExpr->getType();
5454 Qualifiers BaseQuals = BaseType.getQualifiers();
5455 Qualifiers MemberQuals = ResultType.getQualifiers();
5456 Qualifiers Combined = BaseQuals + MemberQuals;
5457 if (Combined != MemberQuals)
5458 ResultType = Context.getQualifiedType(ResultType, Combined);
5459 } else if (LHSTy->isArrayType()) {
5460 // If we see an array that wasn't promoted by
5461 // DefaultFunctionArrayLvalueConversion, it must be an array that
5462 // wasn't promoted because of the C90 rule that doesn't
5463 // allow promoting non-lvalue arrays. Warn, then
5464 // force the promotion here.
5465 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5466 << LHSExp->getSourceRange();
5467 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5468 CK_ArrayToPointerDecay).get();
5469 LHSTy = LHSExp->getType();
5470
5471 BaseExpr = LHSExp;
5472 IndexExpr = RHSExp;
5473 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5474 } else if (RHSTy->isArrayType()) {
5475 // Same as previous, except for 123[f().a] case
5476 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5477 << RHSExp->getSourceRange();
5478 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5479 CK_ArrayToPointerDecay).get();
5480 RHSTy = RHSExp->getType();
5481
5482 BaseExpr = RHSExp;
5483 IndexExpr = LHSExp;
5484 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5485 } else {
5486 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5487 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5488 }
5489 // C99 6.5.2.1p1
5490 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5491 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5492 << IndexExpr->getSourceRange());
5493
5494 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5495 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5496 && !IndexExpr->isTypeDependent())
5497 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5498
5499 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5500 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5501 // type. Note that Functions are not objects, and that (in C99 parlance)
5502 // incomplete types are not object types.
5503 if (ResultType->isFunctionType()) {
5504 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5505 << ResultType << BaseExpr->getSourceRange();
5506 return ExprError();
5507 }
5508
5509 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5510 // GNU extension: subscripting on pointer to void
5511 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5512 << BaseExpr->getSourceRange();
5513
5514 // C forbids expressions of unqualified void type from being l-values.
5515 // See IsCForbiddenLValueType.
5516 if (!ResultType.hasQualifiers()) VK = VK_RValue;
5517 } else if (!ResultType->isDependentType() &&
5518 RequireCompleteSizedType(
5519 LLoc, ResultType,
5520 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5521 return ExprError();
5522
5523 assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5524, __PRETTY_FUNCTION__))
5524 !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5524, __PRETTY_FUNCTION__))
;
5525
5526 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5527 FunctionScopes.size() > 1) {
5528 if (auto *TT =
5529 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5530 for (auto I = FunctionScopes.rbegin(),
5531 E = std::prev(FunctionScopes.rend());
5532 I != E; ++I) {
5533 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5534 if (CSI == nullptr)
5535 break;
5536 DeclContext *DC = nullptr;
5537 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5538 DC = LSI->CallOperator;
5539 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5540 DC = CRSI->TheCapturedDecl;
5541 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5542 DC = BSI->TheDecl;
5543 if (DC) {
5544 if (DC->containsDecl(TT->getDecl()))
5545 break;
5546 captureVariablyModifiedType(
5547 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5548 }
5549 }
5550 }
5551 }
5552
5553 return new (Context)
5554 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5555}
5556
5557bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5558 ParmVarDecl *Param) {
5559 if (Param->hasUnparsedDefaultArg()) {
5560 // If we've already cleared out the location for the default argument,
5561 // that means we're parsing it right now.
5562 if (!UnparsedDefaultArgLocs.count(Param)) {
5563 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5564 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5565 Param->setInvalidDecl();
5566 return true;
5567 }
5568
5569 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5570 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5571 Diag(UnparsedDefaultArgLocs[Param],
5572 diag::note_default_argument_declared_here);
5573 return true;
5574 }
5575
5576 if (Param->hasUninstantiatedDefaultArg() &&
5577 InstantiateDefaultArgument(CallLoc, FD, Param))
5578 return true;
5579
5580 assert(Param->hasInit() && "default argument but no initializer?")((Param->hasInit() && "default argument but no initializer?"
) ? static_cast<void> (0) : __assert_fail ("Param->hasInit() && \"default argument but no initializer?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5580, __PRETTY_FUNCTION__))
;
5581
5582 // If the default expression creates temporaries, we need to
5583 // push them to the current stack of expression temporaries so they'll
5584 // be properly destroyed.
5585 // FIXME: We should really be rebuilding the default argument with new
5586 // bound temporaries; see the comment in PR5810.
5587 // We don't need to do that with block decls, though, because
5588 // blocks in default argument expression can never capture anything.
5589 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5590 // Set the "needs cleanups" bit regardless of whether there are
5591 // any explicit objects.
5592 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5593
5594 // Append all the objects to the cleanup list. Right now, this
5595 // should always be a no-op, because blocks in default argument
5596 // expressions should never be able to capture anything.
5597 assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5598, __PRETTY_FUNCTION__))
5598 "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5598, __PRETTY_FUNCTION__))
;
5599 }
5600
5601 // We already type-checked the argument, so we know it works.
5602 // Just mark all of the declarations in this potentially-evaluated expression
5603 // as being "referenced".
5604 EnterExpressionEvaluationContext EvalContext(
5605 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5606 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5607 /*SkipLocalVariables=*/true);
5608 return false;
5609}
5610
5611ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5612 FunctionDecl *FD, ParmVarDecl *Param) {
5613 assert(Param->hasDefaultArg() && "can't build nonexistent default arg")((Param->hasDefaultArg() && "can't build nonexistent default arg"
) ? static_cast<void> (0) : __assert_fail ("Param->hasDefaultArg() && \"can't build nonexistent default arg\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5613, __PRETTY_FUNCTION__))
;
5614 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5615 return ExprError();
5616 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5617}
5618
5619Sema::VariadicCallType
5620Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5621 Expr *Fn) {
5622 if (Proto && Proto->isVariadic()) {
5623 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5624 return VariadicConstructor;
5625 else if (Fn && Fn->getType()->isBlockPointerType())
5626 return VariadicBlock;
5627 else if (FDecl) {
5628 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5629 if (Method->isInstance())
5630 return VariadicMethod;
5631 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5632 return VariadicMethod;
5633 return VariadicFunction;
5634 }
5635 return VariadicDoesNotApply;
5636}
5637
5638namespace {
5639class FunctionCallCCC final : public FunctionCallFilterCCC {
5640public:
5641 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5642 unsigned NumArgs, MemberExpr *ME)
5643 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5644 FunctionName(FuncName) {}
5645
5646 bool ValidateCandidate(const TypoCorrection &candidate) override {
5647 if (!candidate.getCorrectionSpecifier() ||
5648 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5649 return false;
5650 }
5651
5652 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5653 }
5654
5655 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5656 return std::make_unique<FunctionCallCCC>(*this);
5657 }
5658
5659private:
5660 const IdentifierInfo *const FunctionName;
5661};
5662}
5663
5664static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5665 FunctionDecl *FDecl,
5666 ArrayRef<Expr *> Args) {
5667 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5668 DeclarationName FuncName = FDecl->getDeclName();
5669 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5670
5671 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5672 if (TypoCorrection Corrected = S.CorrectTypo(
5673 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5674 S.getScopeForContext(S.CurContext), nullptr, CCC,
5675 Sema::CTK_ErrorRecovery)) {
5676 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5677 if (Corrected.isOverloaded()) {
5678 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5679 OverloadCandidateSet::iterator Best;
5680 for (NamedDecl *CD : Corrected) {
5681 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5682 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5683 OCS);
5684 }
5685 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5686 case OR_Success:
5687 ND = Best->FoundDecl;
5688 Corrected.setCorrectionDecl(ND);
5689 break;
5690 default:
5691 break;
5692 }
5693 }
5694 ND = ND->getUnderlyingDecl();
5695 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5696 return Corrected;
5697 }
5698 }
5699 return TypoCorrection();
5700}
5701
5702/// ConvertArgumentsForCall - Converts the arguments specified in
5703/// Args/NumArgs to the parameter types of the function FDecl with
5704/// function prototype Proto. Call is the call expression itself, and
5705/// Fn is the function expression. For a C++ member function, this
5706/// routine does not attempt to convert the object argument. Returns
5707/// true if the call is ill-formed.
5708bool
5709Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5710 FunctionDecl *FDecl,
5711 const FunctionProtoType *Proto,
5712 ArrayRef<Expr *> Args,
5713 SourceLocation RParenLoc,
5714 bool IsExecConfig) {
5715 // Bail out early if calling a builtin with custom typechecking.
5716 if (FDecl)
5717 if (unsigned ID = FDecl->getBuiltinID())
5718 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5719 return false;
5720
5721 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5722 // assignment, to the types of the corresponding parameter, ...
5723 unsigned NumParams = Proto->getNumParams();
5724 bool Invalid = false;
5725 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5726 unsigned FnKind = Fn->getType()->isBlockPointerType()
5727 ? 1 /* block */
5728 : (IsExecConfig ? 3 /* kernel function (exec config) */
5729 : 0 /* function */);
5730
5731 // If too few arguments are available (and we don't have default
5732 // arguments for the remaining parameters), don't make the call.
5733 if (Args.size() < NumParams) {
5734 if (Args.size() < MinArgs) {
5735 TypoCorrection TC;
5736 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5737 unsigned diag_id =
5738 MinArgs == NumParams && !Proto->isVariadic()
5739 ? diag::err_typecheck_call_too_few_args_suggest
5740 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5741 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5742 << static_cast<unsigned>(Args.size())
5743 << TC.getCorrectionRange());
5744 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5745 Diag(RParenLoc,
5746 MinArgs == NumParams && !Proto->isVariadic()
5747 ? diag::err_typecheck_call_too_few_args_one
5748 : diag::err_typecheck_call_too_few_args_at_least_one)
5749 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5750 else
5751 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5752 ? diag::err_typecheck_call_too_few_args
5753 : diag::err_typecheck_call_too_few_args_at_least)
5754 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5755 << Fn->getSourceRange();
5756
5757 // Emit the location of the prototype.
5758 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5759 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5760
5761 return true;
5762 }
5763 // We reserve space for the default arguments when we create
5764 // the call expression, before calling ConvertArgumentsForCall.
5765 assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5766, __PRETTY_FUNCTION__))
5766 "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5766, __PRETTY_FUNCTION__))
;
5767 }
5768
5769 // If too many are passed and not variadic, error on the extras and drop
5770 // them.
5771 if (Args.size() > NumParams) {
5772 if (!Proto->isVariadic()) {
5773 TypoCorrection TC;
5774 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5775 unsigned diag_id =
5776 MinArgs == NumParams && !Proto->isVariadic()
5777 ? diag::err_typecheck_call_too_many_args_suggest
5778 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5779 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5780 << static_cast<unsigned>(Args.size())
5781 << TC.getCorrectionRange());
5782 } else if (NumParams == 1 && FDecl &&
5783 FDecl->getParamDecl(0)->getDeclName())
5784 Diag(Args[NumParams]->getBeginLoc(),
5785 MinArgs == NumParams
5786 ? diag::err_typecheck_call_too_many_args_one
5787 : diag::err_typecheck_call_too_many_args_at_most_one)
5788 << FnKind << FDecl->getParamDecl(0)
5789 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5790 << SourceRange(Args[NumParams]->getBeginLoc(),
5791 Args.back()->getEndLoc());
5792 else
5793 Diag(Args[NumParams]->getBeginLoc(),
5794 MinArgs == NumParams
5795 ? diag::err_typecheck_call_too_many_args
5796 : diag::err_typecheck_call_too_many_args_at_most)
5797 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5798 << Fn->getSourceRange()
5799 << SourceRange(Args[NumParams]->getBeginLoc(),
5800 Args.back()->getEndLoc());
5801
5802 // Emit the location of the prototype.
5803 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5804 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5805
5806 // This deletes the extra arguments.
5807 Call->shrinkNumArgs(NumParams);
5808 return true;
5809 }
5810 }
5811 SmallVector<Expr *, 8> AllArgs;
5812 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5813
5814 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5815 AllArgs, CallType);
5816 if (Invalid)
5817 return true;
5818 unsigned TotalNumArgs = AllArgs.size();
5819 for (unsigned i = 0; i < TotalNumArgs; ++i)
5820 Call->setArg(i, AllArgs[i]);
5821
5822 return false;
5823}
5824
5825bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5826 const FunctionProtoType *Proto,
5827 unsigned FirstParam, ArrayRef<Expr *> Args,
5828 SmallVectorImpl<Expr *> &AllArgs,
5829 VariadicCallType CallType, bool AllowExplicit,
5830 bool IsListInitialization) {
5831 unsigned NumParams = Proto->getNumParams();
5832 bool Invalid = false;
5833 size_t ArgIx = 0;
5834 // Continue to check argument types (even if we have too few/many args).
5835 for (unsigned i = FirstParam; i < NumParams; i++) {
5836 QualType ProtoArgType = Proto->getParamType(i);
5837
5838 Expr *Arg;
5839 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5840 if (ArgIx < Args.size()) {
5841 Arg = Args[ArgIx++];
5842
5843 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5844 diag::err_call_incomplete_argument, Arg))
5845 return true;
5846
5847 // Strip the unbridged-cast placeholder expression off, if applicable.
5848 bool CFAudited = false;
5849 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5850 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5851 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5852 Arg = stripARCUnbridgedCast(Arg);
5853 else if (getLangOpts().ObjCAutoRefCount &&
5854 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5855 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5856 CFAudited = true;
5857
5858 if (Proto->getExtParameterInfo(i).isNoEscape())
5859 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5860 BE->getBlockDecl()->setDoesNotEscape();
5861
5862 InitializedEntity Entity =
5863 Param ? InitializedEntity::InitializeParameter(Context, Param,
5864 ProtoArgType)
5865 : InitializedEntity::InitializeParameter(
5866 Context, ProtoArgType, Proto->isParamConsumed(i));
5867
5868 // Remember that parameter belongs to a CF audited API.
5869 if (CFAudited)
5870 Entity.setParameterCFAudited();
5871
5872 ExprResult ArgE = PerformCopyInitialization(
5873 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5874 if (ArgE.isInvalid())
5875 return true;
5876
5877 Arg = ArgE.getAs<Expr>();
5878 } else {
5879 assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee"
) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 5879, __PRETTY_FUNCTION__))
;
5880
5881 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5882 if (ArgExpr.isInvalid())
5883 return true;
5884
5885 Arg = ArgExpr.getAs<Expr>();
5886 }
5887
5888 // Check for array bounds violations for each argument to the call. This
5889 // check only triggers warnings when the argument isn't a more complex Expr
5890 // with its own checking, such as a BinaryOperator.
5891 CheckArrayAccess(Arg);
5892
5893 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5894 CheckStaticArrayArgument(CallLoc, Param, Arg);
5895
5896 AllArgs.push_back(Arg);
5897 }
5898
5899 // If this is a variadic call, handle args passed through "...".
5900 if (CallType != VariadicDoesNotApply) {
5901 // Assume that extern "C" functions with variadic arguments that
5902 // return __unknown_anytype aren't *really* variadic.
5903 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5904 FDecl->isExternC()) {
5905 for (Expr *A : Args.slice(ArgIx)) {
5906 QualType paramType; // ignored
5907 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5908 Invalid |= arg.isInvalid();
5909 AllArgs.push_back(arg.get());
5910 }
5911
5912 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5913 } else {
5914 for (Expr *A : Args.slice(ArgIx)) {
5915 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5916 Invalid |= Arg.isInvalid();
5917 AllArgs.push_back(Arg.get());
5918 }
5919 }
5920
5921 // Check for array bounds violations.
5922 for (Expr *A : Args.slice(ArgIx))
5923 CheckArrayAccess(A);
5924 }
5925 return Invalid;
5926}
5927
5928static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5929 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5930 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5931 TL = DTL.getOriginalLoc();
5932 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5933 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5934 << ATL.getLocalSourceRange();
5935}
5936
5937/// CheckStaticArrayArgument - If the given argument corresponds to a static
5938/// array parameter, check that it is non-null, and that if it is formed by
5939/// array-to-pointer decay, the underlying array is sufficiently large.
5940///
5941/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5942/// array type derivation, then for each call to the function, the value of the
5943/// corresponding actual argument shall provide access to the first element of
5944/// an array with at least as many elements as specified by the size expression.
5945void
5946Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5947 ParmVarDecl *Param,
5948 const Expr *ArgExpr) {
5949 // Static array parameters are not supported in C++.
5950 if (!Param || getLangOpts().CPlusPlus)
5951 return;
5952
5953 QualType OrigTy = Param->getOriginalType();
5954
5955 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5956 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5957 return;
5958
5959 if (ArgExpr->isNullPointerConstant(Context,
5960 Expr::NPC_NeverValueDependent)) {
5961 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5962 DiagnoseCalleeStaticArrayParam(*this, Param);
5963 return;
5964 }
5965
5966 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5967 if (!CAT)
5968 return;
5969
5970 const ConstantArrayType *ArgCAT =
5971 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5972 if (!ArgCAT)
5973 return;
5974
5975 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5976 ArgCAT->getElementType())) {
5977 if (ArgCAT->getSize().ult(CAT->getSize())) {
5978 Diag(CallLoc, diag::warn_static_array_too_small)
5979 << ArgExpr->getSourceRange()
5980 << (unsigned)ArgCAT->getSize().getZExtValue()
5981 << (unsigned)CAT->getSize().getZExtValue() << 0;
5982 DiagnoseCalleeStaticArrayParam(*this, Param);
5983 }
5984 return;
5985 }
5986
5987 Optional<CharUnits> ArgSize =
5988 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5989 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5990 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5991 Diag(CallLoc, diag::warn_static_array_too_small)
5992 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5993 << (unsigned)ParmSize->getQuantity() << 1;
5994 DiagnoseCalleeStaticArrayParam(*this, Param);
5995 }
5996}
5997
5998/// Given a function expression of unknown-any type, try to rebuild it
5999/// to have a function type.
6000static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6001
6002/// Is the given type a placeholder that we need to lower out
6003/// immediately during argument processing?
6004static bool isPlaceholderToRemoveAsArg(QualType type) {
6005 // Placeholders are never sugared.
6006 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6007 if (!placeholder) return false;
6008
6009 switch (placeholder->getKind()) {
6010 // Ignore all the non-placeholder types.
6011#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6012 case BuiltinType::Id:
6013#include "clang/Basic/OpenCLImageTypes.def"
6014#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6015 case BuiltinType::Id:
6016#include "clang/Basic/OpenCLExtensionTypes.def"
6017 // In practice we'll never use this, since all SVE types are sugared
6018 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6019#define SVE_TYPE(Name, Id, SingletonId) \
6020 case BuiltinType::Id:
6021#include "clang/Basic/AArch64SVEACLETypes.def"
6022#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6023#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6024#include "clang/AST/BuiltinTypes.def"
6025 return false;
6026
6027 // We cannot lower out overload sets; they might validly be resolved
6028 // by the call machinery.
6029 case BuiltinType::Overload:
6030 return false;
6031
6032 // Unbridged casts in ARC can be handled in some call positions and
6033 // should be left in place.
6034 case BuiltinType::ARCUnbridgedCast:
6035 return false;
6036
6037 // Pseudo-objects should be converted as soon as possible.
6038 case BuiltinType::PseudoObject:
6039 return true;
6040
6041 // The debugger mode could theoretically but currently does not try
6042 // to resolve unknown-typed arguments based on known parameter types.
6043 case BuiltinType::UnknownAny:
6044 return true;
6045
6046 // These are always invalid as call arguments and should be reported.
6047 case BuiltinType::BoundMember:
6048 case BuiltinType::BuiltinFn:
6049 case BuiltinType::IncompleteMatrixIdx:
6050 case BuiltinType::OMPArraySection:
6051 case BuiltinType::OMPArrayShaping:
6052 case BuiltinType::OMPIterator:
6053 return true;
6054
6055 }
6056 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6056)
;
6057}
6058
6059/// Check an argument list for placeholders that we won't try to
6060/// handle later.
6061static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6062 // Apply this processing to all the arguments at once instead of
6063 // dying at the first failure.
6064 bool hasInvalid = false;
6065 for (size_t i = 0, e = args.size(); i != e; i++) {
6066 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6067 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6068 if (result.isInvalid()) hasInvalid = true;
6069 else args[i] = result.get();
6070 } else if (hasInvalid) {
6071 (void)S.CorrectDelayedTyposInExpr(args[i]);
6072 }
6073 }
6074 return hasInvalid;
6075}
6076
6077/// If a builtin function has a pointer argument with no explicit address
6078/// space, then it should be able to accept a pointer to any address
6079/// space as input. In order to do this, we need to replace the
6080/// standard builtin declaration with one that uses the same address space
6081/// as the call.
6082///
6083/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6084/// it does not contain any pointer arguments without
6085/// an address space qualifer. Otherwise the rewritten
6086/// FunctionDecl is returned.
6087/// TODO: Handle pointer return types.
6088static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6089 FunctionDecl *FDecl,
6090 MultiExprArg ArgExprs) {
6091
6092 QualType DeclType = FDecl->getType();
6093 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6094
6095 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6096 ArgExprs.size() < FT->getNumParams())
6097 return nullptr;
6098
6099 bool NeedsNewDecl = false;
6100 unsigned i = 0;
6101 SmallVector<QualType, 8> OverloadParams;
6102
6103 for (QualType ParamType : FT->param_types()) {
6104
6105 // Convert array arguments to pointer to simplify type lookup.
6106 ExprResult ArgRes =
6107 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6108 if (ArgRes.isInvalid())
6109 return nullptr;
6110 Expr *Arg = ArgRes.get();
6111 QualType ArgType = Arg->getType();
6112 if (!ParamType->isPointerType() ||
6113 ParamType.hasAddressSpace() ||
6114 !ArgType->isPointerType() ||
6115 !ArgType->getPointeeType().hasAddressSpace()) {
6116 OverloadParams.push_back(ParamType);
6117 continue;
6118 }
6119
6120 QualType PointeeType = ParamType->getPointeeType();
6121 if (PointeeType.hasAddressSpace())
6122 continue;
6123
6124 NeedsNewDecl = true;
6125 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6126
6127 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6128 OverloadParams.push_back(Context.getPointerType(PointeeType));
6129 }
6130
6131 if (!NeedsNewDecl)
6132 return nullptr;
6133
6134 FunctionProtoType::ExtProtoInfo EPI;
6135 EPI.Variadic = FT->isVariadic();
6136 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6137 OverloadParams, EPI);
6138 DeclContext *Parent = FDecl->getParent();
6139 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6140 FDecl->getLocation(),
6141 FDecl->getLocation(),
6142 FDecl->getIdentifier(),
6143 OverloadTy,
6144 /*TInfo=*/nullptr,
6145 SC_Extern, false,
6146 /*hasPrototype=*/true);
6147 SmallVector<ParmVarDecl*, 16> Params;
6148 FT = cast<FunctionProtoType>(OverloadTy);
6149 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6150 QualType ParamType = FT->getParamType(i);
6151 ParmVarDecl *Parm =
6152 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6153 SourceLocation(), nullptr, ParamType,
6154 /*TInfo=*/nullptr, SC_None, nullptr);
6155 Parm->setScopeInfo(0, i);
6156 Params.push_back(Parm);
6157 }
6158 OverloadDecl->setParams(Params);
6159 return OverloadDecl;
6160}
6161
6162static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6163 FunctionDecl *Callee,
6164 MultiExprArg ArgExprs) {
6165 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6166 // similar attributes) really don't like it when functions are called with an
6167 // invalid number of args.
6168 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6169 /*PartialOverloading=*/false) &&
6170 !Callee->isVariadic())
6171 return;
6172 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6173 return;
6174
6175 if (const EnableIfAttr *Attr =
6176 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6177 S.Diag(Fn->getBeginLoc(),
6178 isa<CXXMethodDecl>(Callee)
6179 ? diag::err_ovl_no_viable_member_function_in_call
6180 : diag::err_ovl_no_viable_function_in_call)
6181 << Callee << Callee->getSourceRange();
6182 S.Diag(Callee->getLocation(),
6183 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6184 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6185 return;
6186 }
6187}
6188
6189static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6190 const UnresolvedMemberExpr *const UME, Sema &S) {
6191
6192 const auto GetFunctionLevelDCIfCXXClass =
6193 [](Sema &S) -> const CXXRecordDecl * {
6194 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6195 if (!DC || !DC->getParent())
6196 return nullptr;
6197
6198 // If the call to some member function was made from within a member
6199 // function body 'M' return return 'M's parent.
6200 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6201 return MD->getParent()->getCanonicalDecl();
6202 // else the call was made from within a default member initializer of a
6203 // class, so return the class.
6204 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6205 return RD->getCanonicalDecl();
6206 return nullptr;
6207 };
6208 // If our DeclContext is neither a member function nor a class (in the
6209 // case of a lambda in a default member initializer), we can't have an
6210 // enclosing 'this'.
6211
6212 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6213 if (!CurParentClass)
6214 return false;
6215
6216 // The naming class for implicit member functions call is the class in which
6217 // name lookup starts.
6218 const CXXRecordDecl *const NamingClass =
6219 UME->getNamingClass()->getCanonicalDecl();
6220 assert(NamingClass && "Must have naming class even for implicit access")((NamingClass && "Must have naming class even for implicit access"
) ? static_cast<void> (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6220, __PRETTY_FUNCTION__))
;
6221
6222 // If the unresolved member functions were found in a 'naming class' that is
6223 // related (either the same or derived from) to the class that contains the
6224 // member function that itself contained the implicit member access.
6225
6226 return CurParentClass == NamingClass ||
6227 CurParentClass->isDerivedFrom(NamingClass);
6228}
6229
6230static void
6231tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6232 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6233
6234 if (!UME)
6235 return;
6236
6237 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6238 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6239 // already been captured, or if this is an implicit member function call (if
6240 // it isn't, an attempt to capture 'this' should already have been made).
6241 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6242 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6243 return;
6244
6245 // Check if the naming class in which the unresolved members were found is
6246 // related (same as or is a base of) to the enclosing class.
6247
6248 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6249 return;
6250
6251
6252 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6253 // If the enclosing function is not dependent, then this lambda is
6254 // capture ready, so if we can capture this, do so.
6255 if (!EnclosingFunctionCtx->isDependentContext()) {
6256 // If the current lambda and all enclosing lambdas can capture 'this' -
6257 // then go ahead and capture 'this' (since our unresolved overload set
6258 // contains at least one non-static member function).
6259 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6260 S.CheckCXXThisCapture(CallLoc);
6261 } else if (S.CurContext->isDependentContext()) {
6262 // ... since this is an implicit member reference, that might potentially
6263 // involve a 'this' capture, mark 'this' for potential capture in
6264 // enclosing lambdas.
6265 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6266 CurLSI->addPotentialThisCapture(CallLoc);
6267 }
6268}
6269
6270ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6271 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6272 Expr *ExecConfig) {
6273 ExprResult Call =
6274 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6275 if (Call.isInvalid())
6276 return Call;
6277
6278 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6279 // language modes.
6280 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6281 if (ULE->hasExplicitTemplateArgs() &&
6282 ULE->decls_begin() == ULE->decls_end()) {
6283 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6284 ? diag::warn_cxx17_compat_adl_only_template_id
6285 : diag::ext_adl_only_template_id)
6286 << ULE->getName();
6287 }
6288 }
6289
6290 if (LangOpts.OpenMP)
6291 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6292 ExecConfig);
6293
6294 return Call;
6295}
6296
6297/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6298/// This provides the location of the left/right parens and a list of comma
6299/// locations.
6300ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6301 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6302 Expr *ExecConfig, bool IsExecConfig) {
6303 // Since this might be a postfix expression, get rid of ParenListExprs.
6304 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6305 if (Result.isInvalid()) return ExprError();
6306 Fn = Result.get();
6307
6308 if (checkArgsForPlaceholders(*this, ArgExprs))
6309 return ExprError();
6310
6311 if (getLangOpts().CPlusPlus) {
6312 // If this is a pseudo-destructor expression, build the call immediately.
6313 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6314 if (!ArgExprs.empty()) {
6315 // Pseudo-destructor calls should not have any arguments.
6316 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6317 << FixItHint::CreateRemoval(
6318 SourceRange(ArgExprs.front()->getBeginLoc(),
6319 ArgExprs.back()->getEndLoc()));
6320 }
6321
6322 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6323 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6324 }
6325 if (Fn->getType() == Context.PseudoObjectTy) {
6326 ExprResult result = CheckPlaceholderExpr(Fn);
6327 if (result.isInvalid()) return ExprError();
6328 Fn = result.get();
6329 }
6330
6331 // Determine whether this is a dependent call inside a C++ template,
6332 // in which case we won't do any semantic analysis now.
6333 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6334 if (ExecConfig) {
6335 return CUDAKernelCallExpr::Create(
6336 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6337 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6338 } else {
6339
6340 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6341 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6342 Fn->getBeginLoc());
6343
6344 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6345 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6346 }
6347 }
6348
6349 // Determine whether this is a call to an object (C++ [over.call.object]).
6350 if (Fn->getType()->isRecordType())
6351 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6352 RParenLoc);
6353
6354 if (Fn->getType() == Context.UnknownAnyTy) {
6355 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6356 if (result.isInvalid()) return ExprError();
6357 Fn = result.get();
6358 }
6359
6360 if (Fn->getType() == Context.BoundMemberTy) {
6361 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6362 RParenLoc);
6363 }
6364 }
6365
6366 // Check for overloaded calls. This can happen even in C due to extensions.
6367 if (Fn->getType() == Context.OverloadTy) {
6368 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6369
6370 // We aren't supposed to apply this logic if there's an '&' involved.
6371 if (!find.HasFormOfMemberPointer) {
6372 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6373 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6374 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6375 OverloadExpr *ovl = find.Expression;
6376 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6377 return BuildOverloadedCallExpr(
6378 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6379 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6380 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6381 RParenLoc);
6382 }
6383 }
6384
6385 // If we're directly calling a function, get the appropriate declaration.
6386 if (Fn->getType() == Context.UnknownAnyTy) {
6387 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6388 if (result.isInvalid()) return ExprError();
6389 Fn = result.get();
6390 }
6391
6392 Expr *NakedFn = Fn->IgnoreParens();
6393
6394 bool CallingNDeclIndirectly = false;
6395 NamedDecl *NDecl = nullptr;
6396 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6397 if (UnOp->getOpcode() == UO_AddrOf) {
6398 CallingNDeclIndirectly = true;
6399 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6400 }
6401 }
6402
6403 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6404 NDecl = DRE->getDecl();
6405
6406 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6407 if (FDecl && FDecl->getBuiltinID()) {
6408 // Rewrite the function decl for this builtin by replacing parameters
6409 // with no explicit address space with the address space of the arguments
6410 // in ArgExprs.
6411 if ((FDecl =
6412 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6413 NDecl = FDecl;
6414 Fn = DeclRefExpr::Create(
6415 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6416 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6417 nullptr, DRE->isNonOdrUse());
6418 }
6419 }
6420 } else if (isa<MemberExpr>(NakedFn))
6421 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6422
6423 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6424 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6425 FD, /*Complain=*/true, Fn->getBeginLoc()))
6426 return ExprError();
6427
6428 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6429 return ExprError();
6430
6431 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6432 }
6433
6434 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6435 ExecConfig, IsExecConfig);
6436}
6437
6438/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6439///
6440/// __builtin_astype( value, dst type )
6441///
6442ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6443 SourceLocation BuiltinLoc,
6444 SourceLocation RParenLoc) {
6445 ExprValueKind VK = VK_RValue;
6446 ExprObjectKind OK = OK_Ordinary;
6447 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6448 QualType SrcTy = E->getType();
6449 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6450 return ExprError(Diag(BuiltinLoc,
6451 diag::err_invalid_astype_of_different_size)
6452 << DstTy
6453 << SrcTy
6454 << E->getSourceRange());
6455 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6456}
6457
6458/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6459/// provided arguments.
6460///
6461/// __builtin_convertvector( value, dst type )
6462///
6463ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6464 SourceLocation BuiltinLoc,
6465 SourceLocation RParenLoc) {
6466 TypeSourceInfo *TInfo;
6467 GetTypeFromParser(ParsedDestTy, &TInfo);
6468 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6469}
6470
6471/// BuildResolvedCallExpr - Build a call to a resolved expression,
6472/// i.e. an expression not of \p OverloadTy. The expression should
6473/// unary-convert to an expression of function-pointer or
6474/// block-pointer type.
6475///
6476/// \param NDecl the declaration being called, if available
6477ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6478 SourceLocation LParenLoc,
6479 ArrayRef<Expr *> Args,
6480 SourceLocation RParenLoc, Expr *Config,
6481 bool IsExecConfig, ADLCallKind UsesADL) {
6482 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6483 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6484
6485 // Functions with 'interrupt' attribute cannot be called directly.
6486 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6487 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6488 return ExprError();
6489 }
6490
6491 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6492 // so there's some risk when calling out to non-interrupt handler functions
6493 // that the callee might not preserve them. This is easy to diagnose here,
6494 // but can be very challenging to debug.
6495 if (auto *Caller = getCurFunctionDecl())
6496 if (Caller->hasAttr<ARMInterruptAttr>()) {
6497 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6498 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6499 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6500 }
6501
6502 // Promote the function operand.
6503 // We special-case function promotion here because we only allow promoting
6504 // builtin functions to function pointers in the callee of a call.
6505 ExprResult Result;
6506 QualType ResultTy;
6507 if (BuiltinID &&
6508 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6509 // Extract the return type from the (builtin) function pointer type.
6510 // FIXME Several builtins still have setType in
6511 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6512 // Builtins.def to ensure they are correct before removing setType calls.
6513 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6514 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6515 ResultTy = FDecl->getCallResultType();
6516 } else {
6517 Result = CallExprUnaryConversions(Fn);
6518 ResultTy = Context.BoolTy;
6519 }
6520 if (Result.isInvalid())
6521 return ExprError();
6522 Fn = Result.get();
6523
6524 // Check for a valid function type, but only if it is not a builtin which
6525 // requires custom type checking. These will be handled by
6526 // CheckBuiltinFunctionCall below just after creation of the call expression.
6527 const FunctionType *FuncT = nullptr;
6528 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6529 retry:
6530 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6531 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6532 // have type pointer to function".
6533 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6534 if (!FuncT)
6535 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6536 << Fn->getType() << Fn->getSourceRange());
6537 } else if (const BlockPointerType *BPT =
6538 Fn->getType()->getAs<BlockPointerType>()) {
6539 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6540 } else {
6541 // Handle calls to expressions of unknown-any type.
6542 if (Fn->getType() == Context.UnknownAnyTy) {
6543 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6544 if (rewrite.isInvalid())
6545 return ExprError();
6546 Fn = rewrite.get();
6547 goto retry;
6548 }
6549
6550 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6551 << Fn->getType() << Fn->getSourceRange());
6552 }
6553 }
6554
6555 // Get the number of parameters in the function prototype, if any.
6556 // We will allocate space for max(Args.size(), NumParams) arguments
6557 // in the call expression.
6558 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6559 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6560
6561 CallExpr *TheCall;
6562 if (Config) {
6563 assert(UsesADL == ADLCallKind::NotADL &&((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL"
) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6564, __PRETTY_FUNCTION__))
6564 "CUDAKernelCallExpr should not use ADL")((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL"
) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6564, __PRETTY_FUNCTION__))
;
6565 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6566 Args, ResultTy, VK_RValue, RParenLoc,
6567 CurFPFeatureOverrides(), NumParams);
6568 } else {
6569 TheCall =
6570 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6571 CurFPFeatureOverrides(), NumParams, UsesADL);
6572 }
6573
6574 if (!getLangOpts().CPlusPlus) {
6575 // Forget about the nulled arguments since typo correction
6576 // do not handle them well.
6577 TheCall->shrinkNumArgs(Args.size());
6578 // C cannot always handle TypoExpr nodes in builtin calls and direct
6579 // function calls as their argument checking don't necessarily handle
6580 // dependent types properly, so make sure any TypoExprs have been
6581 // dealt with.
6582 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6583 if (!Result.isUsable()) return ExprError();
6584 CallExpr *TheOldCall = TheCall;
6585 TheCall = dyn_cast<CallExpr>(Result.get());
6586 bool CorrectedTypos = TheCall != TheOldCall;
6587 if (!TheCall) return Result;
6588 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6589
6590 // A new call expression node was created if some typos were corrected.
6591 // However it may not have been constructed with enough storage. In this
6592 // case, rebuild the node with enough storage. The waste of space is
6593 // immaterial since this only happens when some typos were corrected.
6594 if (CorrectedTypos && Args.size() < NumParams) {
6595 if (Config)
6596 TheCall = CUDAKernelCallExpr::Create(
6597 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6598 RParenLoc, CurFPFeatureOverrides(), NumParams);
6599 else
6600 TheCall =
6601 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6602 CurFPFeatureOverrides(), NumParams, UsesADL);
6603 }
6604 // We can now handle the nulled arguments for the default arguments.
6605 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6606 }
6607
6608 // Bail out early if calling a builtin with custom type checking.
6609 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6610 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6611
6612 if (getLangOpts().CUDA) {
6613 if (Config) {
6614 // CUDA: Kernel calls must be to global functions
6615 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6616 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6617 << FDecl << Fn->getSourceRange());
6618
6619 // CUDA: Kernel function must have 'void' return type
6620 if (!FuncT->getReturnType()->isVoidType() &&
6621 !FuncT->getReturnType()->getAs<AutoType>() &&
6622 !FuncT->getReturnType()->isInstantiationDependentType())
6623 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6624 << Fn->getType() << Fn->getSourceRange());
6625 } else {
6626 // CUDA: Calls to global functions must be configured
6627 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6628 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6629 << FDecl << Fn->getSourceRange());
6630 }
6631 }
6632
6633 // Check for a valid return type
6634 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6635 FDecl))
6636 return ExprError();
6637
6638 // We know the result type of the call, set it.
6639 TheCall->setType(FuncT->getCallResultType(Context));
6640 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6641
6642 if (Proto) {
6643 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6644 IsExecConfig))
6645 return ExprError();
6646 } else {
6647 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")((isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6647, __PRETTY_FUNCTION__))
;
6648
6649 if (FDecl) {
6650 // Check if we have too few/too many template arguments, based
6651 // on our knowledge of the function definition.
6652 const FunctionDecl *Def = nullptr;
6653 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6654 Proto = Def->getType()->getAs<FunctionProtoType>();
6655 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6656 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6657 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6658 }
6659
6660 // If the function we're calling isn't a function prototype, but we have
6661 // a function prototype from a prior declaratiom, use that prototype.
6662 if (!FDecl->hasPrototype())
6663 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6664 }
6665
6666 // Promote the arguments (C99 6.5.2.2p6).
6667 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6668 Expr *Arg = Args[i];
6669
6670 if (Proto && i < Proto->getNumParams()) {
6671 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6672 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6673 ExprResult ArgE =
6674 PerformCopyInitialization(Entity, SourceLocation(), Arg);
6675 if (ArgE.isInvalid())
6676 return true;
6677
6678 Arg = ArgE.getAs<Expr>();
6679
6680 } else {
6681 ExprResult ArgE = DefaultArgumentPromotion(Arg);
6682
6683 if (ArgE.isInvalid())
6684 return true;
6685
6686 Arg = ArgE.getAs<Expr>();
6687 }
6688
6689 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6690 diag::err_call_incomplete_argument, Arg))
6691 return ExprError();
6692
6693 TheCall->setArg(i, Arg);
6694 }
6695 }
6696
6697 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6698 if (!Method->isStatic())
6699 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6700 << Fn->getSourceRange());
6701
6702 // Check for sentinels
6703 if (NDecl)
6704 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6705
6706 // Warn for unions passing across security boundary (CMSE).
6707 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6708 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6709 if (const auto *RT =
6710 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6711 if (RT->getDecl()->isOrContainsUnion())
6712 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6713 << 0 << i;
6714 }
6715 }
6716 }
6717
6718 // Do special checking on direct calls to functions.
6719 if (FDecl) {
6720 if (CheckFunctionCall(FDecl, TheCall, Proto))
6721 return ExprError();
6722
6723 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6724
6725 if (BuiltinID)
6726 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6727 } else if (NDecl) {
6728 if (CheckPointerCall(NDecl, TheCall, Proto))
6729 return ExprError();
6730 } else {
6731 if (CheckOtherCall(TheCall, Proto))
6732 return ExprError();
6733 }
6734
6735 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6736}
6737
6738ExprResult
6739Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6740 SourceLocation RParenLoc, Expr *InitExpr) {
6741 assert(Ty && "ActOnCompoundLiteral(): missing type")((Ty && "ActOnCompoundLiteral(): missing type") ? static_cast
<void> (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6741, __PRETTY_FUNCTION__))
;
6742 assert(InitExpr && "ActOnCompoundLiteral(): missing expression")((InitExpr && "ActOnCompoundLiteral(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6742, __PRETTY_FUNCTION__))
;
6743
6744 TypeSourceInfo *TInfo;
6745 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6746 if (!TInfo)
6747 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6748
6749 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6750}
6751
6752ExprResult
6753Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6754 SourceLocation RParenLoc, Expr *LiteralExpr) {
6755 QualType literalType = TInfo->getType();
6756
6757 if (literalType->isArrayType()) {
6758 if (RequireCompleteSizedType(
6759 LParenLoc, Context.getBaseElementType(literalType),
6760 diag::err_array_incomplete_or_sizeless_type,
6761 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6762 return ExprError();
6763 if (literalType->isVariableArrayType())
6764 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6765 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6766 } else if (!literalType->isDependentType() &&
6767 RequireCompleteType(LParenLoc, literalType,
6768 diag::err_typecheck_decl_incomplete_type,
6769 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6770 return ExprError();
6771
6772 InitializedEntity Entity
6773 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6774 InitializationKind Kind
6775 = InitializationKind::CreateCStyleCast(LParenLoc,
6776 SourceRange(LParenLoc, RParenLoc),
6777 /*InitList=*/true);
6778 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6779 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6780 &literalType);
6781 if (Result.isInvalid())
6782 return ExprError();
6783 LiteralExpr = Result.get();
6784
6785 bool isFileScope = !CurContext->isFunctionOrMethod();
6786
6787 // In C, compound literals are l-values for some reason.
6788 // For GCC compatibility, in C++, file-scope array compound literals with
6789 // constant initializers are also l-values, and compound literals are
6790 // otherwise prvalues.
6791 //
6792 // (GCC also treats C++ list-initialized file-scope array prvalues with
6793 // constant initializers as l-values, but that's non-conforming, so we don't
6794 // follow it there.)
6795 //
6796 // FIXME: It would be better to handle the lvalue cases as materializing and
6797 // lifetime-extending a temporary object, but our materialized temporaries
6798 // representation only supports lifetime extension from a variable, not "out
6799 // of thin air".
6800 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6801 // is bound to the result of applying array-to-pointer decay to the compound
6802 // literal.
6803 // FIXME: GCC supports compound literals of reference type, which should
6804 // obviously have a value kind derived from the kind of reference involved.
6805 ExprValueKind VK =
6806 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6807 ? VK_RValue
6808 : VK_LValue;
6809
6810 if (isFileScope)
6811 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6812 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6813 Expr *Init = ILE->getInit(i);
6814 ILE->setInit(i, ConstantExpr::Create(Context, Init));
6815 }
6816
6817 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6818 VK, LiteralExpr, isFileScope);
6819 if (isFileScope) {
6820 if (!LiteralExpr->isTypeDependent() &&
6821 !LiteralExpr->isValueDependent() &&
6822 !literalType->isDependentType()) // C99 6.5.2.5p3
6823 if (CheckForConstantInitializer(LiteralExpr, literalType))
6824 return ExprError();
6825 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6826 literalType.getAddressSpace() != LangAS::Default) {
6827 // Embedded-C extensions to C99 6.5.2.5:
6828 // "If the compound literal occurs inside the body of a function, the
6829 // type name shall not be qualified by an address-space qualifier."
6830 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6831 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6832 return ExprError();
6833 }
6834
6835 if (!isFileScope && !getLangOpts().CPlusPlus) {
6836 // Compound literals that have automatic storage duration are destroyed at
6837 // the end of the scope in C; in C++, they're just temporaries.
6838
6839 // Emit diagnostics if it is or contains a C union type that is non-trivial
6840 // to destruct.
6841 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6842 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6843 NTCUC_CompoundLiteral, NTCUK_Destruct);
6844
6845 // Diagnose jumps that enter or exit the lifetime of the compound literal.
6846 if (literalType.isDestructedType()) {
6847 Cleanup.setExprNeedsCleanups(true);
6848 ExprCleanupObjects.push_back(E);
6849 getCurFunction()->setHasBranchProtectedScope();
6850 }
6851 }
6852
6853 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6854 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6855 checkNonTrivialCUnionInInitializer(E->getInitializer(),
6856 E->getInitializer()->getExprLoc());
6857
6858 return MaybeBindToTemporary(E);
6859}
6860
6861ExprResult
6862Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6863 SourceLocation RBraceLoc) {
6864 // Only produce each kind of designated initialization diagnostic once.
6865 SourceLocation FirstDesignator;
6866 bool DiagnosedArrayDesignator = false;
6867 bool DiagnosedNestedDesignator = false;
6868 bool DiagnosedMixedDesignator = false;
6869
6870 // Check that any designated initializers are syntactically valid in the
6871 // current language mode.
6872 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6873 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6874 if (FirstDesignator.isInvalid())
6875 FirstDesignator = DIE->getBeginLoc();
6876
6877 if (!getLangOpts().CPlusPlus)
6878 break;
6879
6880 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6881 DiagnosedNestedDesignator = true;
6882 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6883 << DIE->getDesignatorsSourceRange();
6884 }
6885
6886 for (auto &Desig : DIE->designators()) {
6887 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6888 DiagnosedArrayDesignator = true;
6889 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6890 << Desig.getSourceRange();
6891 }
6892 }
6893
6894 if (!DiagnosedMixedDesignator &&
6895 !isa<DesignatedInitExpr>(InitArgList[0])) {
6896 DiagnosedMixedDesignator = true;
6897 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6898 << DIE->getSourceRange();
6899 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6900 << InitArgList[0]->getSourceRange();
6901 }
6902 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6903 isa<DesignatedInitExpr>(InitArgList[0])) {
6904 DiagnosedMixedDesignator = true;
6905 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6906 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6907 << DIE->getSourceRange();
6908 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6909 << InitArgList[I]->getSourceRange();
6910 }
6911 }
6912
6913 if (FirstDesignator.isValid()) {
6914 // Only diagnose designated initiaization as a C++20 extension if we didn't
6915 // already diagnose use of (non-C++20) C99 designator syntax.
6916 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6917 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6918 Diag(FirstDesignator, getLangOpts().CPlusPlus20
6919 ? diag::warn_cxx17_compat_designated_init
6920 : diag::ext_cxx_designated_init);
6921 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6922 Diag(FirstDesignator, diag::ext_designated_init);
6923 }
6924 }
6925
6926 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6927}
6928
6929ExprResult
6930Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6931 SourceLocation RBraceLoc) {
6932 // Semantic analysis for initializers is done by ActOnDeclarator() and
6933 // CheckInitializer() - it requires knowledge of the object being initialized.
6934
6935 // Immediately handle non-overload placeholders. Overloads can be
6936 // resolved contextually, but everything else here can't.
6937 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6938 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6939 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6940
6941 // Ignore failures; dropping the entire initializer list because
6942 // of one failure would be terrible for indexing/etc.
6943 if (result.isInvalid()) continue;
6944
6945 InitArgList[I] = result.get();
6946 }
6947 }
6948
6949 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6950 RBraceLoc);
6951 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6952 return E;
6953}
6954
6955/// Do an explicit extend of the given block pointer if we're in ARC.
6956void Sema::maybeExtendBlockObject(ExprResult &E) {
6957 assert(E.get()->getType()->isBlockPointerType())((E.get()->getType()->isBlockPointerType()) ? static_cast
<void> (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6957, __PRETTY_FUNCTION__))
;
6958 assert(E.get()->isRValue())((E.get()->isRValue()) ? static_cast<void> (0) : __assert_fail
("E.get()->isRValue()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6958, __PRETTY_FUNCTION__))
;
6959
6960 // Only do this in an r-value context.
6961 if (!getLangOpts().ObjCAutoRefCount) return;
6962
6963 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6964 CK_ARCExtendBlockObject, E.get(),
6965 /*base path*/ nullptr, VK_RValue);
6966 Cleanup.setExprNeedsCleanups(true);
6967}
6968
6969/// Prepare a conversion of the given expression to an ObjC object
6970/// pointer type.
6971CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6972 QualType type = E.get()->getType();
6973 if (type->isObjCObjectPointerType()) {
6974 return CK_BitCast;
6975 } else if (type->isBlockPointerType()) {
6976 maybeExtendBlockObject(E);
6977 return CK_BlockPointerToObjCPointerCast;
6978 } else {
6979 assert(type->isPointerType())((type->isPointerType()) ? static_cast<void> (0) : __assert_fail
("type->isPointerType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6979, __PRETTY_FUNCTION__))
;
6980 return CK_CPointerToObjCPointerCast;
6981 }
6982}
6983
6984/// Prepares for a scalar cast, performing all the necessary stages
6985/// except the final cast and returning the kind required.
6986CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6987 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6988 // Also, callers should have filtered out the invalid cases with
6989 // pointers. Everything else should be possible.
6990
6991 QualType SrcTy = Src.get()->getType();
6992 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6993 return CK_NoOp;
6994
6995 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6996 case Type::STK_MemberPointer:
6997 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 6997)
;
6998
6999 case Type::STK_CPointer:
7000 case Type::STK_BlockPointer:
7001 case Type::STK_ObjCObjectPointer:
7002 switch (DestTy->getScalarTypeKind()) {
7003 case Type::STK_CPointer: {
7004 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7005 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7006 if (SrcAS != DestAS)
7007 return CK_AddressSpaceConversion;
7008 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7009 return CK_NoOp;
7010 return CK_BitCast;
7011 }
7012 case Type::STK_BlockPointer:
7013 return (SrcKind == Type::STK_BlockPointer
7014 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7015 case Type::STK_ObjCObjectPointer:
7016 if (SrcKind == Type::STK_ObjCObjectPointer)
7017 return CK_BitCast;
7018 if (SrcKind == Type::STK_CPointer)
7019 return CK_CPointerToObjCPointerCast;
7020 maybeExtendBlockObject(Src);
7021 return CK_BlockPointerToObjCPointerCast;
7022 case Type::STK_Bool:
7023 return CK_PointerToBoolean;
7024 case Type::STK_Integral:
7025 return CK_PointerToIntegral;
7026 case Type::STK_Floating:
7027 case Type::STK_FloatingComplex:
7028 case Type::STK_IntegralComplex:
7029 case Type::STK_MemberPointer:
7030 case Type::STK_FixedPoint:
7031 llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7031)
;
7032 }
7033 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7033)
;
7034
7035 case Type::STK_FixedPoint:
7036 switch (DestTy->getScalarTypeKind()) {
7037 case Type::STK_FixedPoint:
7038 return CK_FixedPointCast;
7039 case Type::STK_Bool:
7040 return CK_FixedPointToBoolean;
7041 case Type::STK_Integral:
7042 return CK_FixedPointToIntegral;
7043 case Type::STK_Floating:
7044 case Type::STK_IntegralComplex:
7045 case Type::STK_FloatingComplex:
7046 Diag(Src.get()->getExprLoc(),
7047 diag::err_unimplemented_conversion_with_fixed_point_type)
7048 << DestTy;
7049 return CK_IntegralCast;
7050 case Type::STK_CPointer:
7051 case Type::STK_ObjCObjectPointer:
7052 case Type::STK_BlockPointer:
7053 case Type::STK_MemberPointer:
7054 llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7054)
;
7055 }
7056 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7056)
;
7057
7058 case Type::STK_Bool: // casting from bool is like casting from an integer
7059 case Type::STK_Integral:
7060 switch (DestTy->getScalarTypeKind()) {
7061 case Type::STK_CPointer:
7062 case Type::STK_ObjCObjectPointer:
7063 case Type::STK_BlockPointer:
7064 if (Src.get()->isNullPointerConstant(Context,
7065 Expr::NPC_ValueDependentIsNull))
7066 return CK_NullToPointer;
7067 return CK_IntegralToPointer;
7068 case Type::STK_Bool:
7069 return CK_IntegralToBoolean;
7070 case Type::STK_Integral:
7071 return CK_IntegralCast;
7072 case Type::STK_Floating:
7073 return CK_IntegralToFloating;
7074 case Type::STK_IntegralComplex:
7075 Src = ImpCastExprToType(Src.get(),
7076 DestTy->castAs<ComplexType>()->getElementType(),
7077 CK_IntegralCast);
7078 return CK_IntegralRealToComplex;
7079 case Type::STK_FloatingComplex:
7080 Src = ImpCastExprToType(Src.get(),
7081 DestTy->castAs<ComplexType>()->getElementType(),
7082 CK_IntegralToFloating);
7083 return CK_FloatingRealToComplex;
7084 case Type::STK_MemberPointer:
7085 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7085)
;
7086 case Type::STK_FixedPoint:
7087 return CK_IntegralToFixedPoint;
7088 }
7089 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7089)
;
7090
7091 case Type::STK_Floating:
7092 switch (DestTy->getScalarTypeKind()) {
7093 case Type::STK_Floating:
7094 return CK_FloatingCast;
7095 case Type::STK_Bool:
7096 return CK_FloatingToBoolean;
7097 case Type::STK_Integral:
7098 return CK_FloatingToIntegral;
7099 case Type::STK_FloatingComplex:
7100 Src = ImpCastExprToType(Src.get(),
7101 DestTy->castAs<ComplexType>()->getElementType(),
7102 CK_FloatingCast);
7103 return CK_FloatingRealToComplex;
7104 case Type::STK_IntegralComplex:
7105 Src = ImpCastExprToType(Src.get(),
7106 DestTy->castAs<ComplexType>()->getElementType(),
7107 CK_FloatingToIntegral);
7108 return CK_IntegralRealToComplex;
7109 case Type::STK_CPointer:
7110 case Type::STK_ObjCObjectPointer:
7111 case Type::STK_BlockPointer:
7112 llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7112)
;
7113 case Type::STK_MemberPointer:
7114 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7114)
;
7115 case Type::STK_FixedPoint:
7116 Diag(Src.get()->getExprLoc(),
7117 diag::err_unimplemented_conversion_with_fixed_point_type)
7118 << SrcTy;
7119 return CK_IntegralCast;
7120 }
7121 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7121)
;
7122
7123 case Type::STK_FloatingComplex:
7124 switch (DestTy->getScalarTypeKind()) {
7125 case Type::STK_FloatingComplex:
7126 return CK_FloatingComplexCast;
7127 case Type::STK_IntegralComplex:
7128 return CK_FloatingComplexToIntegralComplex;
7129 case Type::STK_Floating: {
7130 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7131 if (Context.hasSameType(ET, DestTy))
7132 return CK_FloatingComplexToReal;
7133 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7134 return CK_FloatingCast;
7135 }
7136 case Type::STK_Bool:
7137 return CK_FloatingComplexToBoolean;
7138 case Type::STK_Integral:
7139 Src = ImpCastExprToType(Src.get(),
7140 SrcTy->castAs<ComplexType>()->getElementType(),
7141 CK_FloatingComplexToReal);
7142 return CK_FloatingToIntegral;
7143 case Type::STK_CPointer:
7144 case Type::STK_ObjCObjectPointer:
7145 case Type::STK_BlockPointer:
7146 llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7146)
;
7147 case Type::STK_MemberPointer:
7148 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7148)
;
7149 case Type::STK_FixedPoint:
7150 Diag(Src.get()->getExprLoc(),
7151 diag::err_unimplemented_conversion_with_fixed_point_type)
7152 << SrcTy;
7153 return CK_IntegralCast;
7154 }
7155 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7155)
;
7156
7157 case Type::STK_IntegralComplex:
7158 switch (DestTy->getScalarTypeKind()) {
7159 case Type::STK_FloatingComplex:
7160 return CK_IntegralComplexToFloatingComplex;
7161 case Type::STK_IntegralComplex:
7162 return CK_IntegralComplexCast;
7163 case Type::STK_Integral: {
7164 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7165 if (Context.hasSameType(ET, DestTy))
7166 return CK_IntegralComplexToReal;
7167 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7168 return CK_IntegralCast;
7169 }
7170 case Type::STK_Bool:
7171 return CK_IntegralComplexToBoolean;
7172 case Type::STK_Floating:
7173 Src = ImpCastExprToType(Src.get(),
7174 SrcTy->castAs<ComplexType>()->getElementType(),
7175 CK_IntegralComplexToReal);
7176 return CK_IntegralToFloating;
7177 case Type::STK_CPointer:
7178 case Type::STK_ObjCObjectPointer:
7179 case Type::STK_BlockPointer:
7180 llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7180)
;
7181 case Type::STK_MemberPointer:
7182 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7182)
;
7183 case Type::STK_FixedPoint:
7184 Diag(Src.get()->getExprLoc(),
7185 diag::err_unimplemented_conversion_with_fixed_point_type)
7186 << SrcTy;
7187 return CK_IntegralCast;
7188 }
7189 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7189)
;
7190 }
7191
7192 llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7192)
;
7193}
7194
7195static bool breakDownVectorType(QualType type, uint64_t &len,
7196 QualType &eltType) {
7197 // Vectors are simple.
7198 if (const VectorType *vecType = type->getAs<VectorType>()) {
7199 len = vecType->getNumElements();
7200 eltType = vecType->getElementType();
7201 assert(eltType->isScalarType())((eltType->isScalarType()) ? static_cast<void> (0) :
__assert_fail ("eltType->isScalarType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7201, __PRETTY_FUNCTION__))
;
7202 return true;
7203 }
7204
7205 // We allow lax conversion to and from non-vector types, but only if
7206 // they're real types (i.e. non-complex, non-pointer scalar types).
7207 if (!type->isRealType()) return false;
7208
7209 len = 1;
7210 eltType = type;
7211 return true;
7212}
7213
7214/// Are the two types lax-compatible vector types? That is, given
7215/// that one of them is a vector, do they have equal storage sizes,
7216/// where the storage size is the number of elements times the element
7217/// size?
7218///
7219/// This will also return false if either of the types is neither a
7220/// vector nor a real type.
7221bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7222 assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast
<void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7222, __PRETTY_FUNCTION__))
;
7223
7224 // Disallow lax conversions between scalars and ExtVectors (these
7225 // conversions are allowed for other vector types because common headers
7226 // depend on them). Most scalar OP ExtVector cases are handled by the
7227 // splat path anyway, which does what we want (convert, not bitcast).
7228 // What this rules out for ExtVectors is crazy things like char4*float.
7229 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7230 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7231
7232 uint64_t srcLen, destLen;
7233 QualType srcEltTy, destEltTy;
7234 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7235 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7236
7237 // ASTContext::getTypeSize will return the size rounded up to a
7238 // power of 2, so instead of using that, we need to use the raw
7239 // element size multiplied by the element count.
7240 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7241 uint64_t destEltSize = Context.getTypeSize(destEltTy);
7242
7243 return (srcLen * srcEltSize == destLen * destEltSize);
7244}
7245
7246/// Is this a legal conversion between two types, one of which is
7247/// known to be a vector type?
7248bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7249 assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast
<void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7249, __PRETTY_FUNCTION__))
;
7250
7251 switch (Context.getLangOpts().getLaxVectorConversions()) {
7252 case LangOptions::LaxVectorConversionKind::None:
7253 return false;
7254
7255 case LangOptions::LaxVectorConversionKind::Integer:
7256 if (!srcTy->isIntegralOrEnumerationType()) {
7257 auto *Vec = srcTy->getAs<VectorType>();
7258 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7259 return false;
7260 }
7261 if (!destTy->isIntegralOrEnumerationType()) {
7262 auto *Vec = destTy->getAs<VectorType>();
7263 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7264 return false;
7265 }
7266 // OK, integer (vector) -> integer (vector) bitcast.
7267 break;
7268
7269 case LangOptions::LaxVectorConversionKind::All:
7270 break;
7271 }
7272
7273 return areLaxCompatibleVectorTypes(srcTy, destTy);
7274}
7275
7276bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7277 CastKind &Kind) {
7278 assert(VectorTy->isVectorType() && "Not a vector type!")((VectorTy->isVectorType() && "Not a vector type!"
) ? static_cast<void> (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7278, __PRETTY_FUNCTION__))
;
7279
7280 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7281 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7282 return Diag(R.getBegin(),
7283 Ty->isVectorType() ?
7284 diag::err_invalid_conversion_between_vectors :
7285 diag::err_invalid_conversion_between_vector_and_integer)
7286 << VectorTy << Ty << R;
7287 } else
7288 return Diag(R.getBegin(),
7289 diag::err_invalid_conversion_between_vector_and_scalar)
7290 << VectorTy << Ty << R;
7291
7292 Kind = CK_BitCast;
7293 return false;
7294}
7295
7296ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7297 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7298
7299 if (DestElemTy == SplattedExpr->getType())
7300 return SplattedExpr;
7301
7302 assert(DestElemTy->isFloatingType() ||((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7303, __PRETTY_FUNCTION__))
7303 DestElemTy->isIntegralOrEnumerationType())((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7303, __PRETTY_FUNCTION__))
;
7304
7305 CastKind CK;
7306 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7307 // OpenCL requires that we convert `true` boolean expressions to -1, but
7308 // only when splatting vectors.
7309 if (DestElemTy->isFloatingType()) {
7310 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7311 // in two steps: boolean to signed integral, then to floating.
7312 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7313 CK_BooleanToSignedIntegral);
7314 SplattedExpr = CastExprRes.get();
7315 CK = CK_IntegralToFloating;
7316 } else {
7317 CK = CK_BooleanToSignedIntegral;
7318 }
7319 } else {
7320 ExprResult CastExprRes = SplattedExpr;
7321 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7322 if (CastExprRes.isInvalid())
7323 return ExprError();
7324 SplattedExpr = CastExprRes.get();
7325 }
7326 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7327}
7328
7329ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7330 Expr *CastExpr, CastKind &Kind) {
7331 assert(DestTy->isExtVectorType() && "Not an extended vector type!")((DestTy->isExtVectorType() && "Not an extended vector type!"
) ? static_cast<void> (0) : __assert_fail ("DestTy->isExtVectorType() && \"Not an extended vector type!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7331, __PRETTY_FUNCTION__))
;
7332
7333 QualType SrcTy = CastExpr->getType();
7334
7335 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7336 // an ExtVectorType.
7337 // In OpenCL, casts between vectors of different types are not allowed.
7338 // (See OpenCL 6.2).
7339 if (SrcTy->isVectorType()) {
7340 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7341 (getLangOpts().OpenCL &&
7342 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7343 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7344 << DestTy << SrcTy << R;
7345 return ExprError();
7346 }
7347 Kind = CK_BitCast;
7348 return CastExpr;
7349 }
7350
7351 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7352 // conversion will take place first from scalar to elt type, and then
7353 // splat from elt type to vector.
7354 if (SrcTy->isPointerType())
7355 return Diag(R.getBegin(),
7356 diag::err_invalid_conversion_between_vector_and_scalar)
7357 << DestTy << SrcTy << R;
7358
7359 Kind = CK_VectorSplat;
7360 return prepareVectorSplat(DestTy, CastExpr);
7361}
7362
7363ExprResult
7364Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7365 Declarator &D, ParsedType &Ty,
7366 SourceLocation RParenLoc, Expr *CastExpr) {
7367 assert(!D.isInvalidType() && (CastExpr != nullptr) &&((!D.isInvalidType() && (CastExpr != nullptr) &&
"ActOnCastExpr(): missing type or expr") ? static_cast<void
> (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7368, __PRETTY_FUNCTION__))
7368 "ActOnCastExpr(): missing type or expr")((!D.isInvalidType() && (CastExpr != nullptr) &&
"ActOnCastExpr(): missing type or expr") ? static_cast<void
> (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7368, __PRETTY_FUNCTION__))
;
7369
7370 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7371 if (D.isInvalidType())
7372 return ExprError();
7373
7374 if (getLangOpts().CPlusPlus) {
7375 // Check that there are no default arguments (C++ only).
7376 CheckExtraCXXDefaultArguments(D);
7377 } else {
7378 // Make sure any TypoExprs have been dealt with.
7379 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7380 if (!Res.isUsable())
7381 return ExprError();
7382 CastExpr = Res.get();
7383 }
7384
7385 checkUnusedDeclAttributes(D);
7386
7387 QualType castType = castTInfo->getType();
7388 Ty = CreateParsedType(castType, castTInfo);
7389
7390 bool isVectorLiteral = false;
7391
7392 // Check for an altivec or OpenCL literal,
7393 // i.e. all the elements are integer constants.
7394 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7395 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7396 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7397 && castType->isVectorType() && (PE || PLE)) {
7398 if (PLE && PLE->getNumExprs() == 0) {
7399 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7400 return ExprError();
7401 }
7402 if (PE || PLE->getNumExprs() == 1) {
7403 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7404 if (!E->getType()->isVectorType())
7405 isVectorLiteral = true;
7406 }
7407 else
7408 isVectorLiteral = true;
7409 }
7410
7411 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7412 // then handle it as such.
7413 if (isVectorLiteral)
7414 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7415
7416 // If the Expr being casted is a ParenListExpr, handle it specially.
7417 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7418 // sequence of BinOp comma operators.
7419 if (isa<ParenListExpr>(CastExpr)) {
7420 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7421 if (Result.isInvalid()) return ExprError();
7422 CastExpr = Result.get();
7423 }
7424
7425 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7426 !getSourceManager().isInSystemMacro(LParenLoc))
7427 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7428
7429 CheckTollFreeBridgeCast(castType, CastExpr);
7430
7431 CheckObjCBridgeRelatedCast(castType, CastExpr);
7432
7433 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7434
7435 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7436}
7437
7438ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7439 SourceLocation RParenLoc, Expr *E,
7440 TypeSourceInfo *TInfo) {
7441 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
"Expected paren or paren list expression") ? static_cast<
void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7442, __PRETTY_FUNCTION__))
7442 "Expected paren or paren list expression")(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
"Expected paren or paren list expression") ? static_cast<
void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7442, __PRETTY_FUNCTION__))
;
7443
7444 Expr **exprs;
7445 unsigned numExprs;
7446 Expr *subExpr;
7447 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7448 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7449 LiteralLParenLoc = PE->getLParenLoc();
7450 LiteralRParenLoc = PE->getRParenLoc();
7451 exprs = PE->getExprs();
7452 numExprs = PE->getNumExprs();
7453 } else { // isa<ParenExpr> by assertion at function entrance
7454 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7455 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7456 subExpr = cast<ParenExpr>(E)->getSubExpr();
7457 exprs = &subExpr;
7458 numExprs = 1;
7459 }
7460
7461 QualType Ty = TInfo->getType();
7462 assert(Ty->isVectorType() && "Expected vector type")((Ty->isVectorType() && "Expected vector type") ? static_cast
<void> (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7462, __PRETTY_FUNCTION__))
;
7463
7464 SmallVector<Expr *, 8> initExprs;
7465 const VectorType *VTy = Ty->castAs<VectorType>();
7466 unsigned numElems = VTy->getNumElements();
7467
7468 // '(...)' form of vector initialization in AltiVec: the number of
7469 // initializers must be one or must match the size of the vector.
7470 // If a single value is specified in the initializer then it will be
7471 // replicated to all the components of the vector
7472 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7473 // The number of initializers must be one or must match the size of the
7474 // vector. If a single value is specified in the initializer then it will
7475 // be replicated to all the components of the vector
7476 if (numExprs == 1) {
7477 QualType ElemTy = VTy->getElementType();
7478 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7479 if (Literal.isInvalid())
7480 return ExprError();
7481 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7482 PrepareScalarCast(Literal, ElemTy));
7483 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7484 }
7485 else if (numExprs < numElems) {
7486 Diag(E->getExprLoc(),
7487 diag::err_incorrect_number_of_vector_initializers);
7488 return ExprError();
7489 }
7490 else
7491 initExprs.append(exprs, exprs + numExprs);
7492 }
7493 else {
7494 // For OpenCL, when the number of initializers is a single value,
7495 // it will be replicated to all components of the vector.
7496 if (getLangOpts().OpenCL &&
7497 VTy->getVectorKind() == VectorType::GenericVector &&
7498 numExprs == 1) {
7499 QualType ElemTy = VTy->getElementType();
7500 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7501 if (Literal.isInvalid())
7502 return ExprError();
7503 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7504 PrepareScalarCast(Literal, ElemTy));
7505 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7506 }
7507
7508 initExprs.append(exprs, exprs + numExprs);
7509 }
7510 // FIXME: This means that pretty-printing the final AST will produce curly
7511 // braces instead of the original commas.
7512 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7513 initExprs, LiteralRParenLoc);
7514 initE->setType(Ty);
7515 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7516}
7517
7518/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7519/// the ParenListExpr into a sequence of comma binary operators.
7520ExprResult
7521Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7522 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7523 if (!E)
7524 return OrigExpr;
7525
7526 ExprResult Result(E->getExpr(0));
7527
7528 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7529 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7530 E->getExpr(i));
7531
7532 if (Result.isInvalid()) return ExprError();
7533
7534 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7535}
7536
7537ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7538 SourceLocation R,
7539 MultiExprArg Val) {
7540 return ParenListExpr::Create(Context, L, Val, R);
7541}
7542
7543/// Emit a specialized diagnostic when one expression is a null pointer
7544/// constant and the other is not a pointer. Returns true if a diagnostic is
7545/// emitted.
7546bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7547 SourceLocation QuestionLoc) {
7548 Expr *NullExpr = LHSExpr;
7549 Expr *NonPointerExpr = RHSExpr;
7550 Expr::NullPointerConstantKind NullKind =
7551 NullExpr->isNullPointerConstant(Context,
7552 Expr::NPC_ValueDependentIsNotNull);
7553
7554 if (NullKind == Expr::NPCK_NotNull) {
7555 NullExpr = RHSExpr;
7556 NonPointerExpr = LHSExpr;
7557 NullKind =
7558 NullExpr->isNullPointerConstant(Context,
7559 Expr::NPC_ValueDependentIsNotNull);
7560 }
7561
7562 if (NullKind == Expr::NPCK_NotNull)
7563 return false;
7564
7565 if (NullKind == Expr::NPCK_ZeroExpression)
7566 return false;
7567
7568 if (NullKind == Expr::NPCK_ZeroLiteral) {
7569 // In this case, check to make sure that we got here from a "NULL"
7570 // string in the source code.
7571 NullExpr = NullExpr->IgnoreParenImpCasts();
7572 SourceLocation loc = NullExpr->getExprLoc();
7573 if (!findMacroSpelling(loc, "NULL"))
7574 return false;
7575 }
7576
7577 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7578 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7579 << NonPointerExpr->getType() << DiagType
7580 << NonPointerExpr->getSourceRange();
7581 return true;
7582}
7583
7584/// Return false if the condition expression is valid, true otherwise.
7585static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7586 QualType CondTy = Cond->getType();
7587
7588 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7589 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7590 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7591 << CondTy << Cond->getSourceRange();
7592 return true;
7593 }
7594
7595 // C99 6.5.15p2
7596 if (CondTy->isScalarType()) return false;
7597
7598 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7599 << CondTy << Cond->getSourceRange();
7600 return true;
7601}
7602
7603/// Handle when one or both operands are void type.
7604static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7605 ExprResult &RHS) {
7606 Expr *LHSExpr = LHS.get();
7607 Expr *RHSExpr = RHS.get();
7608
7609 if (!LHSExpr->getType()->isVoidType())
7610 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7611 << RHSExpr->getSourceRange();
7612 if (!RHSExpr->getType()->isVoidType())
7613 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7614 << LHSExpr->getSourceRange();
7615 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7616 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7617 return S.Context.VoidTy;
7618}
7619
7620/// Return false if the NullExpr can be promoted to PointerTy,
7621/// true otherwise.
7622static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7623 QualType PointerTy) {
7624 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7625 !NullExpr.get()->isNullPointerConstant(S.Context,
7626 Expr::NPC_ValueDependentIsNull))
7627 return true;
7628
7629 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7630 return false;
7631}
7632
7633/// Checks compatibility between two pointers and return the resulting
7634/// type.
7635static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7636 ExprResult &RHS,
7637 SourceLocation Loc) {
7638 QualType LHSTy = LHS.get()->getType();
7639 QualType RHSTy = RHS.get()->getType();
7640
7641 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7642 // Two identical pointers types are always compatible.
7643 return LHSTy;
7644 }
7645
7646 QualType lhptee, rhptee;
7647
7648 // Get the pointee types.
7649 bool IsBlockPointer = false;
7650 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7651 lhptee = LHSBTy->getPointeeType();
7652 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7653 IsBlockPointer = true;
7654 } else {
7655 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7656 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7657 }
7658
7659 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7660 // differently qualified versions of compatible types, the result type is
7661 // a pointer to an appropriately qualified version of the composite
7662 // type.
7663
7664 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7665 // clause doesn't make sense for our extensions. E.g. address space 2 should
7666 // be incompatible with address space 3: they may live on different devices or
7667 // anything.
7668 Qualifiers lhQual = lhptee.getQualifiers();
7669 Qualifiers rhQual = rhptee.getQualifiers();
7670
7671 LangAS ResultAddrSpace = LangAS::Default;
7672 LangAS LAddrSpace = lhQual.getAddressSpace();
7673 LangAS RAddrSpace = rhQual.getAddressSpace();
7674
7675 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7676 // spaces is disallowed.
7677 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7678 ResultAddrSpace = LAddrSpace;
7679 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7680 ResultAddrSpace = RAddrSpace;
7681 else {
7682 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7683 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7684 << RHS.get()->getSourceRange();
7685 return QualType();
7686 }
7687
7688 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7689 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7690 lhQual.removeCVRQualifiers();
7691 rhQual.removeCVRQualifiers();
7692
7693 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7694 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7695 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7696 // qual types are compatible iff
7697 // * corresponded types are compatible
7698 // * CVR qualifiers are equal
7699 // * address spaces are equal
7700 // Thus for conditional operator we merge CVR and address space unqualified
7701 // pointees and if there is a composite type we return a pointer to it with
7702 // merged qualifiers.
7703 LHSCastKind =
7704 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7705 RHSCastKind =
7706 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7707 lhQual.removeAddressSpace();
7708 rhQual.removeAddressSpace();
7709
7710 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7711 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7712
7713 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7714
7715 if (CompositeTy.isNull()) {
7716 // In this situation, we assume void* type. No especially good
7717 // reason, but this is what gcc does, and we do have to pick
7718 // to get a consistent AST.
7719 QualType incompatTy;
7720 incompatTy = S.Context.getPointerType(
7721 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7722 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7723 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7724
7725 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7726 // for casts between types with incompatible address space qualifiers.
7727 // For the following code the compiler produces casts between global and
7728 // local address spaces of the corresponded innermost pointees:
7729 // local int *global *a;
7730 // global int *global *b;
7731 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7732 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7733 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7734 << RHS.get()->getSourceRange();
7735
7736 return incompatTy;
7737 }
7738
7739 // The pointer types are compatible.
7740 // In case of OpenCL ResultTy should have the address space qualifier
7741 // which is a superset of address spaces of both the 2nd and the 3rd
7742 // operands of the conditional operator.
7743 QualType ResultTy = [&, ResultAddrSpace]() {
7744 if (S.getLangOpts().OpenCL) {
7745 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7746 CompositeQuals.setAddressSpace(ResultAddrSpace);
7747 return S.Context
7748 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7749 .withCVRQualifiers(MergedCVRQual);
7750 }
7751 return CompositeTy.withCVRQualifiers(MergedCVRQual);
7752 }();
7753 if (IsBlockPointer)
7754 ResultTy = S.Context.getBlockPointerType(ResultTy);
7755 else
7756 ResultTy = S.Context.getPointerType(ResultTy);
7757
7758 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7759 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7760 return ResultTy;
7761}
7762
7763/// Return the resulting type when the operands are both block pointers.
7764static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7765 ExprResult &LHS,
7766 ExprResult &RHS,
7767 SourceLocation Loc) {
7768 QualType LHSTy = LHS.get()->getType();
7769 QualType RHSTy = RHS.get()->getType();
7770
7771 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7772 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7773 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7774 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7775 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7776 return destType;
7777 }
7778 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7779 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7780 << RHS.get()->getSourceRange();
7781 return QualType();
7782 }
7783
7784 // We have 2 block pointer types.
7785 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7786}
7787
7788/// Return the resulting type when the operands are both pointers.
7789static QualType
7790checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7791 ExprResult &RHS,
7792 SourceLocation Loc) {
7793 // get the pointer types
7794 QualType LHSTy = LHS.get()->getType();
7795 QualType RHSTy = RHS.get()->getType();
7796
7797 // get the "pointed to" types
7798 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7799 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7800
7801 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7802 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7803 // Figure out necessary qualifiers (C99 6.5.15p6)
7804 QualType destPointee
7805 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7806 QualType destType = S.Context.getPointerType(destPointee);
7807 // Add qualifiers if necessary.
7808 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7809 // Promote to void*.
7810 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7811 return destType;
7812 }
7813 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7814 QualType destPointee
7815 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7816 QualType destType = S.Context.getPointerType(destPointee);
7817 // Add qualifiers if necessary.
7818 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7819 // Promote to void*.
7820 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7821 return destType;
7822 }
7823
7824 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7825}
7826
7827/// Return false if the first expression is not an integer and the second
7828/// expression is not a pointer, true otherwise.
7829static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7830 Expr* PointerExpr, SourceLocation Loc,
7831 bool IsIntFirstExpr) {
7832 if (!PointerExpr->getType()->isPointerType() ||
7833 !Int.get()->getType()->isIntegerType())
7834 return false;
7835
7836 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7837 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7838
7839 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7840 << Expr1->getType() << Expr2->getType()
7841 << Expr1->getSourceRange() << Expr2->getSourceRange();
7842 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7843 CK_IntegralToPointer);
7844 return true;
7845}
7846
7847/// Simple conversion between integer and floating point types.
7848///
7849/// Used when handling the OpenCL conditional operator where the
7850/// condition is a vector while the other operands are scalar.
7851///
7852/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7853/// types are either integer or floating type. Between the two
7854/// operands, the type with the higher rank is defined as the "result
7855/// type". The other operand needs to be promoted to the same type. No
7856/// other type promotion is allowed. We cannot use
7857/// UsualArithmeticConversions() for this purpose, since it always
7858/// promotes promotable types.
7859static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7860 ExprResult &RHS,
7861 SourceLocation QuestionLoc) {
7862 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7863 if (LHS.isInvalid())
7864 return QualType();
7865 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7866 if (RHS.isInvalid())
7867 return QualType();
7868
7869 // For conversion purposes, we ignore any qualifiers.
7870 // For example, "const float" and "float" are equivalent.
7871 QualType LHSType =
7872 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7873 QualType RHSType =
7874 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7875
7876 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7877 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7878 << LHSType << LHS.get()->getSourceRange();
7879 return QualType();
7880 }
7881
7882 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7883 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7884 << RHSType << RHS.get()->getSourceRange();
7885 return QualType();
7886 }
7887
7888 // If both types are identical, no conversion is needed.
7889 if (LHSType == RHSType)
7890 return LHSType;
7891
7892 // Now handle "real" floating types (i.e. float, double, long double).
7893 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7894 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7895 /*IsCompAssign = */ false);
7896
7897 // Finally, we have two differing integer types.
7898 return handleIntegerConversion<doIntegralCast, doIntegralCast>
7899 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7900}
7901
7902/// Convert scalar operands to a vector that matches the
7903/// condition in length.
7904///
7905/// Used when handling the OpenCL conditional operator where the
7906/// condition is a vector while the other operands are scalar.
7907///
7908/// We first compute the "result type" for the scalar operands
7909/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7910/// into a vector of that type where the length matches the condition
7911/// vector type. s6.11.6 requires that the element types of the result
7912/// and the condition must have the same number of bits.
7913static QualType
7914OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7915 QualType CondTy, SourceLocation QuestionLoc) {
7916 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7917 if (ResTy.isNull()) return QualType();
7918
7919 const VectorType *CV = CondTy->getAs<VectorType>();
7920 assert(CV)((CV) ? static_cast<void> (0) : __assert_fail ("CV", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7920, __PRETTY_FUNCTION__))
;
7921
7922 // Determine the vector result type
7923 unsigned NumElements = CV->getNumElements();
7924 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7925
7926 // Ensure that all types have the same number of bits
7927 if (S.Context.getTypeSize(CV->getElementType())
7928 != S.Context.getTypeSize(ResTy)) {
7929 // Since VectorTy is created internally, it does not pretty print
7930 // with an OpenCL name. Instead, we just print a description.
7931 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7932 SmallString<64> Str;
7933 llvm::raw_svector_ostream OS(Str);
7934 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7935 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7936 << CondTy << OS.str();
7937 return QualType();
7938 }
7939
7940 // Convert operands to the vector result type
7941 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7942 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7943
7944 return VectorTy;
7945}
7946
7947/// Return false if this is a valid OpenCL condition vector
7948static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7949 SourceLocation QuestionLoc) {
7950 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7951 // integral type.
7952 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7953 assert(CondTy)((CondTy) ? static_cast<void> (0) : __assert_fail ("CondTy"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7953, __PRETTY_FUNCTION__))
;
7954 QualType EleTy = CondTy->getElementType();
7955 if (EleTy->isIntegerType()) return false;
7956
7957 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7958 << Cond->getType() << Cond->getSourceRange();
7959 return true;
7960}
7961
7962/// Return false if the vector condition type and the vector
7963/// result type are compatible.
7964///
7965/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7966/// number of elements, and their element types have the same number
7967/// of bits.
7968static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7969 SourceLocation QuestionLoc) {
7970 const VectorType *CV = CondTy->getAs<VectorType>();
7971 const VectorType *RV = VecResTy->getAs<VectorType>();
7972 assert(CV && RV)((CV && RV) ? static_cast<void> (0) : __assert_fail
("CV && RV", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 7972, __PRETTY_FUNCTION__))
;
7973
7974 if (CV->getNumElements() != RV->getNumElements()) {
7975 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7976 << CondTy << VecResTy;
7977 return true;
7978 }
7979
7980 QualType CVE = CV->getElementType();
7981 QualType RVE = RV->getElementType();
7982
7983 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7984 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7985 << CondTy << VecResTy;
7986 return true;
7987 }
7988
7989 return false;
7990}
7991
7992/// Return the resulting type for the conditional operator in
7993/// OpenCL (aka "ternary selection operator", OpenCL v1.1
7994/// s6.3.i) when the condition is a vector type.
7995static QualType
7996OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7997 ExprResult &LHS, ExprResult &RHS,
7998 SourceLocation QuestionLoc) {
7999 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8000 if (Cond.isInvalid())
8001 return QualType();
8002 QualType CondTy = Cond.get()->getType();
8003
8004 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8005 return QualType();
8006
8007 // If either operand is a vector then find the vector type of the
8008 // result as specified in OpenCL v1.1 s6.3.i.
8009 if (LHS.get()->getType()->isVectorType() ||
8010 RHS.get()->getType()->isVectorType()) {
8011 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8012 /*isCompAssign*/false,
8013 /*AllowBothBool*/true,
8014 /*AllowBoolConversions*/false);
8015 if (VecResTy.isNull()) return QualType();
8016 // The result type must match the condition type as specified in
8017 // OpenCL v1.1 s6.11.6.
8018 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8019 return QualType();
8020 return VecResTy;
8021 }
8022
8023 // Both operands are scalar.
8024 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8025}
8026
8027/// Return true if the Expr is block type
8028static bool checkBlockType(Sema &S, const Expr *E) {
8029 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8030 QualType Ty = CE->getCallee()->getType();
8031 if (Ty->isBlockPointerType()) {
8032 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8033 return true;
8034 }
8035 }
8036 return false;
8037}
8038
8039/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8040/// In that case, LHS = cond.
8041/// C99 6.5.15
8042QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8043 ExprResult &RHS, ExprValueKind &VK,
8044 ExprObjectKind &OK,
8045 SourceLocation QuestionLoc) {
8046
8047 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8048 if (!LHSResult.isUsable()) return QualType();
8049 LHS = LHSResult;
8050
8051 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8052 if (!RHSResult.isUsable()) return QualType();
8053 RHS = RHSResult;
8054
8055 // C++ is sufficiently different to merit its own checker.
8056 if (getLangOpts().CPlusPlus)
8057 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8058
8059 VK = VK_RValue;
8060 OK = OK_Ordinary;
8061
8062 // The OpenCL operator with a vector condition is sufficiently
8063 // different to merit its own checker.
8064 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8065 Cond.get()->getType()->isExtVectorType())
8066 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8067
8068 // First, check the condition.
8069 Cond = UsualUnaryConversions(Cond.get());
8070 if (Cond.isInvalid())
8071 return QualType();
8072 if (checkCondition(*this, Cond.get(), QuestionLoc))
8073 return QualType();
8074
8075 // Now check the two expressions.
8076 if (LHS.get()->getType()->isVectorType() ||
8077 RHS.get()->getType()->isVectorType())
8078 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8079 /*AllowBothBool*/true,
8080 /*AllowBoolConversions*/false);
8081
8082 QualType ResTy =
8083 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8084 if (LHS.isInvalid() || RHS.isInvalid())
8085 return QualType();
8086
8087 QualType LHSTy = LHS.get()->getType();
8088 QualType RHSTy = RHS.get()->getType();
8089
8090 // Diagnose attempts to convert between __float128 and long double where
8091 // such conversions currently can't be handled.
8092 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8093 Diag(QuestionLoc,
8094 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8095 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8096 return QualType();
8097 }
8098
8099 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8100 // selection operator (?:).
8101 if (getLangOpts().OpenCL &&
8102 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8103 return QualType();
8104 }
8105
8106 // If both operands have arithmetic type, do the usual arithmetic conversions
8107 // to find a common type: C99 6.5.15p3,5.
8108 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8109 // Disallow invalid arithmetic conversions, such as those between ExtInts of
8110 // different sizes, or between ExtInts and other types.
8111 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8112 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8113 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8114 << RHS.get()->getSourceRange();
8115 return QualType();
8116 }
8117
8118 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8119 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8120
8121 return ResTy;
8122 }
8123
8124 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8125 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8126 return LHSTy;
8127 }
8128
8129 // If both operands are the same structure or union type, the result is that
8130 // type.
8131 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8132 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8133 if (LHSRT->getDecl() == RHSRT->getDecl())
8134 // "If both the operands have structure or union type, the result has
8135 // that type." This implies that CV qualifiers are dropped.
8136 return LHSTy.getUnqualifiedType();
8137 // FIXME: Type of conditional expression must be complete in C mode.
8138 }
8139
8140 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8141 // The following || allows only one side to be void (a GCC-ism).
8142 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8143 return checkConditionalVoidType(*this, LHS, RHS);
8144 }
8145
8146 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8147 // the type of the other operand."
8148 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8149 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8150
8151 // All objective-c pointer type analysis is done here.
8152 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8153 QuestionLoc);
8154 if (LHS.isInvalid() || RHS.isInvalid())
8155 return QualType();
8156 if (!compositeType.isNull())
8157 return compositeType;
8158
8159
8160 // Handle block pointer types.
8161 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8162 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8163 QuestionLoc);
8164
8165 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8166 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8167 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8168 QuestionLoc);
8169
8170 // GCC compatibility: soften pointer/integer mismatch. Note that
8171 // null pointers have been filtered out by this point.
8172 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8173 /*IsIntFirstExpr=*/true))
8174 return RHSTy;
8175 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8176 /*IsIntFirstExpr=*/false))
8177 return LHSTy;
8178
8179 // Allow ?: operations in which both operands have the same
8180 // built-in sizeless type.
8181 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8182 return LHSTy;
8183
8184 // Emit a better diagnostic if one of the expressions is a null pointer
8185 // constant and the other is not a pointer type. In this case, the user most
8186 // likely forgot to take the address of the other expression.
8187 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8188 return QualType();
8189
8190 // Otherwise, the operands are not compatible.
8191 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8192 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8193 << RHS.get()->getSourceRange();
8194 return QualType();
8195}
8196
8197/// FindCompositeObjCPointerType - Helper method to find composite type of
8198/// two objective-c pointer types of the two input expressions.
8199QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8200 SourceLocation QuestionLoc) {
8201 QualType LHSTy = LHS.get()->getType();
8202 QualType RHSTy = RHS.get()->getType();
8203
8204 // Handle things like Class and struct objc_class*. Here we case the result
8205 // to the pseudo-builtin, because that will be implicitly cast back to the
8206 // redefinition type if an attempt is made to access its fields.
8207 if (LHSTy->isObjCClassType() &&
8208 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8209 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8210 return LHSTy;
8211 }
8212 if (RHSTy->isObjCClassType() &&
8213 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8214 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8215 return RHSTy;
8216 }
8217 // And the same for struct objc_object* / id
8218 if (LHSTy->isObjCIdType() &&
8219 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8220 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8221 return LHSTy;
8222 }
8223 if (RHSTy->isObjCIdType() &&
8224 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8225 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8226 return RHSTy;
8227 }
8228 // And the same for struct objc_selector* / SEL
8229 if (Context.isObjCSelType(LHSTy) &&
8230 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8231 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8232 return LHSTy;
8233 }
8234 if (Context.isObjCSelType(RHSTy) &&
8235 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8236 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8237 return RHSTy;
8238 }
8239 // Check constraints for Objective-C object pointers types.
8240 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8241
8242 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8243 // Two identical object pointer types are always compatible.
8244 return LHSTy;
8245 }
8246 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8247 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8248 QualType compositeType = LHSTy;
8249
8250 // If both operands are interfaces and either operand can be
8251 // assigned to the other, use that type as the composite
8252 // type. This allows
8253 // xxx ? (A*) a : (B*) b
8254 // where B is a subclass of A.
8255 //
8256 // Additionally, as for assignment, if either type is 'id'
8257 // allow silent coercion. Finally, if the types are
8258 // incompatible then make sure to use 'id' as the composite
8259 // type so the result is acceptable for sending messages to.
8260
8261 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8262 // It could return the composite type.
8263 if (!(compositeType =
8264 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8265 // Nothing more to do.
8266 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8267 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8268 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8269 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8270 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8271 RHSOPT->isObjCQualifiedIdType()) &&
8272 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8273 true)) {
8274 // Need to handle "id<xx>" explicitly.
8275 // GCC allows qualified id and any Objective-C type to devolve to
8276 // id. Currently localizing to here until clear this should be
8277 // part of ObjCQualifiedIdTypesAreCompatible.
8278 compositeType = Context.getObjCIdType();
8279 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8280 compositeType = Context.getObjCIdType();
8281 } else {
8282 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8283 << LHSTy << RHSTy
8284 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8285 QualType incompatTy = Context.getObjCIdType();
8286 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8287 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8288 return incompatTy;
8289 }
8290 // The object pointer types are compatible.
8291 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8292 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8293 return compositeType;
8294 }
8295 // Check Objective-C object pointer types and 'void *'
8296 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8297 if (getLangOpts().ObjCAutoRefCount) {
8298 // ARC forbids the implicit conversion of object pointers to 'void *',
8299 // so these types are not compatible.
8300 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8301 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8302 LHS = RHS = true;
8303 return QualType();
8304 }
8305 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8306 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8307 QualType destPointee
8308 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8309 QualType destType = Context.getPointerType(destPointee);
8310 // Add qualifiers if necessary.
8311 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8312 // Promote to void*.
8313 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8314 return destType;
8315 }
8316 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8317 if (getLangOpts().ObjCAutoRefCount) {
8318 // ARC forbids the implicit conversion of object pointers to 'void *',
8319 // so these types are not compatible.
8320 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8321 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8322 LHS = RHS = true;
8323 return QualType();
8324 }
8325 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8326 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8327 QualType destPointee
8328 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8329 QualType destType = Context.getPointerType(destPointee);
8330 // Add qualifiers if necessary.
8331 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8332 // Promote to void*.
8333 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8334 return destType;
8335 }
8336 return QualType();
8337}
8338
8339/// SuggestParentheses - Emit a note with a fixit hint that wraps
8340/// ParenRange in parentheses.
8341static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8342 const PartialDiagnostic &Note,
8343 SourceRange ParenRange) {
8344 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8345 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8346 EndLoc.isValid()) {
8347 Self.Diag(Loc, Note)
8348 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8349 << FixItHint::CreateInsertion(EndLoc, ")");
8350 } else {
8351 // We can't display the parentheses, so just show the bare note.
8352 Self.Diag(Loc, Note) << ParenRange;
8353 }
8354}
8355
8356static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8357 return BinaryOperator::isAdditiveOp(Opc) ||
8358 BinaryOperator::isMultiplicativeOp(Opc) ||
8359 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8360 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8361 // not any of the logical operators. Bitwise-xor is commonly used as a
8362 // logical-xor because there is no logical-xor operator. The logical
8363 // operators, including uses of xor, have a high false positive rate for
8364 // precedence warnings.
8365}
8366
8367/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8368/// expression, either using a built-in or overloaded operator,
8369/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8370/// expression.
8371static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8372 Expr **RHSExprs) {
8373 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8374 E = E->IgnoreImpCasts();
8375 E = E->IgnoreConversionOperator();
8376 E = E->IgnoreImpCasts();
8377 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8378 E = MTE->getSubExpr();
8379 E = E->IgnoreImpCasts();
8380 }
8381
8382 // Built-in binary operator.
8383 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8384 if (IsArithmeticOp(OP->getOpcode())) {
8385 *Opcode = OP->getOpcode();
8386 *RHSExprs = OP->getRHS();
8387 return true;
8388 }
8389 }
8390
8391 // Overloaded operator.
8392 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8393 if (Call->getNumArgs() != 2)
8394 return false;
8395
8396 // Make sure this is really a binary operator that is safe to pass into
8397 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8398 OverloadedOperatorKind OO = Call->getOperator();
8399 if (OO < OO_Plus || OO > OO_Arrow ||
8400 OO == OO_PlusPlus || OO == OO_MinusMinus)
8401 return false;
8402
8403 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8404 if (IsArithmeticOp(OpKind)) {
8405 *Opcode = OpKind;
8406 *RHSExprs = Call->getArg(1);
8407 return true;
8408 }
8409 }
8410
8411 return false;
8412}
8413
8414/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8415/// or is a logical expression such as (x==y) which has int type, but is
8416/// commonly interpreted as boolean.
8417static bool ExprLooksBoolean(Expr *E) {
8418 E = E->IgnoreParenImpCasts();
8419
8420 if (E->getType()->isBooleanType())
8421 return true;
8422 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8423 return OP->isComparisonOp() || OP->isLogicalOp();
8424 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8425 return OP->getOpcode() == UO_LNot;
8426 if (E->getType()->isPointerType())
8427 return true;
8428 // FIXME: What about overloaded operator calls returning "unspecified boolean
8429 // type"s (commonly pointer-to-members)?
8430
8431 return false;
8432}
8433
8434/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8435/// and binary operator are mixed in a way that suggests the programmer assumed
8436/// the conditional operator has higher precedence, for example:
8437/// "int x = a + someBinaryCondition ? 1 : 2".
8438static void DiagnoseConditionalPrecedence(Sema &Self,
8439 SourceLocation OpLoc,
8440 Expr *Condition,
8441 Expr *LHSExpr,
8442 Expr *RHSExpr) {
8443 BinaryOperatorKind CondOpcode;
8444 Expr *CondRHS;
8445
8446 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8447 return;
8448 if (!ExprLooksBoolean(CondRHS))
8449 return;
8450
8451 // The condition is an arithmetic binary expression, with a right-
8452 // hand side that looks boolean, so warn.
8453
8454 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8455 ? diag::warn_precedence_bitwise_conditional
8456 : diag::warn_precedence_conditional;
8457
8458 Self.Diag(OpLoc, DiagID)
8459 << Condition->getSourceRange()
8460 << BinaryOperator::getOpcodeStr(CondOpcode);
8461
8462 SuggestParentheses(
8463 Self, OpLoc,
8464 Self.PDiag(diag::note_precedence_silence)
8465 << BinaryOperator::getOpcodeStr(CondOpcode),
8466 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8467
8468 SuggestParentheses(Self, OpLoc,
8469 Self.PDiag(diag::note_precedence_conditional_first),
8470 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8471}
8472
8473/// Compute the nullability of a conditional expression.
8474static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8475 QualType LHSTy, QualType RHSTy,
8476 ASTContext &Ctx) {
8477 if (!ResTy->isAnyPointerType())
8478 return ResTy;
8479
8480 auto GetNullability = [&Ctx](QualType Ty) {
8481 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8482 if (Kind)
8483 return *Kind;
8484 return NullabilityKind::Unspecified;
8485 };
8486
8487 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8488 NullabilityKind MergedKind;
8489
8490 // Compute nullability of a binary conditional expression.
8491 if (IsBin) {
8492 if (LHSKind == NullabilityKind::NonNull)
8493 MergedKind = NullabilityKind::NonNull;
8494 else
8495 MergedKind = RHSKind;
8496 // Compute nullability of a normal conditional expression.
8497 } else {
8498 if (LHSKind == NullabilityKind::Nullable ||
8499 RHSKind == NullabilityKind::Nullable)
8500 MergedKind = NullabilityKind::Nullable;
8501 else if (LHSKind == NullabilityKind::NonNull)
8502 MergedKind = RHSKind;
8503 else if (RHSKind == NullabilityKind::NonNull)
8504 MergedKind = LHSKind;
8505 else
8506 MergedKind = NullabilityKind::Unspecified;
8507 }
8508
8509 // Return if ResTy already has the correct nullability.
8510 if (GetNullability(ResTy) == MergedKind)
8511 return ResTy;
8512
8513 // Strip all nullability from ResTy.
8514 while (ResTy->getNullability(Ctx))
8515 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8516
8517 // Create a new AttributedType with the new nullability kind.
8518 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8519 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8520}
8521
8522/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8523/// in the case of a the GNU conditional expr extension.
8524ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8525 SourceLocation ColonLoc,
8526 Expr *CondExpr, Expr *LHSExpr,
8527 Expr *RHSExpr) {
8528 if (!getLangOpts().CPlusPlus) {
8529 // C cannot handle TypoExpr nodes in the condition because it
8530 // doesn't handle dependent types properly, so make sure any TypoExprs have
8531 // been dealt with before checking the operands.
8532 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8533 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8534 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8535
8536 if (!CondResult.isUsable())
8537 return ExprError();
8538
8539 if (LHSExpr) {
8540 if (!LHSResult.isUsable())
8541 return ExprError();
8542 }
8543
8544 if (!RHSResult.isUsable())
8545 return ExprError();
8546
8547 CondExpr = CondResult.get();
8548 LHSExpr = LHSResult.get();
8549 RHSExpr = RHSResult.get();
8550 }
8551
8552 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8553 // was the condition.
8554 OpaqueValueExpr *opaqueValue = nullptr;
8555 Expr *commonExpr = nullptr;
8556 if (!LHSExpr) {
8557 commonExpr = CondExpr;
8558 // Lower out placeholder types first. This is important so that we don't
8559 // try to capture a placeholder. This happens in few cases in C++; such
8560 // as Objective-C++'s dictionary subscripting syntax.
8561 if (commonExpr->hasPlaceholderType()) {
8562 ExprResult result = CheckPlaceholderExpr(commonExpr);
8563 if (!result.isUsable()) return ExprError();
8564 commonExpr = result.get();
8565 }
8566 // We usually want to apply unary conversions *before* saving, except
8567 // in the special case of a C++ l-value conditional.
8568 if (!(getLangOpts().CPlusPlus
8569 && !commonExpr->isTypeDependent()
8570 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8571 && commonExpr->isGLValue()
8572 && commonExpr->isOrdinaryOrBitFieldObject()
8573 && RHSExpr->isOrdinaryOrBitFieldObject()
8574 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8575 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8576 if (commonRes.isInvalid())
8577 return ExprError();
8578 commonExpr = commonRes.get();
8579 }
8580
8581 // If the common expression is a class or array prvalue, materialize it
8582 // so that we can safely refer to it multiple times.
8583 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8584 commonExpr->getType()->isArrayType())) {
8585 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8586 if (MatExpr.isInvalid())
8587 return ExprError();
8588 commonExpr = MatExpr.get();
8589 }
8590
8591 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8592 commonExpr->getType(),
8593 commonExpr->getValueKind(),
8594 commonExpr->getObjectKind(),
8595 commonExpr);
8596 LHSExpr = CondExpr = opaqueValue;
8597 }
8598
8599 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8600 ExprValueKind VK = VK_RValue;
8601 ExprObjectKind OK = OK_Ordinary;
8602 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8603 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8604 VK, OK, QuestionLoc);
8605 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8606 RHS.isInvalid())
8607 return ExprError();
8608
8609 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8610 RHS.get());
8611
8612 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8613
8614 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8615 Context);
8616
8617 if (!commonExpr)
8618 return new (Context)
8619 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8620 RHS.get(), result, VK, OK);
8621
8622 return new (Context) BinaryConditionalOperator(
8623 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8624 ColonLoc, result, VK, OK);
8625}
8626
8627// Check if we have a conversion between incompatible cmse function pointer
8628// types, that is, a conversion between a function pointer with the
8629// cmse_nonsecure_call attribute and one without.
8630static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8631 QualType ToType) {
8632 if (const auto *ToFn =
8633 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8634 if (const auto *FromFn =
8635 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8636 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8637 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8638
8639 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8640 }
8641 }
8642 return false;
8643}
8644
8645// checkPointerTypesForAssignment - This is a very tricky routine (despite
8646// being closely modeled after the C99 spec:-). The odd characteristic of this
8647// routine is it effectively iqnores the qualifiers on the top level pointee.
8648// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8649// FIXME: add a couple examples in this comment.
8650static Sema::AssignConvertType
8651checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8652 assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 8652, __PRETTY_FUNCTION__))
;
8653 assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 8653, __PRETTY_FUNCTION__))
;
8654
8655 // get the "pointed to" type (ignoring qualifiers at the top level)
8656 const Type *lhptee, *rhptee;
8657 Qualifiers lhq, rhq;
8658 std::tie(lhptee, lhq) =
8659 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8660 std::tie(rhptee, rhq) =
8661 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8662
8663 Sema::AssignConvertType ConvTy = Sema::Compatible;
8664
8665 // C99 6.5.16.1p1: This following citation is common to constraints
8666 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8667 // qualifiers of the type *pointed to* by the right;
8668
8669 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8670 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8671 lhq.compatiblyIncludesObjCLifetime(rhq)) {
8672 // Ignore lifetime for further calculation.
8673 lhq.removeObjCLifetime();
8674 rhq.removeObjCLifetime();
8675 }
8676
8677 if (!lhq.compatiblyIncludes(rhq)) {
8678 // Treat address-space mismatches as fatal.
8679 if (!lhq.isAddressSpaceSupersetOf(rhq))
8680 return Sema::IncompatiblePointerDiscardsQualifiers;
8681
8682 // It's okay to add or remove GC or lifetime qualifiers when converting to
8683 // and from void*.
8684 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8685 .compatiblyIncludes(
8686 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8687 && (lhptee->isVoidType() || rhptee->isVoidType()))
8688 ; // keep old
8689
8690 // Treat lifetime mismatches as fatal.
8691 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8692 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8693
8694 // For GCC/MS compatibility, other qualifier mismatches are treated
8695 // as still compatible in C.
8696 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8697 }
8698
8699 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8700 // incomplete type and the other is a pointer to a qualified or unqualified
8701 // version of void...
8702 if (lhptee->isVoidType()) {
8703 if (rhptee->isIncompleteOrObjectType())
8704 return ConvTy;
8705
8706 // As an extension, we allow cast to/from void* to function pointer.
8707 assert(rhptee->isFunctionType())((rhptee->isFunctionType()) ? static_cast<void> (0) :
__assert_fail ("rhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 8707, __PRETTY_FUNCTION__))
;
8708 return Sema::FunctionVoidPointer;
8709 }
8710
8711 if (rhptee->isVoidType()) {
8712 if (lhptee->isIncompleteOrObjectType())
8713 return ConvTy;
8714
8715 // As an extension, we allow cast to/from void* to function pointer.
8716 assert(lhptee->isFunctionType())((lhptee->isFunctionType()) ? static_cast<void> (0) :
__assert_fail ("lhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 8716, __PRETTY_FUNCTION__))
;
8717 return Sema::FunctionVoidPointer;
8718 }
8719
8720 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8721 // unqualified versions of compatible types, ...
8722 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8723 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8724 // Check if the pointee types are compatible ignoring the sign.
8725 // We explicitly check for char so that we catch "char" vs
8726 // "unsigned char" on systems where "char" is unsigned.
8727 if (lhptee->isCharType())
8728 ltrans = S.Context.UnsignedCharTy;
8729 else if (lhptee->hasSignedIntegerRepresentation())
8730 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8731
8732 if (rhptee->isCharType())
8733 rtrans = S.Context.UnsignedCharTy;
8734 else if (rhptee->hasSignedIntegerRepresentation())
8735 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8736
8737 if (ltrans == rtrans) {
8738 // Types are compatible ignoring the sign. Qualifier incompatibility
8739 // takes priority over sign incompatibility because the sign
8740 // warning can be disabled.
8741 if (ConvTy != Sema::Compatible)
8742 return ConvTy;
8743
8744 return Sema::IncompatiblePointerSign;
8745 }
8746
8747 // If we are a multi-level pointer, it's possible that our issue is simply
8748 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8749 // the eventual target type is the same and the pointers have the same
8750 // level of indirection, this must be the issue.
8751 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8752 do {
8753 std::tie(lhptee, lhq) =
8754 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8755 std::tie(rhptee, rhq) =
8756 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8757
8758 // Inconsistent address spaces at this point is invalid, even if the
8759 // address spaces would be compatible.
8760 // FIXME: This doesn't catch address space mismatches for pointers of
8761 // different nesting levels, like:
8762 // __local int *** a;
8763 // int ** b = a;
8764 // It's not clear how to actually determine when such pointers are
8765 // invalidly incompatible.
8766 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8767 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8768
8769 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8770
8771 if (lhptee == rhptee)
8772 return Sema::IncompatibleNestedPointerQualifiers;
8773 }
8774
8775 // General pointer incompatibility takes priority over qualifiers.
8776 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8777 return Sema::IncompatibleFunctionPointer;
8778 return Sema::IncompatiblePointer;
8779 }
8780 if (!S.getLangOpts().CPlusPlus &&
8781 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8782 return Sema::IncompatibleFunctionPointer;
8783 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8784 return Sema::IncompatibleFunctionPointer;
8785 return ConvTy;
8786}
8787
8788/// checkBlockPointerTypesForAssignment - This routine determines whether two
8789/// block pointer types are compatible or whether a block and normal pointer
8790/// are compatible. It is more restrict than comparing two function pointer
8791// types.
8792static Sema::AssignConvertType
8793checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8794 QualType RHSType) {
8795 assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 8795, __PRETTY_FUNCTION__))
;
8796 assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 8796, __PRETTY_FUNCTION__))
;
8797
8798 QualType lhptee, rhptee;
8799
8800 // get the "pointed to" type (ignoring qualifiers at the top level)
8801 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8802 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8803
8804 // In C++, the types have to match exactly.
8805 if (S.getLangOpts().CPlusPlus)
8806 return Sema::IncompatibleBlockPointer;
8807
8808 Sema::AssignConvertType ConvTy = Sema::Compatible;
8809
8810 // For blocks we enforce that qualifiers are identical.
8811 Qualifiers LQuals = lhptee.getLocalQualifiers();
8812 Qualifiers RQuals = rhptee.getLocalQualifiers();
8813 if (S.getLangOpts().OpenCL) {
8814 LQuals.removeAddressSpace();
8815 RQuals.removeAddressSpace();
8816 }
8817 if (LQuals != RQuals)
8818 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8819
8820 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8821 // assignment.
8822 // The current behavior is similar to C++ lambdas. A block might be
8823 // assigned to a variable iff its return type and parameters are compatible
8824 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8825 // an assignment. Presumably it should behave in way that a function pointer
8826 // assignment does in C, so for each parameter and return type:
8827 // * CVR and address space of LHS should be a superset of CVR and address
8828 // space of RHS.
8829 // * unqualified types should be compatible.
8830 if (S.getLangOpts().OpenCL) {
8831 if (!S.Context.typesAreBlockPointerCompatible(
8832 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8833 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8834 return Sema::IncompatibleBlockPointer;
8835 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8836 return Sema::IncompatibleBlockPointer;
8837
8838 return ConvTy;
8839}
8840
8841/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8842/// for assignment compatibility.
8843static Sema::AssignConvertType
8844checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8845 QualType RHSType) {
8846 assert(LHSType.isCanonical() && "LHS was not canonicalized!")((LHSType.isCanonical() && "LHS was not canonicalized!"
) ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 8846, __PRETTY_FUNCTION__))
;
8847 assert(RHSType.isCanonical() && "RHS was not canonicalized!")((RHSType.isCanonical() && "RHS was not canonicalized!"
) ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 8847, __PRETTY_FUNCTION__))
;
8848
8849 if (LHSType->isObjCBuiltinType()) {
8850 // Class is not compatible with ObjC object pointers.
8851 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8852 !RHSType->isObjCQualifiedClassType())
8853 return Sema::IncompatiblePointer;
8854 return Sema::Compatible;
8855 }
8856 if (RHSType->isObjCBuiltinType()) {
8857 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8858 !LHSType->isObjCQualifiedClassType())
8859 return Sema::IncompatiblePointer;
8860 return Sema::Compatible;
8861 }
8862 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8863 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8864
8865 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8866 // make an exception for id<P>
8867 !LHSType->isObjCQualifiedIdType())
8868 return Sema::CompatiblePointerDiscardsQualifiers;
8869
8870 if (S.Context.typesAreCompatible(LHSType, RHSType))
8871 return Sema::Compatible;
8872 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8873 return Sema::IncompatibleObjCQualifiedId;
8874 return Sema::IncompatiblePointer;
8875}
8876
8877Sema::AssignConvertType
8878Sema::CheckAssignmentConstraints(SourceLocation Loc,
8879 QualType LHSType, QualType RHSType) {
8880 // Fake up an opaque expression. We don't actually care about what
8881 // cast operations are required, so if CheckAssignmentConstraints
8882 // adds casts to this they'll be wasted, but fortunately that doesn't
8883 // usually happen on valid code.
8884 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8885 ExprResult RHSPtr = &RHSExpr;
8886 CastKind K;
8887
8888 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8889}
8890
8891/// This helper function returns true if QT is a vector type that has element
8892/// type ElementType.
8893static bool isVector(QualType QT, QualType ElementType) {
8894 if (const VectorType *VT = QT->getAs<VectorType>())
8895 return VT->getElementType().getCanonicalType() == ElementType;
8896 return false;
8897}
8898
8899/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8900/// has code to accommodate several GCC extensions when type checking
8901/// pointers. Here are some objectionable examples that GCC considers warnings:
8902///
8903/// int a, *pint;
8904/// short *pshort;
8905/// struct foo *pfoo;
8906///
8907/// pint = pshort; // warning: assignment from incompatible pointer type
8908/// a = pint; // warning: assignment makes integer from pointer without a cast
8909/// pint = a; // warning: assignment makes pointer from integer without a cast
8910/// pint = pfoo; // warning: assignment from incompatible pointer type
8911///
8912/// As a result, the code for dealing with pointers is more complex than the
8913/// C99 spec dictates.
8914///
8915/// Sets 'Kind' for any result kind except Incompatible.
8916Sema::AssignConvertType
8917Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8918 CastKind &Kind, bool ConvertRHS) {
8919 QualType RHSType = RHS.get()->getType();
8920 QualType OrigLHSType = LHSType;
8921
8922 // Get canonical types. We're not formatting these types, just comparing
8923 // them.
8924 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8925 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8926
8927 // Common case: no conversion required.
8928 if (LHSType == RHSType) {
1
Calling 'operator=='
7
Returning from 'operator=='
8
Taking false branch
8929 Kind = CK_NoOp;
8930 return Compatible;
8931 }
8932
8933 // If we have an atomic type, try a non-atomic assignment, then just add an
8934 // atomic qualification step.
8935 if (const AtomicType *AtomicTy
13.1
'AtomicTy' is null
13.1
'AtomicTy' is null
13.1
'AtomicTy' is null
13.1
'AtomicTy' is null
= dyn_cast<AtomicType>(LHSType)) {
9
Calling 'dyn_cast<clang::AtomicType, clang::QualType>'
13
Returning from 'dyn_cast<clang::AtomicType, clang::QualType>'
14
Taking false branch
8936 Sema::AssignConvertType result =
8937 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8938 if (result != Compatible)
8939 return result;
8940 if (Kind != CK_NoOp && ConvertRHS)
8941 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8942 Kind = CK_NonAtomicToAtomic;
8943 return Compatible;
8944 }
8945
8946 // If the left-hand side is a reference type, then we are in a
8947 // (rare!) case where we've allowed the use of references in C,
8948 // e.g., as a parameter type in a built-in function. In this case,
8949 // just make sure that the type referenced is compatible with the
8950 // right-hand side type. The caller is responsible for adjusting
8951 // LHSType so that the resulting expression does not have reference
8952 // type.
8953 if (const ReferenceType *LHSTypeRef
15.1
'LHSTypeRef' is null
15.1
'LHSTypeRef' is null
15.1
'LHSTypeRef' is null
15.1
'LHSTypeRef' is null
= LHSType->getAs<ReferenceType>()) {
15
Assuming the object is not a 'ReferenceType'
16
Taking false branch
8954 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8955 Kind = CK_LValueBitCast;
8956 return Compatible;
8957 }
8958 return Incompatible;
8959 }
8960
8961 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8962 // to the same ExtVector type.
8963 if (LHSType->isExtVectorType()) {
17
Calling 'Type::isExtVectorType'
20
Returning from 'Type::isExtVectorType'
21
Taking false branch
8964 if (RHSType->isExtVectorType())
8965 return Incompatible;
8966 if (RHSType->isArithmeticType()) {
8967 // CK_VectorSplat does T -> vector T, so first cast to the element type.
8968 if (ConvertRHS)
8969 RHS = prepareVectorSplat(LHSType, RHS.get());
8970 Kind = CK_VectorSplat;
8971 return Compatible;
8972 }
8973 }
8974
8975 // Conversions to or from vector type.
8976 if (LHSType->isVectorType() || RHSType->isVectorType()) {
22
Calling 'Type::isVectorType'
25
Returning from 'Type::isVectorType'
26
Calling 'Type::isVectorType'
29
Returning from 'Type::isVectorType'
30
Taking false branch
8977 if (LHSType->isVectorType() && RHSType->isVectorType()) {
8978 // Allow assignments of an AltiVec vector type to an equivalent GCC
8979 // vector type and vice versa
8980 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8981 Kind = CK_BitCast;
8982 return Compatible;
8983 }
8984
8985 // If we are allowing lax vector conversions, and LHS and RHS are both
8986 // vectors, the total size only needs to be the same. This is a bitcast;
8987 // no bits are changed but the result type is different.
8988 if (isLaxVectorConversion(RHSType, LHSType)) {
8989 Kind = CK_BitCast;
8990 return IncompatibleVectors;
8991 }
8992 }
8993
8994 // When the RHS comes from another lax conversion (e.g. binops between
8995 // scalars and vectors) the result is canonicalized as a vector. When the
8996 // LHS is also a vector, the lax is allowed by the condition above. Handle
8997 // the case where LHS is a scalar.
8998 if (LHSType->isScalarType()) {
8999 const VectorType *VecType = RHSType->getAs<VectorType>();
9000 if (VecType && VecType->getNumElements() == 1 &&
9001 isLaxVectorConversion(RHSType, LHSType)) {
9002 ExprResult *VecExpr = &RHS;
9003 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9004 Kind = CK_BitCast;
9005 return Compatible;
9006 }
9007 }
9008
9009 return Incompatible;
9010 }
9011
9012 // Diagnose attempts to convert between __float128 and long double where
9013 // such conversions currently can't be handled.
9014 if (unsupportedTypeConversion(*this, LHSType, RHSType))
31
Calling 'unsupportedTypeConversion'
46
Returning from 'unsupportedTypeConversion'
47
Taking false branch
9015 return Incompatible;
9016
9017 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9018 // discards the imaginary part.
9019 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
48
Assuming field 'CPlusPlus' is 0
9020 !LHSType->getAs<ComplexType>())
9021 return Incompatible;
9022
9023 // Arithmetic conversions.
9024 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
49
Assuming the condition is false
9025 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9026 if (ConvertRHS)
9027 Kind = PrepareScalarCast(RHS, LHSType);
9028 return Compatible;
9029 }
9030
9031 // Conversions to normal pointers.
9032 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
50
Calling 'dyn_cast<clang::PointerType, clang::QualType>'
59
Returning from 'dyn_cast<clang::PointerType, clang::QualType>'
60
Assuming 'LHSPointer' is non-null
61
Taking true branch
9033 // U* -> T*
9034 if (isa<PointerType>(RHSType)) {
62
Assuming 'RHSType' is not a 'PointerType'
63
Taking false branch
9035 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9036 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9037 if (AddrSpaceL != AddrSpaceR)
9038 Kind = CK_AddressSpaceConversion;
9039 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9040 Kind = CK_NoOp;
9041 else
9042 Kind = CK_BitCast;
9043 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9044 }
9045
9046 // int -> T*
9047 if (RHSType->isIntegerType()) {
64
Calling 'Type::isIntegerType'
82
Returning from 'Type::isIntegerType'
83
Taking false branch
9048 Kind = CK_IntegralToPointer; // FIXME: null?
9049 return IntToPointer;
9050 }
9051
9052 // C pointers are not compatible with ObjC object pointers,
9053 // with two exceptions:
9054 if (isa<ObjCObjectPointerType>(RHSType)) {
84
Assuming 'RHSType' is not a 'ObjCObjectPointerType'
85
Taking false branch
9055 // - conversions to void*
9056 if (LHSPointer->getPointeeType()->isVoidType()) {
9057 Kind = CK_BitCast;
9058 return Compatible;
9059 }
9060
9061 // - conversions from 'Class' to the redefinition type
9062 if (RHSType->isObjCClassType() &&
9063 Context.hasSameType(LHSType,
9064 Context.getObjCClassRedefinitionType())) {
9065 Kind = CK_BitCast;
9066 return Compatible;
9067 }
9068
9069 Kind = CK_BitCast;
9070 return IncompatiblePointer;
9071 }
9072
9073 // U^ -> void*
9074 if (RHSType->getAs<BlockPointerType>()) {
86
Assuming the object is a 'BlockPointerType'
87
Assuming the condition is true
88
Taking true branch
9075 if (LHSPointer->getPointeeType()->isVoidType()) {
89
Calling 'Type::isVoidType'
97
Returning from 'Type::isVoidType'
98
Taking true branch
9076 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9077 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
99
Assuming the object is not a 'BlockPointerType'
100
Called C++ object pointer is null
9078 ->getPointeeType()
9079 .getAddressSpace();
9080 Kind =
9081 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9082 return Compatible;
9083 }
9084 }
9085
9086 return Incompatible;
9087 }
9088
9089 // Conversions to block pointers.
9090 if (isa<BlockPointerType>(LHSType)) {
9091 // U^ -> T^
9092 if (RHSType->isBlockPointerType()) {
9093 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9094 ->getPointeeType()
9095 .getAddressSpace();
9096 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9097 ->getPointeeType()
9098 .getAddressSpace();
9099 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9100 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9101 }
9102
9103 // int or null -> T^
9104 if (RHSType->isIntegerType()) {
9105 Kind = CK_IntegralToPointer; // FIXME: null
9106 return IntToBlockPointer;
9107 }
9108
9109 // id -> T^
9110 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9111 Kind = CK_AnyPointerToBlockPointerCast;
9112 return Compatible;
9113 }
9114
9115 // void* -> T^
9116 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9117 if (RHSPT->getPointeeType()->isVoidType()) {
9118 Kind = CK_AnyPointerToBlockPointerCast;
9119 return Compatible;
9120 }
9121
9122 return Incompatible;
9123 }
9124
9125 // Conversions to Objective-C pointers.
9126 if (isa<ObjCObjectPointerType>(LHSType)) {
9127 // A* -> B*
9128 if (RHSType->isObjCObjectPointerType()) {
9129 Kind = CK_BitCast;
9130 Sema::AssignConvertType result =
9131 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9132 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9133 result == Compatible &&
9134 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9135 result = IncompatibleObjCWeakRef;
9136 return result;
9137 }
9138
9139 // int or null -> A*
9140 if (RHSType->isIntegerType()) {
9141 Kind = CK_IntegralToPointer; // FIXME: null
9142 return IntToPointer;
9143 }
9144
9145 // In general, C pointers are not compatible with ObjC object pointers,
9146 // with two exceptions:
9147 if (isa<PointerType>(RHSType)) {
9148 Kind = CK_CPointerToObjCPointerCast;
9149
9150 // - conversions from 'void*'
9151 if (RHSType->isVoidPointerType()) {
9152 return Compatible;
9153 }
9154
9155 // - conversions to 'Class' from its redefinition type
9156 if (LHSType->isObjCClassType() &&
9157 Context.hasSameType(RHSType,
9158 Context.getObjCClassRedefinitionType())) {
9159 return Compatible;
9160 }
9161
9162 return IncompatiblePointer;
9163 }
9164
9165 // Only under strict condition T^ is compatible with an Objective-C pointer.
9166 if (RHSType->isBlockPointerType() &&
9167 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9168 if (ConvertRHS)
9169 maybeExtendBlockObject(RHS);
9170 Kind = CK_BlockPointerToObjCPointerCast;
9171 return Compatible;
9172 }
9173
9174 return Incompatible;
9175 }
9176
9177 // Conversions from pointers that are not covered by the above.
9178 if (isa<PointerType>(RHSType)) {
9179 // T* -> _Bool
9180 if (LHSType == Context.BoolTy) {
9181 Kind = CK_PointerToBoolean;
9182 return Compatible;
9183 }
9184
9185 // T* -> int
9186 if (LHSType->isIntegerType()) {
9187 Kind = CK_PointerToIntegral;
9188 return PointerToInt;
9189 }
9190
9191 return Incompatible;
9192 }
9193
9194 // Conversions from Objective-C pointers that are not covered by the above.
9195 if (isa<ObjCObjectPointerType>(RHSType)) {
9196 // T* -> _Bool
9197 if (LHSType == Context.BoolTy) {
9198 Kind = CK_PointerToBoolean;
9199 return Compatible;
9200 }
9201
9202 // T* -> int
9203 if (LHSType->isIntegerType()) {
9204 Kind = CK_PointerToIntegral;
9205 return PointerToInt;
9206 }
9207
9208 return Incompatible;
9209 }
9210
9211 // struct A -> struct B
9212 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9213 if (Context.typesAreCompatible(LHSType, RHSType)) {
9214 Kind = CK_NoOp;
9215 return Compatible;
9216 }
9217 }
9218
9219 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9220 Kind = CK_IntToOCLSampler;
9221 return Compatible;
9222 }
9223
9224 return Incompatible;
9225}
9226
9227/// Constructs a transparent union from an expression that is
9228/// used to initialize the transparent union.
9229static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9230 ExprResult &EResult, QualType UnionType,
9231 FieldDecl *Field) {
9232 // Build an initializer list that designates the appropriate member
9233 // of the transparent union.
9234 Expr *E = EResult.get();
9235 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9236 E, SourceLocation());
9237 Initializer->setType(UnionType);
9238 Initializer->setInitializedFieldInUnion(Field);
9239
9240 // Build a compound literal constructing a value of the transparent
9241 // union type from this initializer list.
9242 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9243 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9244 VK_RValue, Initializer, false);
9245}
9246
9247Sema::AssignConvertType
9248Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9249 ExprResult &RHS) {
9250 QualType RHSType = RHS.get()->getType();
9251
9252 // If the ArgType is a Union type, we want to handle a potential
9253 // transparent_union GCC extension.
9254 const RecordType *UT = ArgType->getAsUnionType();
9255 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9256 return Incompatible;
9257
9258 // The field to initialize within the transparent union.
9259 RecordDecl *UD = UT->getDecl();
9260 FieldDecl *InitField = nullptr;
9261 // It's compatible if the expression matches any of the fields.
9262 for (auto *it : UD->fields()) {
9263 if (it->getType()->isPointerType()) {
9264 // If the transparent union contains a pointer type, we allow:
9265 // 1) void pointer
9266 // 2) null pointer constant
9267 if (RHSType->isPointerType())
9268 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9269 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9270 InitField = it;
9271 break;
9272 }
9273
9274 if (RHS.get()->isNullPointerConstant(Context,
9275 Expr::NPC_ValueDependentIsNull)) {
9276 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9277 CK_NullToPointer);
9278 InitField = it;
9279 break;
9280 }
9281 }
9282
9283 CastKind Kind;
9284 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9285 == Compatible) {
9286 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9287 InitField = it;
9288 break;
9289 }
9290 }
9291
9292 if (!InitField)
9293 return Incompatible;
9294
9295 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9296 return Compatible;
9297}
9298
9299Sema::AssignConvertType
9300Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9301 bool Diagnose,
9302 bool DiagnoseCFAudited,
9303 bool ConvertRHS) {
9304 // We need to be able to tell the caller whether we diagnosed a problem, if
9305 // they ask us to issue diagnostics.
9306 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"
) ? static_cast<void> (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 9306, __PRETTY_FUNCTION__))
;
9307
9308 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9309 // we can't avoid *all* modifications at the moment, so we need some somewhere
9310 // to put the updated value.
9311 ExprResult LocalRHS = CallerRHS;
9312 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9313
9314 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9315 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9316 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9317 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9318 Diag(RHS.get()->getExprLoc(),
9319 diag::warn_noderef_to_dereferenceable_pointer)
9320 << RHS.get()->getSourceRange();
9321 }
9322 }
9323 }
9324
9325 if (getLangOpts().CPlusPlus) {
9326 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9327 // C++ 5.17p3: If the left operand is not of class type, the
9328 // expression is implicitly converted (C++ 4) to the
9329 // cv-unqualified type of the left operand.
9330 QualType RHSType = RHS.get()->getType();
9331 if (Diagnose) {
9332 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9333 AA_Assigning);
9334 } else {
9335 ImplicitConversionSequence ICS =
9336 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9337 /*SuppressUserConversions=*/false,
9338 AllowedExplicit::None,
9339 /*InOverloadResolution=*/false,
9340 /*CStyle=*/false,
9341 /*AllowObjCWritebackConversion=*/false);
9342 if (ICS.isFailure())
9343 return Incompatible;
9344 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9345 ICS, AA_Assigning);
9346 }
9347 if (RHS.isInvalid())
9348 return Incompatible;
9349 Sema::AssignConvertType result = Compatible;
9350 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9351 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9352 result = IncompatibleObjCWeakRef;
9353 return result;
9354 }
9355
9356 // FIXME: Currently, we fall through and treat C++ classes like C
9357 // structures.
9358 // FIXME: We also fall through for atomics; not sure what should
9359 // happen there, though.
9360 } else if (RHS.get()->getType() == Context.OverloadTy) {
9361 // As a set of extensions to C, we support overloading on functions. These
9362 // functions need to be resolved here.
9363 DeclAccessPair DAP;
9364 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9365 RHS.get(), LHSType, /*Complain=*/false, DAP))
9366 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9367 else
9368 return Incompatible;
9369 }
9370
9371 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9372 // a null pointer constant.
9373 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9374 LHSType->isBlockPointerType()) &&
9375 RHS.get()->isNullPointerConstant(Context,
9376 Expr::NPC_ValueDependentIsNull)) {
9377 if (Diagnose || ConvertRHS) {
9378 CastKind Kind;
9379 CXXCastPath Path;
9380 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9381 /*IgnoreBaseAccess=*/false, Diagnose);
9382 if (ConvertRHS)
9383 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9384 }
9385 return Compatible;
9386 }
9387
9388 // OpenCL queue_t type assignment.
9389 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9390 Context, Expr::NPC_ValueDependentIsNull)) {
9391 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9392 return Compatible;
9393 }
9394
9395 // This check seems unnatural, however it is necessary to ensure the proper
9396 // conversion of functions/arrays. If the conversion were done for all
9397 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9398 // expressions that suppress this implicit conversion (&, sizeof).
9399 //
9400 // Suppress this for references: C++ 8.5.3p5.
9401 if (!LHSType->isReferenceType()) {
9402 // FIXME: We potentially allocate here even if ConvertRHS is false.
9403 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9404 if (RHS.isInvalid())
9405 return Incompatible;
9406 }
9407 CastKind Kind;
9408 Sema::AssignConvertType result =
9409 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9410
9411 // C99 6.5.16.1p2: The value of the right operand is converted to the
9412 // type of the assignment expression.
9413 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9414 // so that we can use references in built-in functions even in C.
9415 // The getNonReferenceType() call makes sure that the resulting expression
9416 // does not have reference type.
9417 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9418 QualType Ty = LHSType.getNonLValueExprType(Context);
9419 Expr *E = RHS.get();
9420
9421 // Check for various Objective-C errors. If we are not reporting
9422 // diagnostics and just checking for errors, e.g., during overload
9423 // resolution, return Incompatible to indicate the failure.
9424 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9425 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9426 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9427 if (!Diagnose)
9428 return Incompatible;
9429 }
9430 if (getLangOpts().ObjC &&
9431 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9432 E->getType(), E, Diagnose) ||
9433 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9434 if (!Diagnose)
9435 return Incompatible;
9436 // Replace the expression with a corrected version and continue so we
9437 // can find further errors.
9438 RHS = E;
9439 return Compatible;
9440 }
9441
9442 if (ConvertRHS)
9443 RHS = ImpCastExprToType(E, Ty, Kind);
9444 }
9445
9446 return result;
9447}
9448
9449namespace {
9450/// The original operand to an operator, prior to the application of the usual
9451/// arithmetic conversions and converting the arguments of a builtin operator
9452/// candidate.
9453struct OriginalOperand {
9454 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9455 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9456 Op = MTE->getSubExpr();
9457 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9458 Op = BTE->getSubExpr();
9459 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9460 Orig = ICE->getSubExprAsWritten();
9461 Conversion = ICE->getConversionFunction();
9462 }
9463 }
9464
9465 QualType getType() const { return Orig->getType(); }
9466
9467 Expr *Orig;
9468 NamedDecl *Conversion;
9469};
9470}
9471
9472QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9473 ExprResult &RHS) {
9474 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9475
9476 Diag(Loc, diag::err_typecheck_invalid_operands)
9477 << OrigLHS.getType() << OrigRHS.getType()
9478 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9479
9480 // If a user-defined conversion was applied to either of the operands prior
9481 // to applying the built-in operator rules, tell the user about it.
9482 if (OrigLHS.Conversion) {
9483 Diag(OrigLHS.Conversion->getLocation(),
9484 diag::note_typecheck_invalid_operands_converted)
9485 << 0 << LHS.get()->getType();
9486 }
9487 if (OrigRHS.Conversion) {
9488 Diag(OrigRHS.Conversion->getLocation(),
9489 diag::note_typecheck_invalid_operands_converted)
9490 << 1 << RHS.get()->getType();
9491 }
9492
9493 return QualType();
9494}
9495
9496// Diagnose cases where a scalar was implicitly converted to a vector and
9497// diagnose the underlying types. Otherwise, diagnose the error
9498// as invalid vector logical operands for non-C++ cases.
9499QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9500 ExprResult &RHS) {
9501 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9502 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9503
9504 bool LHSNatVec = LHSType->isVectorType();
9505 bool RHSNatVec = RHSType->isVectorType();
9506
9507 if (!(LHSNatVec && RHSNatVec)) {
9508 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9509 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9510 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9511 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9512 << Vector->getSourceRange();
9513 return QualType();
9514 }
9515
9516 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9517 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9518 << RHS.get()->getSourceRange();
9519
9520 return QualType();
9521}
9522
9523/// Try to convert a value of non-vector type to a vector type by converting
9524/// the type to the element type of the vector and then performing a splat.
9525/// If the language is OpenCL, we only use conversions that promote scalar
9526/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9527/// for float->int.
9528///
9529/// OpenCL V2.0 6.2.6.p2:
9530/// An error shall occur if any scalar operand type has greater rank
9531/// than the type of the vector element.
9532///
9533/// \param scalar - if non-null, actually perform the conversions
9534/// \return true if the operation fails (but without diagnosing the failure)
9535static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9536 QualType scalarTy,
9537 QualType vectorEltTy,
9538 QualType vectorTy,
9539 unsigned &DiagID) {
9540 // The conversion to apply to the scalar before splatting it,
9541 // if necessary.
9542 CastKind scalarCast = CK_NoOp;
9543
9544 if (vectorEltTy->isIntegralType(S.Context)) {
9545 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9546 (scalarTy->isIntegerType() &&
9547 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9548 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9549 return true;
9550 }
9551 if (!scalarTy->isIntegralType(S.Context))
9552 return true;
9553 scalarCast = CK_IntegralCast;
9554 } else if (vectorEltTy->isRealFloatingType()) {
9555 if (scalarTy->isRealFloatingType()) {
9556 if (S.getLangOpts().OpenCL &&
9557 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9558 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9559 return true;
9560 }
9561 scalarCast = CK_FloatingCast;
9562 }
9563 else if (scalarTy->isIntegralType(S.Context))
9564 scalarCast = CK_IntegralToFloating;
9565 else
9566 return true;
9567 } else {
9568 return true;
9569 }
9570
9571 // Adjust scalar if desired.
9572 if (scalar) {
9573 if (scalarCast != CK_NoOp)
9574 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9575 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9576 }
9577 return false;
9578}
9579
9580/// Convert vector E to a vector with the same number of elements but different
9581/// element type.
9582static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9583 const auto *VecTy = E->getType()->getAs<VectorType>();
9584 assert(VecTy && "Expression E must be a vector")((VecTy && "Expression E must be a vector") ? static_cast
<void> (0) : __assert_fail ("VecTy && \"Expression E must be a vector\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 9584, __PRETTY_FUNCTION__))
;
9585 QualType NewVecTy = S.Context.getVectorType(ElementType,
9586 VecTy->getNumElements(),
9587 VecTy->getVectorKind());
9588
9589 // Look through the implicit cast. Return the subexpression if its type is
9590 // NewVecTy.
9591 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9592 if (ICE->getSubExpr()->getType() == NewVecTy)
9593 return ICE->getSubExpr();
9594
9595 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9596 return S.ImpCastExprToType(E, NewVecTy, Cast);
9597}
9598
9599/// Test if a (constant) integer Int can be casted to another integer type
9600/// IntTy without losing precision.
9601static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9602 QualType OtherIntTy) {
9603 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9604
9605 // Reject cases where the value of the Int is unknown as that would
9606 // possibly cause truncation, but accept cases where the scalar can be
9607 // demoted without loss of precision.
9608 Expr::EvalResult EVResult;
9609 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9610 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9611 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9612 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9613
9614 if (CstInt) {
9615 // If the scalar is constant and is of a higher order and has more active
9616 // bits that the vector element type, reject it.
9617 llvm::APSInt Result = EVResult.Val.getInt();
9618 unsigned NumBits = IntSigned
9619 ? (Result.isNegative() ? Result.getMinSignedBits()
9620 : Result.getActiveBits())
9621 : Result.getActiveBits();
9622 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9623 return true;
9624
9625 // If the signedness of the scalar type and the vector element type
9626 // differs and the number of bits is greater than that of the vector
9627 // element reject it.
9628 return (IntSigned != OtherIntSigned &&
9629 NumBits > S.Context.getIntWidth(OtherIntTy));
9630 }
9631
9632 // Reject cases where the value of the scalar is not constant and it's
9633 // order is greater than that of the vector element type.
9634 return (Order < 0);
9635}
9636
9637/// Test if a (constant) integer Int can be casted to floating point type
9638/// FloatTy without losing precision.
9639static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9640 QualType FloatTy) {
9641 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9642
9643 // Determine if the integer constant can be expressed as a floating point
9644 // number of the appropriate type.
9645 Expr::EvalResult EVResult;
9646 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9647
9648 uint64_t Bits = 0;
9649 if (CstInt) {
9650 // Reject constants that would be truncated if they were converted to
9651 // the floating point type. Test by simple to/from conversion.
9652 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9653 // could be avoided if there was a convertFromAPInt method
9654 // which could signal back if implicit truncation occurred.
9655 llvm::APSInt Result = EVResult.Val.getInt();
9656 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9657 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9658 llvm::APFloat::rmTowardZero);
9659 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9660 !IntTy->hasSignedIntegerRepresentation());
9661 bool Ignored = false;
9662 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9663 &Ignored);
9664 if (Result != ConvertBack)
9665 return true;
9666 } else {
9667 // Reject types that cannot be fully encoded into the mantissa of
9668 // the float.
9669 Bits = S.Context.getTypeSize(IntTy);
9670 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9671 S.Context.getFloatTypeSemantics(FloatTy));
9672 if (Bits > FloatPrec)
9673 return true;
9674 }
9675
9676 return false;
9677}
9678
9679/// Attempt to convert and splat Scalar into a vector whose types matches
9680/// Vector following GCC conversion rules. The rule is that implicit
9681/// conversion can occur when Scalar can be casted to match Vector's element
9682/// type without causing truncation of Scalar.
9683static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9684 ExprResult *Vector) {
9685 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9686 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9687 const VectorType *VT = VectorTy->getAs<VectorType>();
9688
9689 assert(!isa<ExtVectorType>(VT) &&((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 9690, __PRETTY_FUNCTION__))
9690 "ExtVectorTypes should not be handled here!")((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 9690, __PRETTY_FUNCTION__))
;
9691
9692 QualType VectorEltTy = VT->getElementType();
9693
9694 // Reject cases where the vector element type or the scalar element type are
9695 // not integral or floating point types.
9696 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9697 return true;
9698
9699 // The conversion to apply to the scalar before splatting it,
9700 // if necessary.
9701 CastKind ScalarCast = CK_NoOp;
9702
9703 // Accept cases where the vector elements are integers and the scalar is
9704 // an integer.
9705 // FIXME: Notionally if the scalar was a floating point value with a precise
9706 // integral representation, we could cast it to an appropriate integer
9707 // type and then perform the rest of the checks here. GCC will perform
9708 // this conversion in some cases as determined by the input language.
9709 // We should accept it on a language independent basis.
9710 if (VectorEltTy->isIntegralType(S.Context) &&
9711 ScalarTy->isIntegralType(S.Context) &&
9712 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9713
9714 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9715 return true;
9716
9717 ScalarCast = CK_IntegralCast;
9718 } else if (VectorEltTy->isIntegralType(S.Context) &&
9719 ScalarTy->isRealFloatingType()) {
9720 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9721 ScalarCast = CK_FloatingToIntegral;
9722 else
9723 return true;
9724 } else if (VectorEltTy->isRealFloatingType()) {
9725 if (ScalarTy->isRealFloatingType()) {
9726
9727 // Reject cases where the scalar type is not a constant and has a higher
9728 // Order than the vector element type.
9729 llvm::APFloat Result(0.0);
9730
9731 // Determine whether this is a constant scalar. In the event that the
9732 // value is dependent (and thus cannot be evaluated by the constant
9733 // evaluator), skip the evaluation. This will then diagnose once the
9734 // expression is instantiated.
9735 bool CstScalar = Scalar->get()->isValueDependent() ||
9736 Scalar->get()->EvaluateAsFloat(Result, S.Context);
9737 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9738 if (!CstScalar && Order < 0)
9739 return true;
9740
9741 // If the scalar cannot be safely casted to the vector element type,
9742 // reject it.
9743 if (CstScalar) {
9744 bool Truncated = false;
9745 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9746 llvm::APFloat::rmNearestTiesToEven, &Truncated);
9747 if (Truncated)
9748 return true;
9749 }
9750
9751 ScalarCast = CK_FloatingCast;
9752 } else if (ScalarTy->isIntegralType(S.Context)) {
9753 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9754 return true;
9755
9756 ScalarCast = CK_IntegralToFloating;
9757 } else
9758 return true;
9759 } else if (ScalarTy->isEnumeralType())
9760 return true;
9761
9762 // Adjust scalar if desired.
9763 if (Scalar) {
9764 if (ScalarCast != CK_NoOp)
9765 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9766 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9767 }
9768 return false;
9769}
9770
9771QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9772 SourceLocation Loc, bool IsCompAssign,
9773 bool AllowBothBool,
9774 bool AllowBoolConversions) {
9775 if (!IsCompAssign) {
9776 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9777 if (LHS.isInvalid())
9778 return QualType();
9779 }
9780 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9781 if (RHS.isInvalid())
9782 return QualType();
9783
9784 // For conversion purposes, we ignore any qualifiers.
9785 // For example, "const float" and "float" are equivalent.
9786 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9787 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9788
9789 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9790 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9791 assert(LHSVecType || RHSVecType)((LHSVecType || RHSVecType) ? static_cast<void> (0) : __assert_fail
("LHSVecType || RHSVecType", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 9791, __PRETTY_FUNCTION__))
;
9792
9793 // AltiVec-style "vector bool op vector bool" combinations are allowed
9794 // for some operators but not others.
9795 if (!AllowBothBool &&
9796 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9797 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9798 return InvalidOperands(Loc, LHS, RHS);
9799
9800 // If the vector types are identical, return.
9801 if (Context.hasSameType(LHSType, RHSType))
9802 return LHSType;
9803
9804 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9805 if (LHSVecType && RHSVecType &&
9806 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9807 if (isa<ExtVectorType>(LHSVecType)) {
9808 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9809 return LHSType;
9810 }
9811
9812 if (!IsCompAssign)
9813 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9814 return RHSType;
9815 }
9816
9817 // AllowBoolConversions says that bool and non-bool AltiVec vectors
9818 // can be mixed, with the result being the non-bool type. The non-bool
9819 // operand must have integer element type.
9820 if (AllowBoolConversions && LHSVecType && RHSVecType &&
9821 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9822 (Context.getTypeSize(LHSVecType->getElementType()) ==
9823 Context.getTypeSize(RHSVecType->getElementType()))) {
9824 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9825 LHSVecType->getElementType()->isIntegerType() &&
9826 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9827 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9828 return LHSType;
9829 }
9830 if (!IsCompAssign &&
9831 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9832 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9833 RHSVecType->getElementType()->isIntegerType()) {
9834 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9835 return RHSType;
9836 }
9837 }
9838
9839 // If there's a vector type and a scalar, try to convert the scalar to
9840 // the vector element type and splat.
9841 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9842 if (!RHSVecType) {
9843 if (isa<ExtVectorType>(LHSVecType)) {
9844 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9845 LHSVecType->getElementType(), LHSType,
9846 DiagID))
9847 return LHSType;
9848 } else {
9849 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9850 return LHSType;
9851 }
9852 }
9853 if (!LHSVecType) {
9854 if (isa<ExtVectorType>(RHSVecType)) {
9855 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9856 LHSType, RHSVecType->getElementType(),
9857 RHSType, DiagID))
9858 return RHSType;
9859 } else {
9860 if (LHS.get()->getValueKind() == VK_LValue ||
9861 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9862 return RHSType;
9863 }
9864 }
9865
9866 // FIXME: The code below also handles conversion between vectors and
9867 // non-scalars, we should break this down into fine grained specific checks
9868 // and emit proper diagnostics.
9869 QualType VecType = LHSVecType ? LHSType : RHSType;
9870 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9871 QualType OtherType = LHSVecType ? RHSType : LHSType;
9872 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9873 if (isLaxVectorConversion(OtherType, VecType)) {
9874 // If we're allowing lax vector conversions, only the total (data) size
9875 // needs to be the same. For non compound assignment, if one of the types is
9876 // scalar, the result is always the vector type.
9877 if (!IsCompAssign) {
9878 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9879 return VecType;
9880 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9881 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9882 // type. Note that this is already done by non-compound assignments in
9883 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9884 // <1 x T> -> T. The result is also a vector type.
9885 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9886 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9887 ExprResult *RHSExpr = &RHS;
9888 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9889 return VecType;
9890 }
9891 }
9892
9893 // Okay, the expression is invalid.
9894
9895 // If there's a non-vector, non-real operand, diagnose that.
9896 if ((!RHSVecType && !RHSType->isRealType()) ||
9897 (!LHSVecType && !LHSType->isRealType())) {
9898 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9899 << LHSType << RHSType
9900 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9901 return QualType();
9902 }
9903
9904 // OpenCL V1.1 6.2.6.p1:
9905 // If the operands are of more than one vector type, then an error shall
9906 // occur. Implicit conversions between vector types are not permitted, per
9907 // section 6.2.1.
9908 if (getLangOpts().OpenCL &&
9909 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9910 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9911 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9912 << RHSType;
9913 return QualType();
9914 }
9915
9916
9917 // If there is a vector type that is not a ExtVector and a scalar, we reach
9918 // this point if scalar could not be converted to the vector's element type
9919 // without truncation.
9920 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9921 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9922 QualType Scalar = LHSVecType ? RHSType : LHSType;
9923 QualType Vector = LHSVecType ? LHSType : RHSType;
9924 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9925 Diag(Loc,
9926 diag::err_typecheck_vector_not_convertable_implict_truncation)
9927 << ScalarOrVector << Scalar << Vector;
9928
9929 return QualType();
9930 }
9931
9932 // Otherwise, use the generic diagnostic.
9933 Diag(Loc, DiagID)
9934 << LHSType << RHSType
9935 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9936 return QualType();
9937}
9938
9939// checkArithmeticNull - Detect when a NULL constant is used improperly in an
9940// expression. These are mainly cases where the null pointer is used as an
9941// integer instead of a pointer.
9942static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9943 SourceLocation Loc, bool IsCompare) {
9944 // The canonical way to check for a GNU null is with isNullPointerConstant,
9945 // but we use a bit of a hack here for speed; this is a relatively
9946 // hot path, and isNullPointerConstant is slow.
9947 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9948 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9949
9950 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9951
9952 // Avoid analyzing cases where the result will either be invalid (and
9953 // diagnosed as such) or entirely valid and not something to warn about.
9954 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9955 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9956 return;
9957
9958 // Comparison operations would not make sense with a null pointer no matter
9959 // what the other expression is.
9960 if (!IsCompare) {
9961 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9962 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9963 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9964 return;
9965 }
9966
9967 // The rest of the operations only make sense with a null pointer
9968 // if the other expression is a pointer.
9969 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9970 NonNullType->canDecayToPointerType())
9971 return;
9972
9973 S.Diag(Loc, diag::warn_null_in_comparison_operation)
9974 << LHSNull /* LHS is NULL */ << NonNullType
9975 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9976}
9977
9978static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9979 SourceLocation Loc) {
9980 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9981 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9982 if (!LUE || !RUE)
9983 return;
9984 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9985 RUE->getKind() != UETT_SizeOf)
9986 return;
9987
9988 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9989 QualType LHSTy = LHSArg->getType();
9990 QualType RHSTy;
9991
9992 if (RUE->isArgumentType())
9993 RHSTy = RUE->getArgumentType();
9994 else
9995 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9996
9997 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9998 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9999 return;
10000
10001 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10002 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10003 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10004 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10005 << LHSArgDecl;
10006 }
10007 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10008 QualType ArrayElemTy = ArrayTy->getElementType();
10009 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10010 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10011 ArrayElemTy->isCharType() ||
10012 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10013 return;
10014 S.Diag(Loc, diag::warn_division_sizeof_array)
10015 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10016 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10017 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10018 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10019 << LHSArgDecl;
10020 }
10021
10022 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10023 }
10024}
10025
10026static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10027 ExprResult &RHS,
10028 SourceLocation Loc, bool IsDiv) {
10029 // Check for division/remainder by zero.
10030 Expr::EvalResult RHSValue;
10031 if (!RHS.get()->isValueDependent() &&
10032 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10033 RHSValue.Val.getInt() == 0)
10034 S.DiagRuntimeBehavior(Loc, RHS.get(),
10035 S.PDiag(diag::warn_remainder_division_by_zero)
10036 << IsDiv << RHS.get()->getSourceRange());
10037}
10038
10039QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10040 SourceLocation Loc,
10041 bool IsCompAssign, bool IsDiv) {
10042 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10043
10044 if (LHS.get()->getType()->isVectorType() ||
10045 RHS.get()->getType()->isVectorType())
10046 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10047 /*AllowBothBool*/getLangOpts().AltiVec,
10048 /*AllowBoolConversions*/false);
10049 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10050 RHS.get()->getType()->isConstantMatrixType()))
10051 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10052
10053 QualType compType = UsualArithmeticConversions(
10054 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10055 if (LHS.isInvalid() || RHS.isInvalid())
10056 return QualType();
10057
10058
10059 if (compType.isNull() || !compType->isArithmeticType())
10060 return InvalidOperands(Loc, LHS, RHS);
10061 if (IsDiv) {
10062 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10063 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10064 }
10065 return compType;
10066}
10067
10068QualType Sema::CheckRemainderOperands(
10069 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10070 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10071
10072 if (LHS.get()->getType()->isVectorType() ||
10073 RHS.get()->getType()->isVectorType()) {
10074 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10075 RHS.get()->getType()->hasIntegerRepresentation())
10076 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10077 /*AllowBothBool*/getLangOpts().AltiVec,
10078 /*AllowBoolConversions*/false);
10079 return InvalidOperands(Loc, LHS, RHS);
10080 }
10081
10082 QualType compType = UsualArithmeticConversions(
10083 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10084 if (LHS.isInvalid() || RHS.isInvalid())
10085 return QualType();
10086
10087 if (compType.isNull() || !compType->isIntegerType())
10088 return InvalidOperands(Loc, LHS, RHS);
10089 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10090 return compType;
10091}
10092
10093/// Diagnose invalid arithmetic on two void pointers.
10094static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10095 Expr *LHSExpr, Expr *RHSExpr) {
10096 S.Diag(Loc, S.getLangOpts().CPlusPlus
10097 ? diag::err_typecheck_pointer_arith_void_type
10098 : diag::ext_gnu_void_ptr)
10099 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10100 << RHSExpr->getSourceRange();
10101}
10102
10103/// Diagnose invalid arithmetic on a void pointer.
10104static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10105 Expr *Pointer) {
10106 S.Diag(Loc, S.getLangOpts().CPlusPlus
10107 ? diag::err_typecheck_pointer_arith_void_type
10108 : diag::ext_gnu_void_ptr)
10109 << 0 /* one pointer */ << Pointer->getSourceRange();
10110}
10111
10112/// Diagnose invalid arithmetic on a null pointer.
10113///
10114/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10115/// idiom, which we recognize as a GNU extension.
10116///
10117static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10118 Expr *Pointer, bool IsGNUIdiom) {
10119 if (IsGNUIdiom)
10120 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10121 << Pointer->getSourceRange();
10122 else
10123 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10124 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10125}
10126
10127/// Diagnose invalid arithmetic on two function pointers.
10128static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10129 Expr *LHS, Expr *RHS) {
10130 assert(LHS->getType()->isAnyPointerType())((LHS->getType()->isAnyPointerType()) ? static_cast<
void> (0) : __assert_fail ("LHS->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10130, __PRETTY_FUNCTION__))
;
10131 assert(RHS->getType()->isAnyPointerType())((RHS->getType()->isAnyPointerType()) ? static_cast<
void> (0) : __assert_fail ("RHS->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10131, __PRETTY_FUNCTION__))
;
10132 S.Diag(Loc, S.getLangOpts().CPlusPlus
10133 ? diag::err_typecheck_pointer_arith_function_type
10134 : diag::ext_gnu_ptr_func_arith)
10135 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10136 // We only show the second type if it differs from the first.
10137 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10138 RHS->getType())
10139 << RHS->getType()->getPointeeType()
10140 << LHS->getSourceRange() << RHS->getSourceRange();
10141}
10142
10143/// Diagnose invalid arithmetic on a function pointer.
10144static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10145 Expr *Pointer) {
10146 assert(Pointer->getType()->isAnyPointerType())((Pointer->getType()->isAnyPointerType()) ? static_cast
<void> (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10146, __PRETTY_FUNCTION__))
;
10147 S.Diag(Loc, S.getLangOpts().CPlusPlus
10148 ? diag::err_typecheck_pointer_arith_function_type
10149 : diag::ext_gnu_ptr_func_arith)
10150 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10151 << 0 /* one pointer, so only one type */
10152 << Pointer->getSourceRange();
10153}
10154
10155/// Emit error if Operand is incomplete pointer type
10156///
10157/// \returns True if pointer has incomplete type
10158static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10159 Expr *Operand) {
10160 QualType ResType = Operand->getType();
10161 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10162 ResType = ResAtomicType->getValueType();
10163
10164 assert(ResType->isAnyPointerType() && !ResType->isDependentType())((ResType->isAnyPointerType() && !ResType->isDependentType
()) ? static_cast<void> (0) : __assert_fail ("ResType->isAnyPointerType() && !ResType->isDependentType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10164, __PRETTY_FUNCTION__))
;
10165 QualType PointeeTy = ResType->getPointeeType();
10166 return S.RequireCompleteSizedType(
10167 Loc, PointeeTy,
10168 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10169 Operand->getSourceRange());
10170}
10171
10172/// Check the validity of an arithmetic pointer operand.
10173///
10174/// If the operand has pointer type, this code will check for pointer types
10175/// which are invalid in arithmetic operations. These will be diagnosed
10176/// appropriately, including whether or not the use is supported as an
10177/// extension.
10178///
10179/// \returns True when the operand is valid to use (even if as an extension).
10180static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10181 Expr *Operand) {
10182 QualType ResType = Operand->getType();
10183 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10184 ResType = ResAtomicType->getValueType();
10185
10186 if (!ResType->isAnyPointerType()) return true;
10187
10188 QualType PointeeTy = ResType->getPointeeType();
10189 if (PointeeTy->isVoidType()) {
10190 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10191 return !S.getLangOpts().CPlusPlus;
10192 }
10193 if (PointeeTy->isFunctionType()) {
10194 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10195 return !S.getLangOpts().CPlusPlus;
10196 }
10197
10198 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10199
10200 return true;
10201}
10202
10203/// Check the validity of a binary arithmetic operation w.r.t. pointer
10204/// operands.
10205///
10206/// This routine will diagnose any invalid arithmetic on pointer operands much
10207/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10208/// for emitting a single diagnostic even for operations where both LHS and RHS
10209/// are (potentially problematic) pointers.
10210///
10211/// \returns True when the operand is valid to use (even if as an extension).
10212static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10213 Expr *LHSExpr, Expr *RHSExpr) {
10214 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10215 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10216 if (!isLHSPointer && !isRHSPointer) return true;
10217
10218 QualType LHSPointeeTy, RHSPointeeTy;
10219 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10220 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10221
10222 // if both are pointers check if operation is valid wrt address spaces
10223 if (isLHSPointer && isRHSPointer) {
10224 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10225 S.Diag(Loc,
10226 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10227 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10228 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10229 return false;
10230 }
10231 }
10232
10233 // Check for arithmetic on pointers to incomplete types.
10234 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10235 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10236 if (isLHSVoidPtr || isRHSVoidPtr) {
10237 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10238 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10239 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10240
10241 return !S.getLangOpts().CPlusPlus;
10242 }
10243
10244 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10245 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10246 if (isLHSFuncPtr || isRHSFuncPtr) {
10247 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10248 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10249 RHSExpr);
10250 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10251
10252 return !S.getLangOpts().CPlusPlus;
10253 }
10254
10255 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10256 return false;
10257 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10258 return false;
10259
10260 return true;
10261}
10262
10263/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10264/// literal.
10265static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10266 Expr *LHSExpr, Expr *RHSExpr) {
10267 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10268 Expr* IndexExpr = RHSExpr;
10269 if (!StrExpr) {
10270 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10271 IndexExpr = LHSExpr;
10272 }
10273
10274 bool IsStringPlusInt = StrExpr &&
10275 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10276 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10277 return;
10278
10279 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10280 Self.Diag(OpLoc, diag::warn_string_plus_int)
10281 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10282
10283 // Only print a fixit for "str" + int, not for int + "str".
10284 if (IndexExpr == RHSExpr) {
10285 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10286 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10287 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10288 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10289 << FixItHint::CreateInsertion(EndLoc, "]");
10290 } else
10291 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10292}
10293
10294/// Emit a warning when adding a char literal to a string.
10295static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10296 Expr *LHSExpr, Expr *RHSExpr) {
10297 const Expr *StringRefExpr = LHSExpr;
10298 const CharacterLiteral *CharExpr =
10299 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10300
10301 if (!CharExpr) {
10302 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10303 StringRefExpr = RHSExpr;
10304 }
10305
10306 if (!CharExpr || !StringRefExpr)
10307 return;
10308
10309 const QualType StringType = StringRefExpr->getType();
10310
10311 // Return if not a PointerType.
10312 if (!StringType->isAnyPointerType())
10313 return;
10314
10315 // Return if not a CharacterType.
10316 if (!StringType->getPointeeType()->isAnyCharacterType())
10317 return;
10318
10319 ASTContext &Ctx = Self.getASTContext();
10320 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10321
10322 const QualType CharType = CharExpr->getType();
10323 if (!CharType->isAnyCharacterType() &&
10324 CharType->isIntegerType() &&
10325 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10326 Self.Diag(OpLoc, diag::warn_string_plus_char)
10327 << DiagRange << Ctx.CharTy;
10328 } else {
10329 Self.Diag(OpLoc, diag::warn_string_plus_char)
10330 << DiagRange << CharExpr->getType();
10331 }
10332
10333 // Only print a fixit for str + char, not for char + str.
10334 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10335 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10336 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10337 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10338 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10339 << FixItHint::CreateInsertion(EndLoc, "]");
10340 } else {
10341 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10342 }
10343}
10344
10345/// Emit error when two pointers are incompatible.
10346static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10347 Expr *LHSExpr, Expr *RHSExpr) {
10348 assert(LHSExpr->getType()->isAnyPointerType())((LHSExpr->getType()->isAnyPointerType()) ? static_cast
<void> (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10348, __PRETTY_FUNCTION__))
;
10349 assert(RHSExpr->getType()->isAnyPointerType())((RHSExpr->getType()->isAnyPointerType()) ? static_cast
<void> (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10349, __PRETTY_FUNCTION__))
;
10350 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10351 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10352 << RHSExpr->getSourceRange();
10353}
10354
10355// C99 6.5.6
10356QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10357 SourceLocation Loc, BinaryOperatorKind Opc,
10358 QualType* CompLHSTy) {
10359 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10360
10361 if (LHS.get()->getType()->isVectorType() ||
10362 RHS.get()->getType()->isVectorType()) {
10363 QualType compType = CheckVectorOperands(
10364 LHS, RHS, Loc, CompLHSTy,
10365 /*AllowBothBool*/getLangOpts().AltiVec,
10366 /*AllowBoolConversions*/getLangOpts().ZVector);
10367 if (CompLHSTy) *CompLHSTy = compType;
10368 return compType;
10369 }
10370
10371 if (LHS.get()->getType()->isConstantMatrixType() ||
10372 RHS.get()->getType()->isConstantMatrixType()) {
10373 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10374 }
10375
10376 QualType compType = UsualArithmeticConversions(
10377 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10378 if (LHS.isInvalid() || RHS.isInvalid())
10379 return QualType();
10380
10381 // Diagnose "string literal" '+' int and string '+' "char literal".
10382 if (Opc == BO_Add) {
10383 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10384 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10385 }
10386
10387 // handle the common case first (both operands are arithmetic).
10388 if (!compType.isNull() && compType->isArithmeticType()) {
10389 if (CompLHSTy) *CompLHSTy = compType;
10390 return compType;
10391 }
10392
10393 // Type-checking. Ultimately the pointer's going to be in PExp;
10394 // note that we bias towards the LHS being the pointer.
10395 Expr *PExp = LHS.get(), *IExp = RHS.get();
10396
10397 bool isObjCPointer;
10398 if (PExp->getType()->isPointerType()) {
10399 isObjCPointer = false;
10400 } else if (PExp->getType()->isObjCObjectPointerType()) {
10401 isObjCPointer = true;
10402 } else {
10403 std::swap(PExp, IExp);
10404 if (PExp->getType()->isPointerType()) {
10405 isObjCPointer = false;
10406 } else if (PExp->getType()->isObjCObjectPointerType()) {
10407 isObjCPointer = true;
10408 } else {
10409 return InvalidOperands(Loc, LHS, RHS);
10410 }
10411 }
10412 assert(PExp->getType()->isAnyPointerType())((PExp->getType()->isAnyPointerType()) ? static_cast<
void> (0) : __assert_fail ("PExp->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10412, __PRETTY_FUNCTION__))
;
10413
10414 if (!IExp->getType()->isIntegerType())
10415 return InvalidOperands(Loc, LHS, RHS);
10416
10417 // Adding to a null pointer results in undefined behavior.
10418 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10419 Context, Expr::NPC_ValueDependentIsNotNull)) {
10420 // In C++ adding zero to a null pointer is defined.
10421 Expr::EvalResult KnownVal;
10422 if (!getLangOpts().CPlusPlus ||
10423 (!IExp->isValueDependent() &&
10424 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10425 KnownVal.Val.getInt() != 0))) {
10426 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10427 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10428 Context, BO_Add, PExp, IExp);
10429 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10430 }
10431 }
10432
10433 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10434 return QualType();
10435
10436 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10437 return QualType();
10438
10439 // Check array bounds for pointer arithemtic
10440 CheckArrayAccess(PExp, IExp);
10441
10442 if (CompLHSTy) {
10443 QualType LHSTy = Context.isPromotableBitField(LHS.get());
10444 if (LHSTy.isNull()) {
10445 LHSTy = LHS.get()->getType();
10446 if (LHSTy->isPromotableIntegerType())
10447 LHSTy = Context.getPromotedIntegerType(LHSTy);
10448 }
10449 *CompLHSTy = LHSTy;
10450 }
10451
10452 return PExp->getType();
10453}
10454
10455// C99 6.5.6
10456QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10457 SourceLocation Loc,
10458 QualType* CompLHSTy) {
10459 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10460
10461 if (LHS.get()->getType()->isVectorType() ||
10462 RHS.get()->getType()->isVectorType()) {
10463 QualType compType = CheckVectorOperands(
10464 LHS, RHS, Loc, CompLHSTy,
10465 /*AllowBothBool*/getLangOpts().AltiVec,
10466 /*AllowBoolConversions*/getLangOpts().ZVector);
10467 if (CompLHSTy) *CompLHSTy = compType;
10468 return compType;
10469 }
10470
10471 if (LHS.get()->getType()->isConstantMatrixType() ||
10472 RHS.get()->getType()->isConstantMatrixType()) {
10473 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10474 }
10475
10476 QualType compType = UsualArithmeticConversions(
10477 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10478 if (LHS.isInvalid() || RHS.isInvalid())
10479 return QualType();
10480
10481 // Enforce type constraints: C99 6.5.6p3.
10482
10483 // Handle the common case first (both operands are arithmetic).
10484 if (!compType.isNull() && compType->isArithmeticType()) {
10485 if (CompLHSTy) *CompLHSTy = compType;
10486 return compType;
10487 }
10488
10489 // Either ptr - int or ptr - ptr.
10490 if (LHS.get()->getType()->isAnyPointerType()) {
10491 QualType lpointee = LHS.get()->getType()->getPointeeType();
10492
10493 // Diagnose bad cases where we step over interface counts.
10494 if (LHS.get()->getType()->isObjCObjectPointerType() &&
10495 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10496 return QualType();
10497
10498 // The result type of a pointer-int computation is the pointer type.
10499 if (RHS.get()->getType()->isIntegerType()) {
10500 // Subtracting from a null pointer should produce a warning.
10501 // The last argument to the diagnose call says this doesn't match the
10502 // GNU int-to-pointer idiom.
10503 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10504 Expr::NPC_ValueDependentIsNotNull)) {
10505 // In C++ adding zero to a null pointer is defined.
10506 Expr::EvalResult KnownVal;
10507 if (!getLangOpts().CPlusPlus ||
10508 (!RHS.get()->isValueDependent() &&
10509 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10510 KnownVal.Val.getInt() != 0))) {
10511 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10512 }
10513 }
10514
10515 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10516 return QualType();
10517
10518 // Check array bounds for pointer arithemtic
10519 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10520 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10521
10522 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10523 return LHS.get()->getType();
10524 }
10525
10526 // Handle pointer-pointer subtractions.
10527 if (const PointerType *RHSPTy
10528 = RHS.get()->getType()->getAs<PointerType>()) {
10529 QualType rpointee = RHSPTy->getPointeeType();
10530
10531 if (getLangOpts().CPlusPlus) {
10532 // Pointee types must be the same: C++ [expr.add]
10533 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10534 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10535 }
10536 } else {
10537 // Pointee types must be compatible C99 6.5.6p3
10538 if (!Context.typesAreCompatible(
10539 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10540 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10541 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10542 return QualType();
10543 }
10544 }
10545
10546 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10547 LHS.get(), RHS.get()))
10548 return QualType();
10549
10550 // FIXME: Add warnings for nullptr - ptr.
10551
10552 // The pointee type may have zero size. As an extension, a structure or
10553 // union may have zero size or an array may have zero length. In this
10554 // case subtraction does not make sense.
10555 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10556 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10557 if (ElementSize.isZero()) {
10558 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10559 << rpointee.getUnqualifiedType()
10560 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10561 }
10562 }
10563
10564 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10565 return Context.getPointerDiffType();
10566 }
10567 }
10568
10569 return InvalidOperands(Loc, LHS, RHS);
10570}
10571
10572static bool isScopedEnumerationType(QualType T) {
10573 if (const EnumType *ET = T->getAs<EnumType>())
10574 return ET->getDecl()->isScoped();
10575 return false;
10576}
10577
10578static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10579 SourceLocation Loc, BinaryOperatorKind Opc,
10580 QualType LHSType) {
10581 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10582 // so skip remaining warnings as we don't want to modify values within Sema.
10583 if (S.getLangOpts().OpenCL)
10584 return;
10585
10586 // Check right/shifter operand
10587 Expr::EvalResult RHSResult;
10588 if (RHS.get()->isValueDependent() ||
10589 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10590 return;
10591 llvm::APSInt Right = RHSResult.Val.getInt();
10592
10593 if (Right.isNegative()) {
10594 S.DiagRuntimeBehavior(Loc, RHS.get(),
10595 S.PDiag(diag::warn_shift_negative)
10596 << RHS.get()->getSourceRange());
10597 return;
10598 }
10599
10600 QualType LHSExprType = LHS.get()->getType();
10601 uint64_t LeftSize = LHSExprType->isExtIntType()
10602 ? S.Context.getIntWidth(LHSExprType)
10603 : S.Context.getTypeSize(LHSExprType);
10604 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10605 if (Right.uge(LeftBits)) {
10606 S.DiagRuntimeBehavior(Loc, RHS.get(),
10607 S.PDiag(diag::warn_shift_gt_typewidth)
10608 << RHS.get()->getSourceRange());
10609 return;
10610 }
10611
10612 if (Opc != BO_Shl)
10613 return;
10614
10615 // When left shifting an ICE which is signed, we can check for overflow which
10616 // according to C++ standards prior to C++2a has undefined behavior
10617 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10618 // more than the maximum value representable in the result type, so never
10619 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10620 // expression is still probably a bug.)
10621 Expr::EvalResult LHSResult;
10622 if (LHS.get()->isValueDependent() ||
10623 LHSType->hasUnsignedIntegerRepresentation() ||
10624 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10625 return;
10626 llvm::APSInt Left = LHSResult.Val.getInt();
10627
10628 // If LHS does not have a signed type and non-negative value
10629 // then, the behavior is undefined before C++2a. Warn about it.
10630 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10631 !S.getLangOpts().CPlusPlus20) {
10632 S.DiagRuntimeBehavior(Loc, LHS.get(),
10633 S.PDiag(diag::warn_shift_lhs_negative)
10634 << LHS.get()->getSourceRange());
10635 return;
10636 }
10637
10638 llvm::APInt ResultBits =
10639 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10640 if (LeftBits.uge(ResultBits))
10641 return;
10642 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10643 Result = Result.shl(Right);
10644
10645 // Print the bit representation of the signed integer as an unsigned
10646 // hexadecimal number.
10647 SmallString<40> HexResult;
10648 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10649
10650 // If we are only missing a sign bit, this is less likely to result in actual
10651 // bugs -- if the result is cast back to an unsigned type, it will have the
10652 // expected value. Thus we place this behind a different warning that can be
10653 // turned off separately if needed.
10654 if (LeftBits == ResultBits - 1) {
10655 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10656 << HexResult << LHSType
10657 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10658 return;
10659 }
10660
10661 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10662 << HexResult.str() << Result.getMinSignedBits() << LHSType
10663 << Left.getBitWidth() << LHS.get()->getSourceRange()
10664 << RHS.get()->getSourceRange();
10665}
10666
10667/// Return the resulting type when a vector is shifted
10668/// by a scalar or vector shift amount.
10669static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10670 SourceLocation Loc, bool IsCompAssign) {
10671 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10672 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10673 !LHS.get()->getType()->isVectorType()) {
10674 S.Diag(Loc, diag::err_shift_rhs_only_vector)
10675 << RHS.get()->getType() << LHS.get()->getType()
10676 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10677 return QualType();
10678 }
10679
10680 if (!IsCompAssign) {
10681 LHS = S.UsualUnaryConversions(LHS.get());
10682 if (LHS.isInvalid()) return QualType();
10683 }
10684
10685 RHS = S.UsualUnaryConversions(RHS.get());
10686 if (RHS.isInvalid()) return QualType();
10687
10688 QualType LHSType = LHS.get()->getType();
10689 // Note that LHS might be a scalar because the routine calls not only in
10690 // OpenCL case.
10691 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10692 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10693
10694 // Note that RHS might not be a vector.
10695 QualType RHSType = RHS.get()->getType();
10696 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10697 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10698
10699 // The operands need to be integers.
10700 if (!LHSEleType->isIntegerType()) {
10701 S.Diag(Loc, diag::err_typecheck_expect_int)
10702 << LHS.get()->getType() << LHS.get()->getSourceRange();
10703 return QualType();
10704 }
10705
10706 if (!RHSEleType->isIntegerType()) {
10707 S.Diag(Loc, diag::err_typecheck_expect_int)
10708 << RHS.get()->getType() << RHS.get()->getSourceRange();
10709 return QualType();
10710 }
10711
10712 if (!LHSVecTy) {
10713 assert(RHSVecTy)((RHSVecTy) ? static_cast<void> (0) : __assert_fail ("RHSVecTy"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10713, __PRETTY_FUNCTION__))
;
10714 if (IsCompAssign)
10715 return RHSType;
10716 if (LHSEleType != RHSEleType) {
10717 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10718 LHSEleType = RHSEleType;
10719 }
10720 QualType VecTy =
10721 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10722 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10723 LHSType = VecTy;
10724 } else if (RHSVecTy) {
10725 // OpenCL v1.1 s6.3.j says that for vector types, the operators
10726 // are applied component-wise. So if RHS is a vector, then ensure
10727 // that the number of elements is the same as LHS...
10728 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10729 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10730 << LHS.get()->getType() << RHS.get()->getType()
10731 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10732 return QualType();
10733 }
10734 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10735 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10736 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10737 if (LHSBT != RHSBT &&
10738 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10739 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10740 << LHS.get()->getType() << RHS.get()->getType()
10741 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10742 }
10743 }
10744 } else {
10745 // ...else expand RHS to match the number of elements in LHS.
10746 QualType VecTy =
10747 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10748 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10749 }
10750
10751 return LHSType;
10752}
10753
10754// C99 6.5.7
10755QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10756 SourceLocation Loc, BinaryOperatorKind Opc,
10757 bool IsCompAssign) {
10758 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10759
10760 // Vector shifts promote their scalar inputs to vector type.
10761 if (LHS.get()->getType()->isVectorType() ||
10762 RHS.get()->getType()->isVectorType()) {
10763 if (LangOpts.ZVector) {
10764 // The shift operators for the z vector extensions work basically
10765 // like general shifts, except that neither the LHS nor the RHS is
10766 // allowed to be a "vector bool".
10767 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10768 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10769 return InvalidOperands(Loc, LHS, RHS);
10770 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10771 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10772 return InvalidOperands(Loc, LHS, RHS);
10773 }
10774 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10775 }
10776
10777 // Shifts don't perform usual arithmetic conversions, they just do integer
10778 // promotions on each operand. C99 6.5.7p3
10779
10780 // For the LHS, do usual unary conversions, but then reset them away
10781 // if this is a compound assignment.
10782 ExprResult OldLHS = LHS;
10783 LHS = UsualUnaryConversions(LHS.get());
10784 if (LHS.isInvalid())
10785 return QualType();
10786 QualType LHSType = LHS.get()->getType();
10787 if (IsCompAssign) LHS = OldLHS;
10788
10789 // The RHS is simpler.
10790 RHS = UsualUnaryConversions(RHS.get());
10791 if (RHS.isInvalid())
10792 return QualType();
10793 QualType RHSType = RHS.get()->getType();
10794
10795 // C99 6.5.7p2: Each of the operands shall have integer type.
10796 if (!LHSType->hasIntegerRepresentation() ||
10797 !RHSType->hasIntegerRepresentation())
10798 return InvalidOperands(Loc, LHS, RHS);
10799
10800 // C++0x: Don't allow scoped enums. FIXME: Use something better than
10801 // hasIntegerRepresentation() above instead of this.
10802 if (isScopedEnumerationType(LHSType) ||
10803 isScopedEnumerationType(RHSType)) {
10804 return InvalidOperands(Loc, LHS, RHS);
10805 }
10806 // Sanity-check shift operands
10807 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10808
10809 // "The type of the result is that of the promoted left operand."
10810 return LHSType;
10811}
10812
10813/// Diagnose bad pointer comparisons.
10814static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10815 ExprResult &LHS, ExprResult &RHS,
10816 bool IsError) {
10817 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10818 : diag::ext_typecheck_comparison_of_distinct_pointers)
10819 << LHS.get()->getType() << RHS.get()->getType()
10820 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10821}
10822
10823/// Returns false if the pointers are converted to a composite type,
10824/// true otherwise.
10825static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10826 ExprResult &LHS, ExprResult &RHS) {
10827 // C++ [expr.rel]p2:
10828 // [...] Pointer conversions (4.10) and qualification
10829 // conversions (4.4) are performed on pointer operands (or on
10830 // a pointer operand and a null pointer constant) to bring
10831 // them to their composite pointer type. [...]
10832 //
10833 // C++ [expr.eq]p1 uses the same notion for (in)equality
10834 // comparisons of pointers.
10835
10836 QualType LHSType = LHS.get()->getType();
10837 QualType RHSType = RHS.get()->getType();
10838 assert(LHSType->isPointerType() || RHSType->isPointerType() ||((LHSType->isPointerType() || RHSType->isPointerType() ||
LHSType->isMemberPointerType() || RHSType->isMemberPointerType
()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10839, __PRETTY_FUNCTION__))
10839 LHSType->isMemberPointerType() || RHSType->isMemberPointerType())((LHSType->isPointerType() || RHSType->isPointerType() ||
LHSType->isMemberPointerType() || RHSType->isMemberPointerType
()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10839, __PRETTY_FUNCTION__))
;
10840
10841 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10842 if (T.isNull()) {
10843 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10844 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10845 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10846 else
10847 S.InvalidOperands(Loc, LHS, RHS);
10848 return true;
10849 }
10850
10851 return false;
10852}
10853
10854static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10855 ExprResult &LHS,
10856 ExprResult &RHS,
10857 bool IsError) {
10858 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10859 : diag::ext_typecheck_comparison_of_fptr_to_void)
10860 << LHS.get()->getType() << RHS.get()->getType()
10861 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10862}
10863
10864static bool isObjCObjectLiteral(ExprResult &E) {
10865 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10866 case Stmt::ObjCArrayLiteralClass:
10867 case Stmt::ObjCDictionaryLiteralClass:
10868 case Stmt::ObjCStringLiteralClass:
10869 case Stmt::ObjCBoxedExprClass:
10870 return true;
10871 default:
10872 // Note that ObjCBoolLiteral is NOT an object literal!
10873 return false;
10874 }
10875}
10876
10877static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10878 const ObjCObjectPointerType *Type =
10879 LHS->getType()->getAs<ObjCObjectPointerType>();
10880
10881 // If this is not actually an Objective-C object, bail out.
10882 if (!Type)
10883 return false;
10884
10885 // Get the LHS object's interface type.
10886 QualType InterfaceType = Type->getPointeeType();
10887
10888 // If the RHS isn't an Objective-C object, bail out.
10889 if (!RHS->getType()->isObjCObjectPointerType())
10890 return false;
10891
10892 // Try to find the -isEqual: method.
10893 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10894 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10895 InterfaceType,
10896 /*IsInstance=*/true);
10897 if (!Method) {
10898 if (Type->isObjCIdType()) {
10899 // For 'id', just check the global pool.
10900 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10901 /*receiverId=*/true);
10902 } else {
10903 // Check protocols.
10904 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10905 /*IsInstance=*/true);
10906 }
10907 }
10908
10909 if (!Method)
10910 return false;
10911
10912 QualType T = Method->parameters()[0]->getType();
10913 if (!T->isObjCObjectPointerType())
10914 return false;
10915
10916 QualType R = Method->getReturnType();
10917 if (!R->isScalarType())
10918 return false;
10919
10920 return true;
10921}
10922
10923Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10924 FromE = FromE->IgnoreParenImpCasts();
10925 switch (FromE->getStmtClass()) {
10926 default:
10927 break;
10928 case Stmt::ObjCStringLiteralClass:
10929 // "string literal"
10930 return LK_String;
10931 case Stmt::ObjCArrayLiteralClass:
10932 // "array literal"
10933 return LK_Array;
10934 case Stmt::ObjCDictionaryLiteralClass:
10935 // "dictionary literal"
10936 return LK_Dictionary;
10937 case Stmt::BlockExprClass:
10938 return LK_Block;
10939 case Stmt::ObjCBoxedExprClass: {
10940 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10941 switch (Inner->getStmtClass()) {
10942 case Stmt::IntegerLiteralClass:
10943 case Stmt::FloatingLiteralClass:
10944 case Stmt::CharacterLiteralClass:
10945 case Stmt::ObjCBoolLiteralExprClass:
10946 case Stmt::CXXBoolLiteralExprClass:
10947 // "numeric literal"
10948 return LK_Numeric;
10949 case Stmt::ImplicitCastExprClass: {
10950 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10951 // Boolean literals can be represented by implicit casts.
10952 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10953 return LK_Numeric;
10954 break;
10955 }
10956 default:
10957 break;
10958 }
10959 return LK_Boxed;
10960 }
10961 }
10962 return LK_None;
10963}
10964
10965static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10966 ExprResult &LHS, ExprResult &RHS,
10967 BinaryOperator::Opcode Opc){
10968 Expr *Literal;
10969 Expr *Other;
10970 if (isObjCObjectLiteral(LHS)) {
10971 Literal = LHS.get();
10972 Other = RHS.get();
10973 } else {
10974 Literal = RHS.get();
10975 Other = LHS.get();
10976 }
10977
10978 // Don't warn on comparisons against nil.
10979 Other = Other->IgnoreParenCasts();
10980 if (Other->isNullPointerConstant(S.getASTContext(),
10981 Expr::NPC_ValueDependentIsNotNull))
10982 return;
10983
10984 // This should be kept in sync with warn_objc_literal_comparison.
10985 // LK_String should always be after the other literals, since it has its own
10986 // warning flag.
10987 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10988 assert(LiteralKind != Sema::LK_Block)((LiteralKind != Sema::LK_Block) ? static_cast<void> (0
) : __assert_fail ("LiteralKind != Sema::LK_Block", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10988, __PRETTY_FUNCTION__))
;
10989 if (LiteralKind == Sema::LK_None) {
10990 llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 10990)
;
10991 }
10992
10993 if (LiteralKind == Sema::LK_String)
10994 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10995 << Literal->getSourceRange();
10996 else
10997 S.Diag(Loc, diag::warn_objc_literal_comparison)
10998 << LiteralKind << Literal->getSourceRange();
10999
11000 if (BinaryOperator::isEqualityOp(Opc) &&
11001 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11002 SourceLocation Start = LHS.get()->getBeginLoc();
11003 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11004 CharSourceRange OpRange =
11005 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11006
11007 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11008 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11009 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11010 << FixItHint::CreateInsertion(End, "]");
11011 }
11012}
11013
11014/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11015static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11016 ExprResult &RHS, SourceLocation Loc,
11017 BinaryOperatorKind Opc) {
11018 // Check that left hand side is !something.
11019 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11020 if (!UO || UO->getOpcode() != UO_LNot) return;
11021
11022 // Only check if the right hand side is non-bool arithmetic type.
11023 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11024
11025 // Make sure that the something in !something is not bool.
11026 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11027 if (SubExpr->isKnownToHaveBooleanValue()) return;
11028
11029 // Emit warning.
11030 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11031 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11032 << Loc << IsBitwiseOp;
11033
11034 // First note suggest !(x < y)
11035 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11036 SourceLocation FirstClose = RHS.get()->getEndLoc();
11037 FirstClose = S.getLocForEndOfToken(FirstClose);
11038 if (FirstClose.isInvalid())
11039 FirstOpen = SourceLocation();
11040 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11041 << IsBitwiseOp
11042 << FixItHint::CreateInsertion(FirstOpen, "(")
11043 << FixItHint::CreateInsertion(FirstClose, ")");
11044
11045 // Second note suggests (!x) < y
11046 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11047 SourceLocation SecondClose = LHS.get()->getEndLoc();
11048 SecondClose = S.getLocForEndOfToken(SecondClose);
11049 if (SecondClose.isInvalid())
11050 SecondOpen = SourceLocation();
11051 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11052 << FixItHint::CreateInsertion(SecondOpen, "(")
11053 << FixItHint::CreateInsertion(SecondClose, ")");
11054}
11055
11056// Returns true if E refers to a non-weak array.
11057static bool checkForArray(const Expr *E) {
11058 const ValueDecl *D = nullptr;
11059 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11060 D = DR->getDecl();
11061 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11062 if (Mem->isImplicitAccess())
11063 D = Mem->getMemberDecl();
11064 }
11065 if (!D)
11066 return false;
11067 return D->getType()->isArrayType() && !D->isWeak();
11068}
11069
11070/// Diagnose some forms of syntactically-obvious tautological comparison.
11071static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11072 Expr *LHS, Expr *RHS,
11073 BinaryOperatorKind Opc) {
11074 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11075 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11076
11077 QualType LHSType = LHS->getType();
11078 QualType RHSType = RHS->getType();
11079 if (LHSType->hasFloatingRepresentation() ||
11080 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11081 S.inTemplateInstantiation())
11082 return;
11083
11084 // Comparisons between two array types are ill-formed for operator<=>, so
11085 // we shouldn't emit any additional warnings about it.
11086 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11087 return;
11088
11089 // For non-floating point types, check for self-comparisons of the form
11090 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11091 // often indicate logic errors in the program.
11092 //
11093 // NOTE: Don't warn about comparison expressions resulting from macro
11094 // expansion. Also don't warn about comparisons which are only self
11095 // comparisons within a template instantiation. The warnings should catch
11096 // obvious cases in the definition of the template anyways. The idea is to
11097 // warn when the typed comparison operator will always evaluate to the same
11098 // result.
11099
11100 // Used for indexing into %select in warn_comparison_always
11101 enum {
11102 AlwaysConstant,
11103 AlwaysTrue,
11104 AlwaysFalse,
11105 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11106 };
11107
11108 // C++2a [depr.array.comp]:
11109 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11110 // operands of array type are deprecated.
11111 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11112 RHSStripped->getType()->isArrayType()) {
11113 S.Diag(Loc, diag::warn_depr_array_comparison)
11114 << LHS->getSourceRange() << RHS->getSourceRange()
11115 << LHSStripped->getType() << RHSStripped->getType();
11116 // Carry on to produce the tautological comparison warning, if this
11117 // expression is potentially-evaluated, we can resolve the array to a
11118 // non-weak declaration, and so on.
11119 }
11120
11121 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11122 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11123 unsigned Result;
11124 switch (Opc) {
11125 case BO_EQ:
11126 case BO_LE:
11127 case BO_GE:
11128 Result = AlwaysTrue;
11129 break;
11130 case BO_NE:
11131 case BO_LT:
11132 case BO_GT:
11133 Result = AlwaysFalse;
11134 break;
11135 case BO_Cmp:
11136 Result = AlwaysEqual;
11137 break;
11138 default:
11139 Result = AlwaysConstant;
11140 break;
11141 }
11142 S.DiagRuntimeBehavior(Loc, nullptr,
11143 S.PDiag(diag::warn_comparison_always)
11144 << 0 /*self-comparison*/
11145 << Result);
11146 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11147 // What is it always going to evaluate to?
11148 unsigned Result;
11149 switch (Opc) {
11150 case BO_EQ: // e.g. array1 == array2
11151 Result = AlwaysFalse;
11152 break;
11153 case BO_NE: // e.g. array1 != array2
11154 Result = AlwaysTrue;
11155 break;
11156 default: // e.g. array1 <= array2
11157 // The best we can say is 'a constant'
11158 Result = AlwaysConstant;
11159 break;
11160 }
11161 S.DiagRuntimeBehavior(Loc, nullptr,
11162 S.PDiag(diag::warn_comparison_always)
11163 << 1 /*array comparison*/
11164 << Result);
11165 }
11166 }
11167
11168 if (isa<CastExpr>(LHSStripped))
11169 LHSStripped = LHSStripped->IgnoreParenCasts();
11170 if (isa<CastExpr>(RHSStripped))
11171 RHSStripped = RHSStripped->IgnoreParenCasts();
11172
11173 // Warn about comparisons against a string constant (unless the other
11174 // operand is null); the user probably wants string comparison function.
11175 Expr *LiteralString = nullptr;
11176 Expr *LiteralStringStripped = nullptr;
11177 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11178 !RHSStripped->isNullPointerConstant(S.Context,
11179 Expr::NPC_ValueDependentIsNull)) {
11180 LiteralString = LHS;
11181 LiteralStringStripped = LHSStripped;
11182 } else if ((isa<StringLiteral>(RHSStripped) ||
11183 isa<ObjCEncodeExpr>(RHSStripped)) &&
11184 !LHSStripped->isNullPointerConstant(S.Context,
11185 Expr::NPC_ValueDependentIsNull)) {
11186 LiteralString = RHS;
11187 LiteralStringStripped = RHSStripped;
11188 }
11189
11190 if (LiteralString) {
11191 S.DiagRuntimeBehavior(Loc, nullptr,
11192 S.PDiag(diag::warn_stringcompare)
11193 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11194 << LiteralString->getSourceRange());
11195 }
11196}
11197
11198static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11199 switch (CK) {
11200 default: {
11201#ifndef NDEBUG
11202 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11203 << "\n";
11204#endif
11205 llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11205)
;
11206 }
11207 case CK_UserDefinedConversion:
11208 return ICK_Identity;
11209 case CK_LValueToRValue:
11210 return ICK_Lvalue_To_Rvalue;
11211 case CK_ArrayToPointerDecay:
11212 return ICK_Array_To_Pointer;
11213 case CK_FunctionToPointerDecay:
11214 return ICK_Function_To_Pointer;
11215 case CK_IntegralCast:
11216 return ICK_Integral_Conversion;
11217 case CK_FloatingCast:
11218 return ICK_Floating_Conversion;
11219 case CK_IntegralToFloating:
11220 case CK_FloatingToIntegral:
11221 return ICK_Floating_Integral;
11222 case CK_IntegralComplexCast:
11223 case CK_FloatingComplexCast:
11224 case CK_FloatingComplexToIntegralComplex:
11225 case CK_IntegralComplexToFloatingComplex:
11226 return ICK_Complex_Conversion;
11227 case CK_FloatingComplexToReal:
11228 case CK_FloatingRealToComplex:
11229 case CK_IntegralComplexToReal:
11230 case CK_IntegralRealToComplex:
11231 return ICK_Complex_Real;
11232 }
11233}
11234
11235static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11236 QualType FromType,
11237 SourceLocation Loc) {
11238 // Check for a narrowing implicit conversion.
11239 StandardConversionSequence SCS;
11240 SCS.setAsIdentityConversion();
11241 SCS.setToType(0, FromType);
11242 SCS.setToType(1, ToType);
11243 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11244 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11245
11246 APValue PreNarrowingValue;
11247 QualType PreNarrowingType;
11248 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11249 PreNarrowingType,
11250 /*IgnoreFloatToIntegralConversion*/ true)) {
11251 case NK_Dependent_Narrowing:
11252 // Implicit conversion to a narrower type, but the expression is
11253 // value-dependent so we can't tell whether it's actually narrowing.
11254 case NK_Not_Narrowing:
11255 return false;
11256
11257 case NK_Constant_Narrowing:
11258 // Implicit conversion to a narrower type, and the value is not a constant
11259 // expression.
11260 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11261 << /*Constant*/ 1
11262 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11263 return true;
11264
11265 case NK_Variable_Narrowing:
11266 // Implicit conversion to a narrower type, and the value is not a constant
11267 // expression.
11268 case NK_Type_Narrowing:
11269 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11270 << /*Constant*/ 0 << FromType << ToType;
11271 // TODO: It's not a constant expression, but what if the user intended it
11272 // to be? Can we produce notes to help them figure out why it isn't?
11273 return true;
11274 }
11275 llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch",
"/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11275)
;
11276}
11277
11278static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11279 ExprResult &LHS,
11280 ExprResult &RHS,
11281 SourceLocation Loc) {
11282 QualType LHSType = LHS.get()->getType();
11283 QualType RHSType = RHS.get()->getType();
11284 // Dig out the original argument type and expression before implicit casts
11285 // were applied. These are the types/expressions we need to check the
11286 // [expr.spaceship] requirements against.
11287 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11288 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11289 QualType LHSStrippedType = LHSStripped.get()->getType();
11290 QualType RHSStrippedType = RHSStripped.get()->getType();
11291
11292 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11293 // other is not, the program is ill-formed.
11294 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11295 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11296 return QualType();
11297 }
11298
11299 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11300 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11301 RHSStrippedType->isEnumeralType();
11302 if (NumEnumArgs == 1) {
11303 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11304 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11305 if (OtherTy->hasFloatingRepresentation()) {
11306 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11307 return QualType();
11308 }
11309 }
11310 if (NumEnumArgs == 2) {
11311 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11312 // type E, the operator yields the result of converting the operands
11313 // to the underlying type of E and applying <=> to the converted operands.
11314 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11315 S.InvalidOperands(Loc, LHS, RHS);
11316 return QualType();
11317 }
11318 QualType IntType =
11319 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11320 assert(IntType->isArithmeticType())((IntType->isArithmeticType()) ? static_cast<void> (
0) : __assert_fail ("IntType->isArithmeticType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11320, __PRETTY_FUNCTION__))
;
11321
11322 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11323 // promote the boolean type, and all other promotable integer types, to
11324 // avoid this.
11325 if (IntType->isPromotableIntegerType())
11326 IntType = S.Context.getPromotedIntegerType(IntType);
11327
11328 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11329 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11330 LHSType = RHSType = IntType;
11331 }
11332
11333 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11334 // usual arithmetic conversions are applied to the operands.
11335 QualType Type =
11336 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11337 if (LHS.isInvalid() || RHS.isInvalid())
11338 return QualType();
11339 if (Type.isNull())
11340 return S.InvalidOperands(Loc, LHS, RHS);
11341
11342 Optional<ComparisonCategoryType> CCT =
11343 getComparisonCategoryForBuiltinCmp(Type);
11344 if (!CCT)
11345 return S.InvalidOperands(Loc, LHS, RHS);
11346
11347 bool HasNarrowing = checkThreeWayNarrowingConversion(
11348 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11349 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11350 RHS.get()->getBeginLoc());
11351 if (HasNarrowing)
11352 return QualType();
11353
11354 assert(!Type.isNull() && "composite type for <=> has not been set")((!Type.isNull() && "composite type for <=> has not been set"
) ? static_cast<void> (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11354, __PRETTY_FUNCTION__))
;
11355
11356 return S.CheckComparisonCategoryType(
11357 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11358}
11359
11360static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11361 ExprResult &RHS,
11362 SourceLocation Loc,
11363 BinaryOperatorKind Opc) {
11364 if (Opc == BO_Cmp)
11365 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11366
11367 // C99 6.5.8p3 / C99 6.5.9p4
11368 QualType Type =
11369 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11370 if (LHS.isInvalid() || RHS.isInvalid())
11371 return QualType();
11372 if (Type.isNull())
11373 return S.InvalidOperands(Loc, LHS, RHS);
11374 assert(Type->isArithmeticType() || Type->isEnumeralType())((Type->isArithmeticType() || Type->isEnumeralType()) ?
static_cast<void> (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11374, __PRETTY_FUNCTION__))
;
11375
11376 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11377 return S.InvalidOperands(Loc, LHS, RHS);
11378
11379 // Check for comparisons of floating point operands using != and ==.
11380 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11381 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11382
11383 // The result of comparisons is 'bool' in C++, 'int' in C.
11384 return S.Context.getLogicalOperationType();
11385}
11386
11387void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11388 if (!NullE.get()->getType()->isAnyPointerType())
11389 return;
11390 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11391 if (!E.get()->getType()->isAnyPointerType() &&
11392 E.get()->isNullPointerConstant(Context,
11393 Expr::NPC_ValueDependentIsNotNull) ==
11394 Expr::NPCK_ZeroExpression) {
11395 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11396 if (CL->getValue() == 0)
11397 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11398 << NullValue
11399 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11400 NullValue ? "NULL" : "(void *)0");
11401 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11402 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11403 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11404 if (T == Context.CharTy)
11405 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11406 << NullValue
11407 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11408 NullValue ? "NULL" : "(void *)0");
11409 }
11410 }
11411}
11412
11413// C99 6.5.8, C++ [expr.rel]
11414QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11415 SourceLocation Loc,
11416 BinaryOperatorKind Opc) {
11417 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11418 bool IsThreeWay = Opc == BO_Cmp;
11419 bool IsOrdered = IsRelational || IsThreeWay;
11420 auto IsAnyPointerType = [](ExprResult E) {
11421 QualType Ty = E.get()->getType();
11422 return Ty->isPointerType() || Ty->isMemberPointerType();
11423 };
11424
11425 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11426 // type, array-to-pointer, ..., conversions are performed on both operands to
11427 // bring them to their composite type.
11428 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11429 // any type-related checks.
11430 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11431 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11432 if (LHS.isInvalid())
11433 return QualType();
11434 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11435 if (RHS.isInvalid())
11436 return QualType();
11437 } else {
11438 LHS = DefaultLvalueConversion(LHS.get());
11439 if (LHS.isInvalid())
11440 return QualType();
11441 RHS = DefaultLvalueConversion(RHS.get());
11442 if (RHS.isInvalid())
11443 return QualType();
11444 }
11445
11446 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11447 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11448 CheckPtrComparisonWithNullChar(LHS, RHS);
11449 CheckPtrComparisonWithNullChar(RHS, LHS);
11450 }
11451
11452 // Handle vector comparisons separately.
11453 if (LHS.get()->getType()->isVectorType() ||
11454 RHS.get()->getType()->isVectorType())
11455 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11456
11457 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11458 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11459
11460 QualType LHSType = LHS.get()->getType();
11461 QualType RHSType = RHS.get()->getType();
11462 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11463 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11464 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11465
11466 const Expr::NullPointerConstantKind LHSNullKind =
11467 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11468 const Expr::NullPointerConstantKind RHSNullKind =
11469 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11470 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11471 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11472
11473 auto computeResultTy = [&]() {
11474 if (Opc != BO_Cmp)
11475 return Context.getLogicalOperationType();
11476 assert(getLangOpts().CPlusPlus)((getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail
("getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11476, __PRETTY_FUNCTION__))
;
11477 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))((Context.hasSameType(LHS.get()->getType(), RHS.get()->
getType())) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11477, __PRETTY_FUNCTION__))
;
11478
11479 QualType CompositeTy = LHS.get()->getType();
11480 assert(!CompositeTy->isReferenceType())((!CompositeTy->isReferenceType()) ? static_cast<void>
(0) : __assert_fail ("!CompositeTy->isReferenceType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11480, __PRETTY_FUNCTION__))
;
11481
11482 Optional<ComparisonCategoryType> CCT =
11483 getComparisonCategoryForBuiltinCmp(CompositeTy);
11484 if (!CCT)
11485 return InvalidOperands(Loc, LHS, RHS);
11486
11487 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11488 // P0946R0: Comparisons between a null pointer constant and an object
11489 // pointer result in std::strong_equality, which is ill-formed under
11490 // P1959R0.
11491 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11492 << (LHSIsNull ? LHS.get()->getSourceRange()
11493 : RHS.get()->getSourceRange());
11494 return QualType();
11495 }
11496
11497 return CheckComparisonCategoryType(
11498 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11499 };
11500
11501 if (!IsOrdered && LHSIsNull != RHSIsNull) {
11502 bool IsEquality = Opc == BO_EQ;
11503 if (RHSIsNull)
11504 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11505 RHS.get()->getSourceRange());
11506 else
11507 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11508 LHS.get()->getSourceRange());
11509 }
11510
11511 if ((LHSType->isIntegerType() && !LHSIsNull) ||
11512 (RHSType->isIntegerType() && !RHSIsNull)) {
11513 // Skip normal pointer conversion checks in this case; we have better
11514 // diagnostics for this below.
11515 } else if (getLangOpts().CPlusPlus) {
11516 // Equality comparison of a function pointer to a void pointer is invalid,
11517 // but we allow it as an extension.
11518 // FIXME: If we really want to allow this, should it be part of composite
11519 // pointer type computation so it works in conditionals too?
11520 if (!IsOrdered &&
11521 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11522 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11523 // This is a gcc extension compatibility comparison.
11524 // In a SFINAE context, we treat this as a hard error to maintain
11525 // conformance with the C++ standard.
11526 diagnoseFunctionPointerToVoidComparison(
11527 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11528
11529 if (isSFINAEContext())
11530 return QualType();
11531
11532 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11533 return computeResultTy();
11534 }
11535
11536 // C++ [expr.eq]p2:
11537 // If at least one operand is a pointer [...] bring them to their
11538 // composite pointer type.
11539 // C++ [expr.spaceship]p6
11540 // If at least one of the operands is of pointer type, [...] bring them
11541 // to their composite pointer type.
11542 // C++ [expr.rel]p2:
11543 // If both operands are pointers, [...] bring them to their composite
11544 // pointer type.
11545 // For <=>, the only valid non-pointer types are arrays and functions, and
11546 // we already decayed those, so this is really the same as the relational
11547 // comparison rule.
11548 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11549 (IsOrdered ? 2 : 1) &&
11550 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11551 RHSType->isObjCObjectPointerType()))) {
11552 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11553 return QualType();
11554 return computeResultTy();
11555 }
11556 } else if (LHSType->isPointerType() &&
11557 RHSType->isPointerType()) { // C99 6.5.8p2
11558 // All of the following pointer-related warnings are GCC extensions, except
11559 // when handling null pointer constants.
11560 QualType LCanPointeeTy =
11561 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11562 QualType RCanPointeeTy =
11563 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11564
11565 // C99 6.5.9p2 and C99 6.5.8p2
11566 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11567 RCanPointeeTy.getUnqualifiedType())) {
11568 if (IsRelational) {
11569 // Pointers both need to point to complete or incomplete types
11570 if ((LCanPointeeTy->isIncompleteType() !=
11571 RCanPointeeTy->isIncompleteType()) &&
11572 !getLangOpts().C11) {
11573 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11574 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11575 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11576 << RCanPointeeTy->isIncompleteType();
11577 }
11578 if (LCanPointeeTy->isFunctionType()) {
11579 // Valid unless a relational comparison of function pointers
11580 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11581 << LHSType << RHSType << LHS.get()->getSourceRange()
11582 << RHS.get()->getSourceRange();
11583 }
11584 }
11585 } else if (!IsRelational &&
11586 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11587 // Valid unless comparison between non-null pointer and function pointer
11588 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11589 && !LHSIsNull && !RHSIsNull)
11590 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11591 /*isError*/false);
11592 } else {
11593 // Invalid
11594 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11595 }
11596 if (LCanPointeeTy != RCanPointeeTy) {
11597 // Treat NULL constant as a special case in OpenCL.
11598 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11599 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11600 Diag(Loc,
11601 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11602 << LHSType << RHSType << 0 /* comparison */
11603 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11604 }
11605 }
11606 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11607 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11608 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11609 : CK_BitCast;
11610 if (LHSIsNull && !RHSIsNull)
11611 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11612 else
11613 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11614 }
11615 return computeResultTy();
11616 }
11617
11618 if (getLangOpts().CPlusPlus) {
11619 // C++ [expr.eq]p4:
11620 // Two operands of type std::nullptr_t or one operand of type
11621 // std::nullptr_t and the other a null pointer constant compare equal.
11622 if (!IsOrdered && LHSIsNull && RHSIsNull) {
11623 if (LHSType->isNullPtrType()) {
11624 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11625 return computeResultTy();
11626 }
11627 if (RHSType->isNullPtrType()) {
11628 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11629 return computeResultTy();
11630 }
11631 }
11632
11633 // Comparison of Objective-C pointers and block pointers against nullptr_t.
11634 // These aren't covered by the composite pointer type rules.
11635 if (!IsOrdered && RHSType->isNullPtrType() &&
11636 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11637 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11638 return computeResultTy();
11639 }
11640 if (!IsOrdered && LHSType->isNullPtrType() &&
11641 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11642 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11643 return computeResultTy();
11644 }
11645
11646 if (IsRelational &&
11647 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11648 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11649 // HACK: Relational comparison of nullptr_t against a pointer type is
11650 // invalid per DR583, but we allow it within std::less<> and friends,
11651 // since otherwise common uses of it break.
11652 // FIXME: Consider removing this hack once LWG fixes std::less<> and
11653 // friends to have std::nullptr_t overload candidates.
11654 DeclContext *DC = CurContext;
11655 if (isa<FunctionDecl>(DC))
11656 DC = DC->getParent();
11657 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11658 if (CTSD->isInStdNamespace() &&
11659 llvm::StringSwitch<bool>(CTSD->getName())
11660 .Cases("less", "less_equal", "greater", "greater_equal", true)
11661 .Default(false)) {
11662 if (RHSType->isNullPtrType())
11663 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11664 else
11665 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11666 return computeResultTy();
11667 }
11668 }
11669 }
11670
11671 // C++ [expr.eq]p2:
11672 // If at least one operand is a pointer to member, [...] bring them to
11673 // their composite pointer type.
11674 if (!IsOrdered &&
11675 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11676 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11677 return QualType();
11678 else
11679 return computeResultTy();
11680 }
11681 }
11682
11683 // Handle block pointer types.
11684 if (!IsOrdered && LHSType->isBlockPointerType() &&
11685 RHSType->isBlockPointerType()) {
11686 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11687 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11688
11689 if (!LHSIsNull && !RHSIsNull &&
11690 !Context.typesAreCompatible(lpointee, rpointee)) {
11691 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11692 << LHSType << RHSType << LHS.get()->getSourceRange()
11693 << RHS.get()->getSourceRange();
11694 }
11695 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11696 return computeResultTy();
11697 }
11698
11699 // Allow block pointers to be compared with null pointer constants.
11700 if (!IsOrdered
11701 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11702 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11703 if (!LHSIsNull && !RHSIsNull) {
11704 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11705 ->getPointeeType()->isVoidType())
11706 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11707 ->getPointeeType()->isVoidType())))
11708 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11709 << LHSType << RHSType << LHS.get()->getSourceRange()
11710 << RHS.get()->getSourceRange();
11711 }
11712 if (LHSIsNull && !RHSIsNull)
11713 LHS = ImpCastExprToType(LHS.get(), RHSType,
11714 RHSType->isPointerType() ? CK_BitCast
11715 : CK_AnyPointerToBlockPointerCast);
11716 else
11717 RHS = ImpCastExprToType(RHS.get(), LHSType,
11718 LHSType->isPointerType() ? CK_BitCast
11719 : CK_AnyPointerToBlockPointerCast);
11720 return computeResultTy();
11721 }
11722
11723 if (LHSType->isObjCObjectPointerType() ||
11724 RHSType->isObjCObjectPointerType()) {
11725 const PointerType *LPT = LHSType->getAs<PointerType>();
11726 const PointerType *RPT = RHSType->getAs<PointerType>();
11727 if (LPT || RPT) {
11728 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11729 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11730
11731 if (!LPtrToVoid && !RPtrToVoid &&
11732 !Context.typesAreCompatible(LHSType, RHSType)) {
11733 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11734 /*isError*/false);
11735 }
11736 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11737 // the RHS, but we have test coverage for this behavior.
11738 // FIXME: Consider using convertPointersToCompositeType in C++.
11739 if (LHSIsNull && !RHSIsNull) {
11740 Expr *E = LHS.get();
11741 if (getLangOpts().ObjCAutoRefCount)
11742 CheckObjCConversion(SourceRange(), RHSType, E,
11743 CCK_ImplicitConversion);
11744 LHS = ImpCastExprToType(E, RHSType,
11745 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11746 }
11747 else {
11748 Expr *E = RHS.get();
11749 if (getLangOpts().ObjCAutoRefCount)
11750 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11751 /*Diagnose=*/true,
11752 /*DiagnoseCFAudited=*/false, Opc);
11753 RHS = ImpCastExprToType(E, LHSType,
11754 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11755 }
11756 return computeResultTy();
11757 }
11758 if (LHSType->isObjCObjectPointerType() &&
11759 RHSType->isObjCObjectPointerType()) {
11760 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11761 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11762 /*isError*/false);
11763 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11764 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11765
11766 if (LHSIsNull && !RHSIsNull)
11767 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11768 else
11769 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11770 return computeResultTy();
11771 }
11772
11773 if (!IsOrdered && LHSType->isBlockPointerType() &&
11774 RHSType->isBlockCompatibleObjCPointerType(Context)) {
11775 LHS = ImpCastExprToType(LHS.get(), RHSType,
11776 CK_BlockPointerToObjCPointerCast);
11777 return computeResultTy();
11778 } else if (!IsOrdered &&
11779 LHSType->isBlockCompatibleObjCPointerType(Context) &&
11780 RHSType->isBlockPointerType()) {
11781 RHS = ImpCastExprToType(RHS.get(), LHSType,
11782 CK_BlockPointerToObjCPointerCast);
11783 return computeResultTy();
11784 }
11785 }
11786 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11787 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11788 unsigned DiagID = 0;
11789 bool isError = false;
11790 if (LangOpts.DebuggerSupport) {
11791 // Under a debugger, allow the comparison of pointers to integers,
11792 // since users tend to want to compare addresses.
11793 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11794 (RHSIsNull && RHSType->isIntegerType())) {
11795 if (IsOrdered) {
11796 isError = getLangOpts().CPlusPlus;
11797 DiagID =
11798 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11799 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11800 }
11801 } else if (getLangOpts().CPlusPlus) {
11802 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11803 isError = true;
11804 } else if (IsOrdered)
11805 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11806 else
11807 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11808
11809 if (DiagID) {
11810 Diag(Loc, DiagID)
11811 << LHSType << RHSType << LHS.get()->getSourceRange()
11812 << RHS.get()->getSourceRange();
11813 if (isError)
11814 return QualType();
11815 }
11816
11817 if (LHSType->isIntegerType())
11818 LHS = ImpCastExprToType(LHS.get(), RHSType,
11819 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11820 else
11821 RHS = ImpCastExprToType(RHS.get(), LHSType,
11822 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11823 return computeResultTy();
11824 }
11825
11826 // Handle block pointers.
11827 if (!IsOrdered && RHSIsNull
11828 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11829 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11830 return computeResultTy();
11831 }
11832 if (!IsOrdered && LHSIsNull
11833 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11834 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11835 return computeResultTy();
11836 }
11837
11838 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11839 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11840 return computeResultTy();
11841 }
11842
11843 if (LHSType->isQueueT() && RHSType->isQueueT()) {
11844 return computeResultTy();
11845 }
11846
11847 if (LHSIsNull && RHSType->isQueueT()) {
11848 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11849 return computeResultTy();
11850 }
11851
11852 if (LHSType->isQueueT() && RHSIsNull) {
11853 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11854 return computeResultTy();
11855 }
11856 }
11857
11858 return InvalidOperands(Loc, LHS, RHS);
11859}
11860
11861// Return a signed ext_vector_type that is of identical size and number of
11862// elements. For floating point vectors, return an integer type of identical
11863// size and number of elements. In the non ext_vector_type case, search from
11864// the largest type to the smallest type to avoid cases where long long == long,
11865// where long gets picked over long long.
11866QualType Sema::GetSignedVectorType(QualType V) {
11867 const VectorType *VTy = V->castAs<VectorType>();
11868 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11869
11870 if (isa<ExtVectorType>(VTy)) {
11871 if (TypeSize == Context.getTypeSize(Context.CharTy))
11872 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11873 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11874 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11875 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11876 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11877 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11878 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11879 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&((TypeSize == Context.getTypeSize(Context.LongLongTy) &&
"Unhandled vector element size in vector compare") ? static_cast
<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11880, __PRETTY_FUNCTION__))
11880 "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.LongLongTy) &&
"Unhandled vector element size in vector compare") ? static_cast
<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11880, __PRETTY_FUNCTION__))
;
11881 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11882 }
11883
11884 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11885 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11886 VectorType::GenericVector);
11887 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11888 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11889 VectorType::GenericVector);
11890 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11891 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11892 VectorType::GenericVector);
11893 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11894 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11895 VectorType::GenericVector);
11896 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare"
) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11897, __PRETTY_FUNCTION__))
11897 "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare"
) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11897, __PRETTY_FUNCTION__))
;
11898 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11899 VectorType::GenericVector);
11900}
11901
11902/// CheckVectorCompareOperands - vector comparisons are a clang extension that
11903/// operates on extended vector types. Instead of producing an IntTy result,
11904/// like a scalar comparison, a vector comparison produces a vector of integer
11905/// types.
11906QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11907 SourceLocation Loc,
11908 BinaryOperatorKind Opc) {
11909 if (Opc == BO_Cmp) {
11910 Diag(Loc, diag::err_three_way_vector_comparison);
11911 return QualType();
11912 }
11913
11914 // Check to make sure we're operating on vectors of the same type and width,
11915 // Allowing one side to be a scalar of element type.
11916 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11917 /*AllowBothBool*/true,
11918 /*AllowBoolConversions*/getLangOpts().ZVector);
11919 if (vType.isNull())
11920 return vType;
11921
11922 QualType LHSType = LHS.get()->getType();
11923
11924 // If AltiVec, the comparison results in a numeric type, i.e.
11925 // bool for C++, int for C
11926 if (getLangOpts().AltiVec &&
11927 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11928 return Context.getLogicalOperationType();
11929
11930 // For non-floating point types, check for self-comparisons of the form
11931 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11932 // often indicate logic errors in the program.
11933 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11934
11935 // Check for comparisons of floating point operands using != and ==.
11936 if (BinaryOperator::isEqualityOp(Opc) &&
11937 LHSType->hasFloatingRepresentation()) {
11938 assert(RHS.get()->getType()->hasFloatingRepresentation())((RHS.get()->getType()->hasFloatingRepresentation()) ? static_cast
<void> (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 11938, __PRETTY_FUNCTION__))
;
11939 CheckFloatComparison(Loc, LHS.get(), RHS.get());
11940 }
11941
11942 // Return a signed type for the vector.
11943 return GetSignedVectorType(vType);
11944}
11945
11946static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11947 const ExprResult &XorRHS,
11948 const SourceLocation Loc) {
11949 // Do not diagnose macros.
11950 if (Loc.isMacroID())
11951 return;
11952
11953 bool Negative = false;
11954 bool ExplicitPlus = false;
11955 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11956 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11957
11958 if (!LHSInt)
11959 return;
11960 if (!RHSInt) {
11961 // Check negative literals.
11962 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11963 UnaryOperatorKind Opc = UO->getOpcode();
11964 if (Opc != UO_Minus && Opc != UO_Plus)
11965 return;
11966 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11967 if (!RHSInt)
11968 return;
11969 Negative = (Opc == UO_Minus);
11970 ExplicitPlus = !Negative;
11971 } else {
11972 return;
11973 }
11974 }
11975
11976 const llvm::APInt &LeftSideValue = LHSInt->getValue();
11977 llvm::APInt RightSideValue = RHSInt->getValue();
11978 if (LeftSideValue != 2 && LeftSideValue != 10)
11979 return;
11980
11981 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11982 return;
11983
11984 CharSourceRange ExprRange = CharSourceRange::getCharRange(
11985 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11986 llvm::StringRef ExprStr =
11987 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11988
11989 CharSourceRange XorRange =
11990 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11991 llvm::StringRef XorStr =
11992 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11993 // Do not diagnose if xor keyword/macro is used.
11994 if (XorStr == "xor")
11995 return;
11996
11997 std::string LHSStr = std::string(Lexer::getSourceText(
11998 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11999 S.getSourceManager(), S.getLangOpts()));
12000 std::string RHSStr = std::string(Lexer::getSourceText(
12001 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12002 S.getSourceManager(), S.getLangOpts()));
12003
12004 if (Negative) {
12005 RightSideValue = -RightSideValue;
12006 RHSStr = "-" + RHSStr;
12007 } else if (ExplicitPlus) {
12008 RHSStr = "+" + RHSStr;
12009 }
12010
12011 StringRef LHSStrRef = LHSStr;
12012 StringRef RHSStrRef = RHSStr;
12013 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12014 // literals.
12015 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12016 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12017 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12018 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12019 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12020 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12021 LHSStrRef.find('\'') != StringRef::npos ||
12022 RHSStrRef.find('\'') != StringRef::npos)
12023 return;
12024
12025 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12026 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12027 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12028 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12029 std::string SuggestedExpr = "1 << " + RHSStr;
12030 bool Overflow = false;
12031 llvm::APInt One = (LeftSideValue - 1);
12032 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12033 if (Overflow) {
12034 if (RightSideIntValue < 64)
12035 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12036 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12037 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12038 else if (RightSideIntValue == 64)
12039 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12040 else
12041 return;
12042 } else {
12043 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12044 << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12045 << PowValue.toString(10, true)
12046 << FixItHint::CreateReplacement(
12047 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12048 }
12049
12050 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12051 } else if (LeftSideValue == 10) {
12052 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12053 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12054 << ExprStr << XorValue.toString(10, true) << SuggestedValue
12055 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12056 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12057 }
12058}
12059
12060QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12061 SourceLocation Loc) {
12062 // Ensure that either both operands are of the same vector type, or
12063 // one operand is of a vector type and the other is of its element type.
12064 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12065 /*AllowBothBool*/true,
12066 /*AllowBoolConversions*/false);
12067 if (vType.isNull())
12068 return InvalidOperands(Loc, LHS, RHS);
12069 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12070 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12071 return InvalidOperands(Loc, LHS, RHS);
12072 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12073 // usage of the logical operators && and || with vectors in C. This
12074 // check could be notionally dropped.
12075 if (!getLangOpts().CPlusPlus &&
12076 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12077 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12078
12079 return GetSignedVectorType(LHS.get()->getType());
12080}
12081
12082QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12083 SourceLocation Loc,
12084 bool IsCompAssign) {
12085 if (!IsCompAssign) {
12086 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12087 if (LHS.isInvalid())
12088 return QualType();
12089 }
12090 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12091 if (RHS.isInvalid())
12092 return QualType();
12093
12094 // For conversion purposes, we ignore any qualifiers.
12095 // For example, "const float" and "float" are equivalent.
12096 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12097 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12098
12099 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12100 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12101 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix"
) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12101, __PRETTY_FUNCTION__))
;
12102
12103 if (Context.hasSameType(LHSType, RHSType))
12104 return LHSType;
12105
12106 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12107 // case we have to return InvalidOperands.
12108 ExprResult OriginalLHS = LHS;
12109 ExprResult OriginalRHS = RHS;
12110 if (LHSMatType && !RHSMatType) {
12111 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12112 if (!RHS.isInvalid())
12113 return LHSType;
12114
12115 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12116 }
12117
12118 if (!LHSMatType && RHSMatType) {
12119 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12120 if (!LHS.isInvalid())
12121 return RHSType;
12122 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12123 }
12124
12125 return InvalidOperands(Loc, LHS, RHS);
12126}
12127
12128QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12129 SourceLocation Loc,
12130 bool IsCompAssign) {
12131 if (!IsCompAssign) {
12132 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12133 if (LHS.isInvalid())
12134 return QualType();
12135 }
12136 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12137 if (RHS.isInvalid())
12138 return QualType();
12139
12140 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12141 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12142 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix")(((LHSMatType || RHSMatType) && "At least one operand must be a matrix"
) ? static_cast<void> (0) : __assert_fail ("(LHSMatType || RHSMatType) && \"At least one operand must be a matrix\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12142, __PRETTY_FUNCTION__))
;
12143
12144 if (LHSMatType && RHSMatType) {
12145 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12146 return InvalidOperands(Loc, LHS, RHS);
12147
12148 if (!Context.hasSameType(LHSMatType->getElementType(),
12149 RHSMatType->getElementType()))
12150 return InvalidOperands(Loc, LHS, RHS);
12151
12152 return Context.getConstantMatrixType(LHSMatType->getElementType(),
12153 LHSMatType->getNumRows(),
12154 RHSMatType->getNumColumns());
12155 }
12156 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12157}
12158
12159inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12160 SourceLocation Loc,
12161 BinaryOperatorKind Opc) {
12162 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12163
12164 bool IsCompAssign =
12165 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12166
12167 if (LHS.get()->getType()->isVectorType() ||
12168 RHS.get()->getType()->isVectorType()) {
12169 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12170 RHS.get()->getType()->hasIntegerRepresentation())
12171 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12172 /*AllowBothBool*/true,
12173 /*AllowBoolConversions*/getLangOpts().ZVector);
12174 return InvalidOperands(Loc, LHS, RHS);
12175 }
12176
12177 if (Opc == BO_And)
12178 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12179
12180 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12181 RHS.get()->getType()->hasFloatingRepresentation())
12182 return InvalidOperands(Loc, LHS, RHS);
12183
12184 ExprResult LHSResult = LHS, RHSResult = RHS;
12185 QualType compType = UsualArithmeticConversions(
12186 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12187 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12188 return QualType();
12189 LHS = LHSResult.get();
12190 RHS = RHSResult.get();
12191
12192 if (Opc == BO_Xor)
12193 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12194
12195 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12196 return compType;
12197 return InvalidOperands(Loc, LHS, RHS);
12198}
12199
12200// C99 6.5.[13,14]
12201inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12202 SourceLocation Loc,
12203 BinaryOperatorKind Opc) {
12204 // Check vector operands differently.
12205 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12206 return CheckVectorLogicalOperands(LHS, RHS, Loc);
12207
12208 bool EnumConstantInBoolContext = false;
12209 for (const ExprResult &HS : {LHS, RHS}) {
12210 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12211 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12212 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12213 EnumConstantInBoolContext = true;
12214 }
12215 }
12216
12217 if (EnumConstantInBoolContext)
12218 Diag(Loc, diag::warn_enum_constant_in_bool_context);
12219
12220 // Diagnose cases where the user write a logical and/or but probably meant a
12221 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
12222 // is a constant.
12223 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12224 !LHS.get()->getType()->isBooleanType() &&
12225 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12226 // Don't warn in macros or template instantiations.
12227 !Loc.isMacroID() && !inTemplateInstantiation()) {
12228 // If the RHS can be constant folded, and if it constant folds to something
12229 // that isn't 0 or 1 (which indicate a potential logical operation that
12230 // happened to fold to true/false) then warn.
12231 // Parens on the RHS are ignored.
12232 Expr::EvalResult EVResult;
12233 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12234 llvm::APSInt Result = EVResult.Val.getInt();
12235 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12236 !RHS.get()->getExprLoc().isMacroID()) ||
12237 (Result != 0 && Result != 1)) {
12238 Diag(Loc, diag::warn_logical_instead_of_bitwise)
12239 << RHS.get()->getSourceRange()
12240 << (Opc == BO_LAnd ? "&&" : "||");
12241 // Suggest replacing the logical operator with the bitwise version
12242 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12243 << (Opc == BO_LAnd ? "&" : "|")
12244 << FixItHint::CreateReplacement(SourceRange(
12245 Loc, getLocForEndOfToken(Loc)),
12246 Opc == BO_LAnd ? "&" : "|");
12247 if (Opc == BO_LAnd)
12248 // Suggest replacing "Foo() && kNonZero" with "Foo()"
12249 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12250 << FixItHint::CreateRemoval(
12251 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12252 RHS.get()->getEndLoc()));
12253 }
12254 }
12255 }
12256
12257 if (!Context.getLangOpts().CPlusPlus) {
12258 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12259 // not operate on the built-in scalar and vector float types.
12260 if (Context.getLangOpts().OpenCL &&
12261 Context.getLangOpts().OpenCLVersion < 120) {
12262 if (LHS.get()->getType()->isFloatingType() ||
12263 RHS.get()->getType()->isFloatingType())
12264 return InvalidOperands(Loc, LHS, RHS);
12265 }
12266
12267 LHS = UsualUnaryConversions(LHS.get());
12268 if (LHS.isInvalid())
12269 return QualType();
12270
12271 RHS = UsualUnaryConversions(RHS.get());
12272 if (RHS.isInvalid())
12273 return QualType();
12274
12275 if (!LHS.get()->getType()->isScalarType() ||
12276 !RHS.get()->getType()->isScalarType())
12277 return InvalidOperands(Loc, LHS, RHS);
12278
12279 return Context.IntTy;
12280 }
12281
12282 // The following is safe because we only use this method for
12283 // non-overloadable operands.
12284
12285 // C++ [expr.log.and]p1
12286 // C++ [expr.log.or]p1
12287 // The operands are both contextually converted to type bool.
12288 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12289 if (LHSRes.isInvalid())
12290 return InvalidOperands(Loc, LHS, RHS);
12291 LHS = LHSRes;
12292
12293 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12294 if (RHSRes.isInvalid())
12295 return InvalidOperands(Loc, LHS, RHS);
12296 RHS = RHSRes;
12297
12298 // C++ [expr.log.and]p2
12299 // C++ [expr.log.or]p2
12300 // The result is a bool.
12301 return Context.BoolTy;
12302}
12303
12304static bool IsReadonlyMessage(Expr *E, Sema &S) {
12305 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12306 if (!ME) return false;
12307 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12308 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12309 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12310 if (!Base) return false;
12311 return Base->getMethodDecl() != nullptr;
12312}
12313
12314/// Is the given expression (which must be 'const') a reference to a
12315/// variable which was originally non-const, but which has become
12316/// 'const' due to being captured within a block?
12317enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12318static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12319 assert(E->isLValue() && E->getType().isConstQualified())((E->isLValue() && E->getType().isConstQualified
()) ? static_cast<void> (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12319, __PRETTY_FUNCTION__))
;
12320 E = E->IgnoreParens();
12321
12322 // Must be a reference to a declaration from an enclosing scope.
12323 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12324 if (!DRE) return NCCK_None;
12325 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12326
12327 // The declaration must be a variable which is not declared 'const'.
12328 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12329 if (!var) return NCCK_None;
12330 if (var->getType().isConstQualified()) return NCCK_None;
12331 assert(var->hasLocalStorage() && "capture added 'const' to non-local?")((var->hasLocalStorage() && "capture added 'const' to non-local?"
) ? static_cast<void> (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12331, __PRETTY_FUNCTION__))
;
12332
12333 // Decide whether the first capture was for a block or a lambda.
12334 DeclContext *DC = S.CurContext, *Prev = nullptr;
12335 // Decide whether the first capture was for a block or a lambda.
12336 while (DC) {
12337 // For init-capture, it is possible that the variable belongs to the
12338 // template pattern of the current context.
12339 if (auto *FD = dyn_cast<FunctionDecl>(DC))
12340 if (var->isInitCapture() &&
12341 FD->getTemplateInstantiationPattern() == var->getDeclContext())
12342 break;
12343 if (DC == var->getDeclContext())
12344 break;
12345 Prev = DC;
12346 DC = DC->getParent();
12347 }
12348 // Unless we have an init-capture, we've gone one step too far.
12349 if (!var->isInitCapture())
12350 DC = Prev;
12351 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12352}
12353
12354static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12355 Ty = Ty.getNonReferenceType();
12356 if (IsDereference && Ty->isPointerType())
12357 Ty = Ty->getPointeeType();
12358 return !Ty.isConstQualified();
12359}
12360
12361// Update err_typecheck_assign_const and note_typecheck_assign_const
12362// when this enum is changed.
12363enum {
12364 ConstFunction,
12365 ConstVariable,
12366 ConstMember,
12367 ConstMethod,
12368 NestedConstMember,
12369 ConstUnknown, // Keep as last element
12370};
12371
12372/// Emit the "read-only variable not assignable" error and print notes to give
12373/// more information about why the variable is not assignable, such as pointing
12374/// to the declaration of a const variable, showing that a method is const, or
12375/// that the function is returning a const reference.
12376static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12377 SourceLocation Loc) {
12378 SourceRange ExprRange = E->getSourceRange();
12379
12380 // Only emit one error on the first const found. All other consts will emit
12381 // a note to the error.
12382 bool DiagnosticEmitted = false;
12383
12384 // Track if the current expression is the result of a dereference, and if the
12385 // next checked expression is the result of a dereference.
12386 bool IsDereference = false;
12387 bool NextIsDereference = false;
12388
12389 // Loop to process MemberExpr chains.
12390 while (true) {
12391 IsDereference = NextIsDereference;
12392
12393 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12394 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12395 NextIsDereference = ME->isArrow();
12396 const ValueDecl *VD = ME->getMemberDecl();
12397 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12398 // Mutable fields can be modified even if the class is const.
12399 if (Field->isMutable()) {
12400 assert(DiagnosticEmitted && "Expected diagnostic not emitted.")((DiagnosticEmitted && "Expected diagnostic not emitted."
) ? static_cast<void> (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12400, __PRETTY_FUNCTION__))
;
12401 break;
12402 }
12403
12404 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12405 if (!DiagnosticEmitted) {
12406 S.Diag(Loc, diag::err_typecheck_assign_const)
12407 << ExprRange << ConstMember << false /*static*/ << Field
12408 << Field->getType();
12409 DiagnosticEmitted = true;
12410 }
12411 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12412 << ConstMember << false /*static*/ << Field << Field->getType()
12413 << Field->getSourceRange();
12414 }
12415 E = ME->getBase();
12416 continue;
12417 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12418 if (VDecl->getType().isConstQualified()) {
12419 if (!DiagnosticEmitted) {
12420 S.Diag(Loc, diag::err_typecheck_assign_const)
12421 << ExprRange << ConstMember << true /*static*/ << VDecl
12422 << VDecl->getType();
12423 DiagnosticEmitted = true;
12424 }
12425 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12426 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12427 << VDecl->getSourceRange();
12428 }
12429 // Static fields do not inherit constness from parents.
12430 break;
12431 }
12432 break; // End MemberExpr
12433 } else if (const ArraySubscriptExpr *ASE =
12434 dyn_cast<ArraySubscriptExpr>(E)) {
12435 E = ASE->getBase()->IgnoreParenImpCasts();
12436 continue;
12437 } else if (const ExtVectorElementExpr *EVE =
12438 dyn_cast<ExtVectorElementExpr>(E)) {
12439 E = EVE->getBase()->IgnoreParenImpCasts();
12440 continue;
12441 }
12442 break;
12443 }
12444
12445 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12446 // Function calls
12447 const FunctionDecl *FD = CE->getDirectCallee();
12448 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12449 if (!DiagnosticEmitted) {
12450 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12451 << ConstFunction << FD;
12452 DiagnosticEmitted = true;
12453 }
12454 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12455 diag::note_typecheck_assign_const)
12456 << ConstFunction << FD << FD->getReturnType()
12457 << FD->getReturnTypeSourceRange();
12458 }
12459 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12460 // Point to variable declaration.
12461 if (const ValueDecl *VD = DRE->getDecl()) {
12462 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12463 if (!DiagnosticEmitted) {
12464 S.Diag(Loc, diag::err_typecheck_assign_const)
12465 << ExprRange << ConstVariable << VD << VD->getType();
12466 DiagnosticEmitted = true;
12467 }
12468 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12469 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12470 }
12471 }
12472 } else if (isa<CXXThisExpr>(E)) {
12473 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12474 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12475 if (MD->isConst()) {
12476 if (!DiagnosticEmitted) {
12477 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12478 << ConstMethod << MD;
12479 DiagnosticEmitted = true;
12480 }
12481 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12482 << ConstMethod << MD << MD->getSourceRange();
12483 }
12484 }
12485 }
12486 }
12487
12488 if (DiagnosticEmitted)
12489 return;
12490
12491 // Can't determine a more specific message, so display the generic error.
12492 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12493}
12494
12495enum OriginalExprKind {
12496 OEK_Variable,
12497 OEK_Member,
12498 OEK_LValue
12499};
12500
12501static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12502 const RecordType *Ty,
12503 SourceLocation Loc, SourceRange Range,
12504 OriginalExprKind OEK,
12505 bool &DiagnosticEmitted) {
12506 std::vector<const RecordType *> RecordTypeList;
12507 RecordTypeList.push_back(Ty);
12508 unsigned NextToCheckIndex = 0;
12509 // We walk the record hierarchy breadth-first to ensure that we print
12510 // diagnostics in field nesting order.
12511 while (RecordTypeList.size() > NextToCheckIndex) {
12512 bool IsNested = NextToCheckIndex > 0;
12513 for (const FieldDecl *Field :
12514 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12515 // First, check every field for constness.
12516 QualType FieldTy = Field->getType();
12517 if (FieldTy.isConstQualified()) {
12518 if (!DiagnosticEmitted) {
12519 S.Diag(Loc, diag::err_typecheck_assign_const)
12520 << Range << NestedConstMember << OEK << VD
12521 << IsNested << Field;
12522 DiagnosticEmitted = true;
12523 }
12524 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12525 << NestedConstMember << IsNested << Field
12526 << FieldTy << Field->getSourceRange();
12527 }
12528
12529 // Then we append it to the list to check next in order.
12530 FieldTy = FieldTy.getCanonicalType();
12531 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12532 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12533 RecordTypeList.push_back(FieldRecTy);
12534 }
12535 }
12536 ++NextToCheckIndex;
12537 }
12538}
12539
12540/// Emit an error for the case where a record we are trying to assign to has a
12541/// const-qualified field somewhere in its hierarchy.
12542static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12543 SourceLocation Loc) {
12544 QualType Ty = E->getType();
12545 assert(Ty->isRecordType() && "lvalue was not record?")((Ty->isRecordType() && "lvalue was not record?") ?
static_cast<void> (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12545, __PRETTY_FUNCTION__))
;
12546 SourceRange Range = E->getSourceRange();
12547 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12548 bool DiagEmitted = false;
12549
12550 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12551 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12552 Range, OEK_Member, DiagEmitted);
12553 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12554 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12555 Range, OEK_Variable, DiagEmitted);
12556 else
12557 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12558 Range, OEK_LValue, DiagEmitted);
12559 if (!DiagEmitted)
12560 DiagnoseConstAssignment(S, E, Loc);
12561}
12562
12563/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
12564/// emit an error and return true. If so, return false.
12565static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12566 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))((!E->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast
<void> (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12566, __PRETTY_FUNCTION__))
;
12567
12568 S.CheckShadowingDeclModification(E, Loc);
12569
12570 SourceLocation OrigLoc = Loc;
12571 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12572 &Loc);
12573 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12574 IsLV = Expr::MLV_InvalidMessageExpression;
12575 if (IsLV == Expr::MLV_Valid)
12576 return false;
12577
12578 unsigned DiagID = 0;
12579 bool NeedType = false;
12580 switch (IsLV) { // C99 6.5.16p2
12581 case Expr::MLV_ConstQualified:
12582 // Use a specialized diagnostic when we're assigning to an object
12583 // from an enclosing function or block.
12584 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12585 if (NCCK == NCCK_Block)
12586 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12587 else
12588 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12589 break;
12590 }
12591
12592 // In ARC, use some specialized diagnostics for occasions where we
12593 // infer 'const'. These are always pseudo-strong variables.
12594 if (S.getLangOpts().ObjCAutoRefCount) {
12595 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12596 if (declRef && isa<VarDecl>(declRef->getDecl())) {
12597 VarDecl *var = cast<VarDecl>(declRef->getDecl());
12598
12599 // Use the normal diagnostic if it's pseudo-__strong but the
12600 // user actually wrote 'const'.
12601 if (var->isARCPseudoStrong() &&
12602 (!var->getTypeSourceInfo() ||
12603 !var->getTypeSourceInfo()->getType().isConstQualified())) {
12604 // There are three pseudo-strong cases:
12605 // - self
12606 ObjCMethodDecl *method = S.getCurMethodDecl();
12607 if (method && var == method->getSelfDecl()) {
12608 DiagID = method->isClassMethod()
12609 ? diag::err_typecheck_arc_assign_self_class_method
12610 : diag::err_typecheck_arc_assign_self;
12611
12612 // - Objective-C externally_retained attribute.
12613 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12614 isa<ParmVarDecl>(var)) {
12615 DiagID = diag::err_typecheck_arc_assign_externally_retained;
12616
12617 // - fast enumeration variables
12618 } else {
12619 DiagID = diag::err_typecheck_arr_assign_enumeration;
12620 }
12621
12622 SourceRange Assign;
12623 if (Loc != OrigLoc)
12624 Assign = SourceRange(OrigLoc, OrigLoc);
12625 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12626 // We need to preserve the AST regardless, so migration tool
12627 // can do its job.
12628 return false;
12629 }
12630 }
12631 }
12632
12633 // If none of the special cases above are triggered, then this is a
12634 // simple const assignment.
12635 if (DiagID == 0) {
12636 DiagnoseConstAssignment(S, E, Loc);
12637 return true;
12638 }
12639
12640 break;
12641 case Expr::MLV_ConstAddrSpace:
12642 DiagnoseConstAssignment(S, E, Loc);
12643 return true;
12644 case Expr::MLV_ConstQualifiedField:
12645 DiagnoseRecursiveConstFields(S, E, Loc);
12646 return true;
12647 case Expr::MLV_ArrayType:
12648 case Expr::MLV_ArrayTemporary:
12649 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12650 NeedType = true;
12651 break;
12652 case Expr::MLV_NotObjectType:
12653 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12654 NeedType = true;
12655 break;
12656 case Expr::MLV_LValueCast:
12657 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12658 break;
12659 case Expr::MLV_Valid:
12660 llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12660)
;
12661 case Expr::MLV_InvalidExpression:
12662 case Expr::MLV_MemberFunction:
12663 case Expr::MLV_ClassTemporary:
12664 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12665 break;
12666 case Expr::MLV_IncompleteType:
12667 case Expr::MLV_IncompleteVoidType:
12668 return S.RequireCompleteType(Loc, E->getType(),
12669 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12670 case Expr::MLV_DuplicateVectorComponents:
12671 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12672 break;
12673 case Expr::MLV_NoSetterProperty:
12674 llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12674)
;
12675 case Expr::MLV_InvalidMessageExpression:
12676 DiagID = diag::err_readonly_message_assignment;
12677 break;
12678 case Expr::MLV_SubObjCPropertySetting:
12679 DiagID = diag::err_no_subobject_property_setting;
12680 break;
12681 }
12682
12683 SourceRange Assign;
12684 if (Loc != OrigLoc)
12685 Assign = SourceRange(OrigLoc, OrigLoc);
12686 if (NeedType)
12687 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12688 else
12689 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12690 return true;
12691}
12692
12693static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12694 SourceLocation Loc,
12695 Sema &Sema) {
12696 if (Sema.inTemplateInstantiation())
12697 return;
12698 if (Sema.isUnevaluatedContext())
12699 return;
12700 if (Loc.isInvalid() || Loc.isMacroID())
12701 return;
12702 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12703 return;
12704
12705 // C / C++ fields
12706 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12707 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12708 if (ML && MR) {
12709 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12710 return;
12711 const ValueDecl *LHSDecl =
12712 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12713 const ValueDecl *RHSDecl =
12714 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12715 if (LHSDecl != RHSDecl)
12716 return;
12717 if (LHSDecl->getType().isVolatileQualified())
12718 return;
12719 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12720 if (RefTy->getPointeeType().isVolatileQualified())
12721 return;
12722
12723 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12724 }
12725
12726 // Objective-C instance variables
12727 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12728 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12729 if (OL && OR && OL->getDecl() == OR->getDecl()) {
12730 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12731 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12732 if (RL && RR && RL->getDecl() == RR->getDecl())
12733 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12734 }
12735}
12736
12737// C99 6.5.16.1
12738QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12739 SourceLocation Loc,
12740 QualType CompoundType) {
12741 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))((!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))
? static_cast<void> (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12741, __PRETTY_FUNCTION__))
;
12742
12743 // Verify that LHS is a modifiable lvalue, and emit error if not.
12744 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12745 return QualType();
12746
12747 QualType LHSType = LHSExpr->getType();
12748 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12749 CompoundType;
12750 // OpenCL v1.2 s6.1.1.1 p2:
12751 // The half data type can only be used to declare a pointer to a buffer that
12752 // contains half values
12753 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12754 LHSType->isHalfType()) {
12755 Diag(Loc, diag::err_opencl_half_load_store) << 1
12756 << LHSType.getUnqualifiedType();
12757 return QualType();
12758 }
12759
12760 AssignConvertType ConvTy;
12761 if (CompoundType.isNull()) {
12762 Expr *RHSCheck = RHS.get();
12763
12764 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12765
12766 QualType LHSTy(LHSType);
12767 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12768 if (RHS.isInvalid())
12769 return QualType();
12770 // Special case of NSObject attributes on c-style pointer types.
12771 if (ConvTy == IncompatiblePointer &&
12772 ((Context.isObjCNSObjectType(LHSType) &&
12773 RHSType->isObjCObjectPointerType()) ||
12774 (Context.isObjCNSObjectType(RHSType) &&
12775 LHSType->isObjCObjectPointerType())))
12776 ConvTy = Compatible;
12777
12778 if (ConvTy == Compatible &&
12779 LHSType->isObjCObjectType())
12780 Diag(Loc, diag::err_objc_object_assignment)
12781 << LHSType;
12782
12783 // If the RHS is a unary plus or minus, check to see if they = and + are
12784 // right next to each other. If so, the user may have typo'd "x =+ 4"
12785 // instead of "x += 4".
12786 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12787 RHSCheck = ICE->getSubExpr();
12788 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12789 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12790 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12791 // Only if the two operators are exactly adjacent.
12792 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12793 // And there is a space or other character before the subexpr of the
12794 // unary +/-. We don't want to warn on "x=-1".
12795 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12796 UO->getSubExpr()->getBeginLoc().isFileID()) {
12797 Diag(Loc, diag::warn_not_compound_assign)
12798 << (UO->getOpcode() == UO_Plus ? "+" : "-")
12799 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12800 }
12801 }
12802
12803 if (ConvTy == Compatible) {
12804 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12805 // Warn about retain cycles where a block captures the LHS, but
12806 // not if the LHS is a simple variable into which the block is
12807 // being stored...unless that variable can be captured by reference!
12808 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12809 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12810 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12811 checkRetainCycles(LHSExpr, RHS.get());
12812 }
12813
12814 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12815 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12816 // It is safe to assign a weak reference into a strong variable.
12817 // Although this code can still have problems:
12818 // id x = self.weakProp;
12819 // id y = self.weakProp;
12820 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12821 // paths through the function. This should be revisited if
12822 // -Wrepeated-use-of-weak is made flow-sensitive.
12823 // For ObjCWeak only, we do not warn if the assign is to a non-weak
12824 // variable, which will be valid for the current autorelease scope.
12825 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12826 RHS.get()->getBeginLoc()))
12827 getCurFunction()->markSafeWeakUse(RHS.get());
12828
12829 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12830 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12831 }
12832 }
12833 } else {
12834 // Compound assignment "x += y"
12835 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12836 }
12837
12838 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12839 RHS.get(), AA_Assigning))
12840 return QualType();
12841
12842 CheckForNullPointerDereference(*this, LHSExpr);
12843
12844 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12845 if (CompoundType.isNull()) {
12846 // C++2a [expr.ass]p5:
12847 // A simple-assignment whose left operand is of a volatile-qualified
12848 // type is deprecated unless the assignment is either a discarded-value
12849 // expression or an unevaluated operand
12850 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12851 } else {
12852 // C++2a [expr.ass]p6:
12853 // [Compound-assignment] expressions are deprecated if E1 has
12854 // volatile-qualified type
12855 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12856 }
12857 }
12858
12859 // C99 6.5.16p3: The type of an assignment expression is the type of the
12860 // left operand unless the left operand has qualified type, in which case
12861 // it is the unqualified version of the type of the left operand.
12862 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12863 // is converted to the type of the assignment expression (above).
12864 // C++ 5.17p1: the type of the assignment expression is that of its left
12865 // operand.
12866 return (getLangOpts().CPlusPlus
12867 ? LHSType : LHSType.getUnqualifiedType());
12868}
12869
12870// Only ignore explicit casts to void.
12871static bool IgnoreCommaOperand(const Expr *E) {
12872 E = E->IgnoreParens();
12873
12874 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12875 if (CE->getCastKind() == CK_ToVoid) {
12876 return true;
12877 }
12878
12879 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12880 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12881 CE->getSubExpr()->getType()->isDependentType()) {
12882 return true;
12883 }
12884 }
12885
12886 return false;
12887}
12888
12889// Look for instances where it is likely the comma operator is confused with
12890// another operator. There is an explicit list of acceptable expressions for
12891// the left hand side of the comma operator, otherwise emit a warning.
12892void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12893 // No warnings in macros
12894 if (Loc.isMacroID())
12895 return;
12896
12897 // Don't warn in template instantiations.
12898 if (inTemplateInstantiation())
12899 return;
12900
12901 // Scope isn't fine-grained enough to explicitly list the specific cases, so
12902 // instead, skip more than needed, then call back into here with the
12903 // CommaVisitor in SemaStmt.cpp.
12904 // The listed locations are the initialization and increment portions
12905 // of a for loop. The additional checks are on the condition of
12906 // if statements, do/while loops, and for loops.
12907 // Differences in scope flags for C89 mode requires the extra logic.
12908 const unsigned ForIncrementFlags =
12909 getLangOpts().C99 || getLangOpts().CPlusPlus
12910 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12911 : Scope::ContinueScope | Scope::BreakScope;
12912 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12913 const unsigned ScopeFlags = getCurScope()->getFlags();
12914 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12915 (ScopeFlags & ForInitFlags) == ForInitFlags)
12916 return;
12917
12918 // If there are multiple comma operators used together, get the RHS of the
12919 // of the comma operator as the LHS.
12920 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12921 if (BO->getOpcode() != BO_Comma)
12922 break;
12923 LHS = BO->getRHS();
12924 }
12925
12926 // Only allow some expressions on LHS to not warn.
12927 if (IgnoreCommaOperand(LHS))
12928 return;
12929
12930 Diag(Loc, diag::warn_comma_operator);
12931 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12932 << LHS->getSourceRange()
12933 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12934 LangOpts.CPlusPlus ? "static_cast<void>("
12935 : "(void)(")
12936 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12937 ")");
12938}
12939
12940// C99 6.5.17
12941static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12942 SourceLocation Loc) {
12943 LHS = S.CheckPlaceholderExpr(LHS.get());
12944 RHS = S.CheckPlaceholderExpr(RHS.get());
12945 if (LHS.isInvalid() || RHS.isInvalid())
12946 return QualType();
12947
12948 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12949 // operands, but not unary promotions.
12950 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12951
12952 // So we treat the LHS as a ignored value, and in C++ we allow the
12953 // containing site to determine what should be done with the RHS.
12954 LHS = S.IgnoredValueConversions(LHS.get());
12955 if (LHS.isInvalid())
12956 return QualType();
12957
12958 S.DiagnoseUnusedExprResult(LHS.get());
12959
12960 if (!S.getLangOpts().CPlusPlus) {
12961 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12962 if (RHS.isInvalid())
12963 return QualType();
12964 if (!RHS.get()->getType()->isVoidType())
12965 S.RequireCompleteType(Loc, RHS.get()->getType(),
12966 diag::err_incomplete_type);
12967 }
12968
12969 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12970 S.DiagnoseCommaOperator(LHS.get(), Loc);
12971
12972 return RHS.get()->getType();
12973}
12974
12975/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12976/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12977static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12978 ExprValueKind &VK,
12979 ExprObjectKind &OK,
12980 SourceLocation OpLoc,
12981 bool IsInc, bool IsPrefix) {
12982 if (Op->isTypeDependent())
12983 return S.Context.DependentTy;
12984
12985 QualType ResType = Op->getType();
12986 // Atomic types can be used for increment / decrement where the non-atomic
12987 // versions can, so ignore the _Atomic() specifier for the purpose of
12988 // checking.
12989 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12990 ResType = ResAtomicType->getValueType();
12991
12992 assert(!ResType.isNull() && "no type for increment/decrement expression")((!ResType.isNull() && "no type for increment/decrement expression"
) ? static_cast<void> (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 12992, __PRETTY_FUNCTION__))
;
12993
12994 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12995 // Decrement of bool is not allowed.
12996 if (!IsInc) {
12997 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12998 return QualType();
12999 }
13000 // Increment of bool sets it to true, but is deprecated.
13001 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13002 : diag::warn_increment_bool)
13003 << Op->getSourceRange();
13004 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13005 // Error on enum increments and decrements in C++ mode
13006 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13007 return QualType();
13008 } else if (ResType->isRealType()) {
13009 // OK!
13010 } else if (ResType->isPointerType()) {
13011 // C99 6.5.2.4p2, 6.5.6p2
13012 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13013 return QualType();
13014 } else if (ResType->isObjCObjectPointerType()) {
13015 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13016 // Otherwise, we just need a complete type.
13017 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13018 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13019 return QualType();
13020 } else if (ResType->isAnyComplexType()) {
13021 // C99 does not support ++/-- on complex types, we allow as an extension.
13022 S.Diag(OpLoc, diag::ext_integer_increment_complex)
13023 << ResType << Op->getSourceRange();
13024 } else if (ResType->isPlaceholderType()) {
13025 ExprResult PR = S.CheckPlaceholderExpr(Op);
13026 if (PR.isInvalid()) return QualType();
13027 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13028 IsInc, IsPrefix);
13029 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13030 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13031 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13032 (ResType->castAs<VectorType>()->getVectorKind() !=
13033 VectorType::AltiVecBool)) {
13034 // The z vector extensions allow ++ and -- for non-bool vectors.
13035 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13036 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13037 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13038 } else {
13039 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13040 << ResType << int(IsInc) << Op->getSourceRange();
13041 return QualType();
13042 }
13043 // At this point, we know we have a real, complex or pointer type.
13044 // Now make sure the operand is a modifiable lvalue.
13045 if (CheckForModifiableLvalue(Op, OpLoc, S))
13046 return QualType();
13047 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13048 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13049 // An operand with volatile-qualified type is deprecated
13050 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13051 << IsInc << ResType;
13052 }
13053 // In C++, a prefix increment is the same type as the operand. Otherwise
13054 // (in C or with postfix), the increment is the unqualified type of the
13055 // operand.
13056 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13057 VK = VK_LValue;
13058 OK = Op->getObjectKind();
13059 return ResType;
13060 } else {
13061 VK = VK_RValue;
13062 return ResType.getUnqualifiedType();
13063 }
13064}
13065
13066
13067/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13068/// This routine allows us to typecheck complex/recursive expressions
13069/// where the declaration is needed for type checking. We only need to
13070/// handle cases when the expression references a function designator
13071/// or is an lvalue. Here are some examples:
13072/// - &(x) => x
13073/// - &*****f => f for f a function designator.
13074/// - &s.xx => s
13075/// - &s.zz[1].yy -> s, if zz is an array
13076/// - *(x + 1) -> x, if x is an array
13077/// - &"123"[2] -> 0
13078/// - & __real__ x -> x
13079///
13080/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13081/// members.
13082static ValueDecl *getPrimaryDecl(Expr *E) {
13083 switch (E->getStmtClass()) {
13084 case Stmt::DeclRefExprClass:
13085 return cast<DeclRefExpr>(E)->getDecl();
13086 case Stmt::MemberExprClass:
13087 // If this is an arrow operator, the address is an offset from
13088 // the base's value, so the object the base refers to is
13089 // irrelevant.
13090 if (cast<MemberExpr>(E)->isArrow())
13091 return nullptr;
13092 // Otherwise, the expression refers to a part of the base
13093 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13094 case Stmt::ArraySubscriptExprClass: {
13095 // FIXME: This code shouldn't be necessary! We should catch the implicit
13096 // promotion of register arrays earlier.
13097 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13098 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13099 if (ICE->getSubExpr()->getType()->isArrayType())
13100 return getPrimaryDecl(ICE->getSubExpr());
13101 }
13102 return nullptr;
13103 }
13104 case Stmt::UnaryOperatorClass: {
13105 UnaryOperator *UO = cast<UnaryOperator>(E);
13106
13107 switch(UO->getOpcode()) {
13108 case UO_Real:
13109 case UO_Imag:
13110 case UO_Extension:
13111 return getPrimaryDecl(UO->getSubExpr());
13112 default:
13113 return nullptr;
13114 }
13115 }
13116 case Stmt::ParenExprClass:
13117 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13118 case Stmt::ImplicitCastExprClass:
13119 // If the result of an implicit cast is an l-value, we care about
13120 // the sub-expression; otherwise, the result here doesn't matter.
13121 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13122 case Stmt::CXXUuidofExprClass:
13123 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13124 default:
13125 return nullptr;
13126 }
13127}
13128
13129namespace {
13130enum {
13131 AO_Bit_Field = 0,
13132 AO_Vector_Element = 1,
13133 AO_Property_Expansion = 2,
13134 AO_Register_Variable = 3,
13135 AO_Matrix_Element = 4,
13136 AO_No_Error = 5
13137};
13138}
13139/// Diagnose invalid operand for address of operations.
13140///
13141/// \param Type The type of operand which cannot have its address taken.
13142static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13143 Expr *E, unsigned Type) {
13144 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13145}
13146
13147/// CheckAddressOfOperand - The operand of & must be either a function
13148/// designator or an lvalue designating an object. If it is an lvalue, the
13149/// object cannot be declared with storage class register or be a bit field.
13150/// Note: The usual conversions are *not* applied to the operand of the &
13151/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13152/// In C++, the operand might be an overloaded function name, in which case
13153/// we allow the '&' but retain the overloaded-function type.
13154QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13155 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13156 if (PTy->getKind() == BuiltinType::Overload) {
13157 Expr *E = OrigOp.get()->IgnoreParens();
13158 if (!isa<OverloadExpr>(E)) {
13159 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)((cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) ?
static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13159, __PRETTY_FUNCTION__))
;
13160 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13161 << OrigOp.get()->getSourceRange();
13162 return QualType();
13163 }
13164
13165 OverloadExpr *Ovl = cast<OverloadExpr>(E);
13166 if (isa<UnresolvedMemberExpr>(Ovl))
13167 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13168 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13169 << OrigOp.get()->getSourceRange();
13170 return QualType();
13171 }
13172
13173 return Context.OverloadTy;
13174 }
13175
13176 if (PTy->getKind() == BuiltinType::UnknownAny)
13177 return Context.UnknownAnyTy;
13178
13179 if (PTy->getKind() == BuiltinType::BoundMember) {
13180 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13181 << OrigOp.get()->getSourceRange();
13182 return QualType();
13183 }
13184
13185 OrigOp = CheckPlaceholderExpr(OrigOp.get());
13186 if (OrigOp.isInvalid()) return QualType();
13187 }
13188
13189 if (OrigOp.get()->isTypeDependent())
13190 return Context.DependentTy;
13191
13192 assert(!OrigOp.get()->getType()->isPlaceholderType())((!OrigOp.get()->getType()->isPlaceholderType()) ? static_cast
<void> (0) : __assert_fail ("!OrigOp.get()->getType()->isPlaceholderType()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13192, __PRETTY_FUNCTION__))
;
13193
13194 // Make sure to ignore parentheses in subsequent checks
13195 Expr *op = OrigOp.get()->IgnoreParens();
13196
13197 // In OpenCL captures for blocks called as lambda functions
13198 // are located in the private address space. Blocks used in
13199 // enqueue_kernel can be located in a different address space
13200 // depending on a vendor implementation. Thus preventing
13201 // taking an address of the capture to avoid invalid AS casts.
13202 if (LangOpts.OpenCL) {
13203 auto* VarRef = dyn_cast<DeclRefExpr>(op);
13204 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13205 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13206 return QualType();
13207 }
13208 }
13209
13210 if (getLangOpts().C99) {
13211 // Implement C99-only parts of addressof rules.
13212 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13213 if (uOp->getOpcode() == UO_Deref)
13214 // Per C99 6.5.3.2, the address of a deref always returns a valid result
13215 // (assuming the deref expression is valid).
13216 return uOp->getSubExpr()->getType();
13217 }
13218 // Technically, there should be a check for array subscript
13219 // expressions here, but the result of one is always an lvalue anyway.
13220 }
13221 ValueDecl *dcl = getPrimaryDecl(op);
13222
13223 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13224 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13225 op->getBeginLoc()))
13226 return QualType();
13227
13228 Expr::LValueClassification lval = op->ClassifyLValue(Context);
13229 unsigned AddressOfError = AO_No_Error;
13230
13231 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13232 bool sfinae = (bool)isSFINAEContext();
13233 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13234 : diag::ext_typecheck_addrof_temporary)
13235 << op->getType() << op->getSourceRange();
13236 if (sfinae)
13237 return QualType();
13238 // Materialize the temporary as an lvalue so that we can take its address.
13239 OrigOp = op =
13240 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13241 } else if (isa<ObjCSelectorExpr>(op)) {
13242 return Context.getPointerType(op->getType());
13243 } else if (lval == Expr::LV_MemberFunction) {
13244 // If it's an instance method, make a member pointer.
13245 // The expression must have exactly the form &A::foo.
13246
13247 // If the underlying expression isn't a decl ref, give up.
13248 if (!isa<DeclRefExpr>(op)) {
13249 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13250 << OrigOp.get()->getSourceRange();
13251 return QualType();
13252 }
13253 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13254 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13255
13256 // The id-expression was parenthesized.
13257 if (OrigOp.get() != DRE) {
13258 Diag(OpLoc, diag::err_parens_pointer_member_function)
13259 << OrigOp.get()->getSourceRange();
13260
13261 // The method was named without a qualifier.
13262 } else if (!DRE->getQualifier()) {
13263 if (MD->getParent()->getName().empty())
13264 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13265 << op->getSourceRange();
13266 else {
13267 SmallString<32> Str;
13268 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13269 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13270 << op->getSourceRange()
13271 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13272 }
13273 }
13274
13275 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13276 if (isa<CXXDestructorDecl>(MD))
13277 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13278
13279 QualType MPTy = Context.getMemberPointerType(
13280 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13281 // Under the MS ABI, lock down the inheritance model now.
13282 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13283 (void)isCompleteType(OpLoc, MPTy);
13284 return MPTy;
13285 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13286 // C99 6.5.3.2p1
13287 // The operand must be either an l-value or a function designator
13288 if (!op->getType()->isFunctionType()) {
13289 // Use a special diagnostic for loads from property references.
13290 if (isa<PseudoObjectExpr>(op)) {
13291 AddressOfError = AO_Property_Expansion;
13292 } else {
13293 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13294 << op->getType() << op->getSourceRange();
13295 return QualType();
13296 }
13297 }
13298 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13299 // The operand cannot be a bit-field
13300 AddressOfError = AO_Bit_Field;
13301 } else if (op->getObjectKind() == OK_VectorComponent) {
13302 // The operand cannot be an element of a vector
13303 AddressOfError = AO_Vector_Element;
13304 } else if (op->getObjectKind() == OK_MatrixComponent) {
13305 // The operand cannot be an element of a matrix.
13306 AddressOfError = AO_Matrix_Element;
13307 } else if (dcl) { // C99 6.5.3.2p1
13308 // We have an lvalue with a decl. Make sure the decl is not declared
13309 // with the register storage-class specifier.
13310 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13311 // in C++ it is not error to take address of a register
13312 // variable (c++03 7.1.1P3)
13313 if (vd->getStorageClass() == SC_Register &&
13314 !getLangOpts().CPlusPlus) {
13315 AddressOfError = AO_Register_Variable;
13316 }
13317 } else if (isa<MSPropertyDecl>(dcl)) {
13318 AddressOfError = AO_Property_Expansion;
13319 } else if (isa<FunctionTemplateDecl>(dcl)) {
13320 return Context.OverloadTy;
13321 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13322 // Okay: we can take the address of a field.
13323 // Could be a pointer to member, though, if there is an explicit
13324 // scope qualifier for the class.
13325 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13326 DeclContext *Ctx = dcl->getDeclContext();
13327 if (Ctx && Ctx->isRecord()) {
13328 if (dcl->getType()->isReferenceType()) {
13329 Diag(OpLoc,
13330 diag::err_cannot_form_pointer_to_member_of_reference_type)
13331 << dcl->getDeclName() << dcl->getType();
13332 return QualType();
13333 }
13334
13335 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13336 Ctx = Ctx->getParent();
13337
13338 QualType MPTy = Context.getMemberPointerType(
13339 op->getType(),
13340 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13341 // Under the MS ABI, lock down the inheritance model now.
13342 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13343 (void)isCompleteType(OpLoc, MPTy);
13344 return MPTy;
13345 }
13346 }
13347 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13348 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13349 llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13349)
;
13350 }
13351
13352 if (AddressOfError != AO_No_Error) {
13353 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13354 return QualType();
13355 }
13356
13357 if (lval == Expr::LV_IncompleteVoidType) {
13358 // Taking the address of a void variable is technically illegal, but we
13359 // allow it in cases which are otherwise valid.
13360 // Example: "extern void x; void* y = &x;".
13361 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13362 }
13363
13364 // If the operand has type "type", the result has type "pointer to type".
13365 if (op->getType()->isObjCObjectType())
13366 return Context.getObjCObjectPointerType(op->getType());
13367
13368 CheckAddressOfPackedMember(op);
13369
13370 return Context.getPointerType(op->getType());
13371}
13372
13373static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13374 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13375 if (!DRE)
13376 return;
13377 const Decl *D = DRE->getDecl();
13378 if (!D)
13379 return;
13380 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13381 if (!Param)
13382 return;
13383 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13384 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13385 return;
13386 if (FunctionScopeInfo *FD = S.getCurFunction())
13387 if (!FD->ModifiedNonNullParams.count(Param))
13388 FD->ModifiedNonNullParams.insert(Param);
13389}
13390
13391/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13392static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13393 SourceLocation OpLoc) {
13394 if (Op->isTypeDependent())
13395 return S.Context.DependentTy;
13396
13397 ExprResult ConvResult = S.UsualUnaryConversions(Op);
13398 if (ConvResult.isInvalid())
13399 return QualType();
13400 Op = ConvResult.get();
13401 QualType OpTy = Op->getType();
13402 QualType Result;
13403
13404 if (isa<CXXReinterpretCastExpr>(Op)) {
13405 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13406 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13407 Op->getSourceRange());
13408 }
13409
13410 if (const PointerType *PT = OpTy->getAs<PointerType>())
13411 {
13412 Result = PT->getPointeeType();
13413 }
13414 else if (const ObjCObjectPointerType *OPT =
13415 OpTy->getAs<ObjCObjectPointerType>())
13416 Result = OPT->getPointeeType();
13417 else {
13418 ExprResult PR = S.CheckPlaceholderExpr(Op);
13419 if (PR.isInvalid()) return QualType();
13420 if (PR.get() != Op)
13421 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13422 }
13423
13424 if (Result.isNull()) {
13425 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13426 << OpTy << Op->getSourceRange();
13427 return QualType();
13428 }
13429
13430 // Note that per both C89 and C99, indirection is always legal, even if Result
13431 // is an incomplete type or void. It would be possible to warn about
13432 // dereferencing a void pointer, but it's completely well-defined, and such a
13433 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13434 // for pointers to 'void' but is fine for any other pointer type:
13435 //
13436 // C++ [expr.unary.op]p1:
13437 // [...] the expression to which [the unary * operator] is applied shall
13438 // be a pointer to an object type, or a pointer to a function type
13439 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13440 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13441 << OpTy << Op->getSourceRange();
13442
13443 // Dereferences are usually l-values...
13444 VK = VK_LValue;
13445
13446 // ...except that certain expressions are never l-values in C.
13447 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13448 VK = VK_RValue;
13449
13450 return Result;
13451}
13452
13453BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13454 BinaryOperatorKind Opc;
13455 switch (Kind) {
13456 default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13456)
;
13457 case tok::periodstar: Opc = BO_PtrMemD; break;
13458 case tok::arrowstar: Opc = BO_PtrMemI; break;
13459 case tok::star: Opc = BO_Mul; break;
13460 case tok::slash: Opc = BO_Div; break;
13461 case tok::percent: Opc = BO_Rem; break;
13462 case tok::plus: Opc = BO_Add; break;
13463 case tok::minus: Opc = BO_Sub; break;
13464 case tok::lessless: Opc = BO_Shl; break;
13465 case tok::greatergreater: Opc = BO_Shr; break;
13466 case tok::lessequal: Opc = BO_LE; break;
13467 case tok::less: Opc = BO_LT; break;
13468 case tok::greaterequal: Opc = BO_GE; break;
13469 case tok::greater: Opc = BO_GT; break;
13470 case tok::exclaimequal: Opc = BO_NE; break;
13471 case tok::equalequal: Opc = BO_EQ; break;
13472 case tok::spaceship: Opc = BO_Cmp; break;
13473 case tok::amp: Opc = BO_And; break;
13474 case tok::caret: Opc = BO_Xor; break;
13475 case tok::pipe: Opc = BO_Or; break;
13476 case tok::ampamp: Opc = BO_LAnd; break;
13477 case tok::pipepipe: Opc = BO_LOr; break;
13478 case tok::equal: Opc = BO_Assign; break;
13479 case tok::starequal: Opc = BO_MulAssign; break;
13480 case tok::slashequal: Opc = BO_DivAssign; break;
13481 case tok::percentequal: Opc = BO_RemAssign; break;
13482 case tok::plusequal: Opc = BO_AddAssign; break;
13483 case tok::minusequal: Opc = BO_SubAssign; break;
13484 case tok::lesslessequal: Opc = BO_ShlAssign; break;
13485 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
13486 case tok::ampequal: Opc = BO_AndAssign; break;
13487 case tok::caretequal: Opc = BO_XorAssign; break;
13488 case tok::pipeequal: Opc = BO_OrAssign; break;
13489 case tok::comma: Opc = BO_Comma; break;
13490 }
13491 return Opc;
13492}
13493
13494static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13495 tok::TokenKind Kind) {
13496 UnaryOperatorKind Opc;
13497 switch (Kind) {
13498 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13498)
;
13499 case tok::plusplus: Opc = UO_PreInc; break;
13500 case tok::minusminus: Opc = UO_PreDec; break;
13501 case tok::amp: Opc = UO_AddrOf; break;
13502 case tok::star: Opc = UO_Deref; break;
13503 case tok::plus: Opc = UO_Plus; break;
13504 case tok::minus: Opc = UO_Minus; break;
13505 case tok::tilde: Opc = UO_Not; break;
13506 case tok::exclaim: Opc = UO_LNot; break;
13507 case tok::kw___real: Opc = UO_Real; break;
13508 case tok::kw___imag: Opc = UO_Imag; break;
13509 case tok::kw___extension__: Opc = UO_Extension; break;
13510 }
13511 return Opc;
13512}
13513
13514/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13515/// This warning suppressed in the event of macro expansions.
13516static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13517 SourceLocation OpLoc, bool IsBuiltin) {
13518 if (S.inTemplateInstantiation())
13519 return;
13520 if (S.isUnevaluatedContext())
13521 return;
13522 if (OpLoc.isInvalid() || OpLoc.isMacroID())
13523 return;
13524 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13525 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13526 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13527 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13528 if (!LHSDeclRef || !RHSDeclRef ||
13529 LHSDeclRef->getLocation().isMacroID() ||
13530 RHSDeclRef->getLocation().isMacroID())
13531 return;
13532 const ValueDecl *LHSDecl =
13533 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13534 const ValueDecl *RHSDecl =
13535 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13536 if (LHSDecl != RHSDecl)
13537 return;
13538 if (LHSDecl->getType().isVolatileQualified())
13539 return;
13540 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13541 if (RefTy->getPointeeType().isVolatileQualified())
13542 return;
13543
13544 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13545 : diag::warn_self_assignment_overloaded)
13546 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13547 << RHSExpr->getSourceRange();
13548}
13549
13550/// Check if a bitwise-& is performed on an Objective-C pointer. This
13551/// is usually indicative of introspection within the Objective-C pointer.
13552static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13553 SourceLocation OpLoc) {
13554 if (!S.getLangOpts().ObjC)
13555 return;
13556
13557 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13558 const Expr *LHS = L.get();
13559 const Expr *RHS = R.get();
13560
13561 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13562 ObjCPointerExpr = LHS;
13563 OtherExpr = RHS;
13564 }
13565 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13566 ObjCPointerExpr = RHS;
13567 OtherExpr = LHS;
13568 }
13569
13570 // This warning is deliberately made very specific to reduce false
13571 // positives with logic that uses '&' for hashing. This logic mainly
13572 // looks for code trying to introspect into tagged pointers, which
13573 // code should generally never do.
13574 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13575 unsigned Diag = diag::warn_objc_pointer_masking;
13576 // Determine if we are introspecting the result of performSelectorXXX.
13577 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13578 // Special case messages to -performSelector and friends, which
13579 // can return non-pointer values boxed in a pointer value.
13580 // Some clients may wish to silence warnings in this subcase.
13581 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13582 Selector S = ME->getSelector();
13583 StringRef SelArg0 = S.getNameForSlot(0);
13584 if (SelArg0.startswith("performSelector"))
13585 Diag = diag::warn_objc_pointer_masking_performSelector;
13586 }
13587
13588 S.Diag(OpLoc, Diag)
13589 << ObjCPointerExpr->getSourceRange();
13590 }
13591}
13592
13593static NamedDecl *getDeclFromExpr(Expr *E) {
13594 if (!E)
13595 return nullptr;
13596 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13597 return DRE->getDecl();
13598 if (auto *ME = dyn_cast<MemberExpr>(E))
13599 return ME->getMemberDecl();
13600 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13601 return IRE->getDecl();
13602 return nullptr;
13603}
13604
13605// This helper function promotes a binary operator's operands (which are of a
13606// half vector type) to a vector of floats and then truncates the result to
13607// a vector of either half or short.
13608static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13609 BinaryOperatorKind Opc, QualType ResultTy,
13610 ExprValueKind VK, ExprObjectKind OK,
13611 bool IsCompAssign, SourceLocation OpLoc,
13612 FPOptionsOverride FPFeatures) {
13613 auto &Context = S.getASTContext();
13614 assert((isVector(ResultTy, Context.HalfTy) ||(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context
.ShortTy)) && "Result must be a vector of half or short"
) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13616, __PRETTY_FUNCTION__))
13615 isVector(ResultTy, Context.ShortTy)) &&(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context
.ShortTy)) && "Result must be a vector of half or short"
) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13616, __PRETTY_FUNCTION__))
13616 "Result must be a vector of half or short")(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context
.ShortTy)) && "Result must be a vector of half or short"
) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13616, __PRETTY_FUNCTION__))
;
13617 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) &&
isVector(RHS.get()->getType(), Context.HalfTy) &&
"both operands expected to be a half vector") ? static_cast<
void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13619, __PRETTY_FUNCTION__))
13618 isVector(RHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) &&
isVector(RHS.get()->getType(), Context.HalfTy) &&
"both operands expected to be a half vector") ? static_cast<
void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13619, __PRETTY_FUNCTION__))
13619 "both operands expected to be a half vector")((isVector(LHS.get()->getType(), Context.HalfTy) &&
isVector(RHS.get()->getType(), Context.HalfTy) &&
"both operands expected to be a half vector") ? static_cast<
void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13619, __PRETTY_FUNCTION__))
;
13620
13621 RHS = convertVector(RHS.get(), Context.FloatTy, S);
13622 QualType BinOpResTy = RHS.get()->getType();
13623
13624 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13625 // change BinOpResTy to a vector of ints.
13626 if (isVector(ResultTy, Context.ShortTy))
13627 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13628
13629 if (IsCompAssign)
13630 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13631 ResultTy, VK, OK, OpLoc, FPFeatures,
13632 BinOpResTy, BinOpResTy);
13633
13634 LHS = convertVector(LHS.get(), Context.FloatTy, S);
13635 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13636 BinOpResTy, VK, OK, OpLoc, FPFeatures);
13637 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13638}
13639
13640static std::pair<ExprResult, ExprResult>
13641CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13642 Expr *RHSExpr) {
13643 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13644 if (!S.getLangOpts().CPlusPlus) {
13645 // C cannot handle TypoExpr nodes on either side of a binop because it
13646 // doesn't handle dependent types properly, so make sure any TypoExprs have
13647 // been dealt with before checking the operands.
13648 LHS = S.CorrectDelayedTyposInExpr(LHS);
13649 RHS = S.CorrectDelayedTyposInExpr(
13650 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13651 [Opc, LHS](Expr *E) {
13652 if (Opc != BO_Assign)
13653 return ExprResult(E);
13654 // Avoid correcting the RHS to the same Expr as the LHS.
13655 Decl *D = getDeclFromExpr(E);
13656 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13657 });
13658 }
13659 return std::make_pair(LHS, RHS);
13660}
13661
13662/// Returns true if conversion between vectors of halfs and vectors of floats
13663/// is needed.
13664static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13665 Expr *E0, Expr *E1 = nullptr) {
13666 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13667 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13668 return false;
13669
13670 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13671 QualType Ty = E->IgnoreImplicit()->getType();
13672
13673 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13674 // to vectors of floats. Although the element type of the vectors is __fp16,
13675 // the vectors shouldn't be treated as storage-only types. See the
13676 // discussion here: https://reviews.llvm.org/rG825235c140e7
13677 if (const VectorType *VT = Ty->getAs<VectorType>()) {
13678 if (VT->getVectorKind() == VectorType::NeonVector)
13679 return false;
13680 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13681 }
13682 return false;
13683 };
13684
13685 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13686}
13687
13688/// CreateBuiltinBinOp - Creates a new built-in binary operation with
13689/// operator @p Opc at location @c TokLoc. This routine only supports
13690/// built-in operations; ActOnBinOp handles overloaded operators.
13691ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13692 BinaryOperatorKind Opc,
13693 Expr *LHSExpr, Expr *RHSExpr) {
13694 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13695 // The syntax only allows initializer lists on the RHS of assignment,
13696 // so we don't need to worry about accepting invalid code for
13697 // non-assignment operators.
13698 // C++11 5.17p9:
13699 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13700 // of x = {} is x = T().
13701 InitializationKind Kind = InitializationKind::CreateDirectList(
13702 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13703 InitializedEntity Entity =
13704 InitializedEntity::InitializeTemporary(LHSExpr->getType());
13705 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13706 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13707 if (Init.isInvalid())
13708 return Init;
13709 RHSExpr = Init.get();
13710 }
13711
13712 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13713 QualType ResultTy; // Result type of the binary operator.
13714 // The following two variables are used for compound assignment operators
13715 QualType CompLHSTy; // Type of LHS after promotions for computation
13716 QualType CompResultTy; // Type of computation result
13717 ExprValueKind VK = VK_RValue;
13718 ExprObjectKind OK = OK_Ordinary;
13719 bool ConvertHalfVec = false;
13720
13721 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13722 if (!LHS.isUsable() || !RHS.isUsable())
13723 return ExprError();
13724
13725 if (getLangOpts().OpenCL) {
13726 QualType LHSTy = LHSExpr->getType();
13727 QualType RHSTy = RHSExpr->getType();
13728 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13729 // the ATOMIC_VAR_INIT macro.
13730 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13731 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13732 if (BO_Assign == Opc)
13733 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13734 else
13735 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13736 return ExprError();
13737 }
13738
13739 // OpenCL special types - image, sampler, pipe, and blocks are to be used
13740 // only with a builtin functions and therefore should be disallowed here.
13741 if (LHSTy->isImageType() || RHSTy->isImageType() ||
13742 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13743 LHSTy->isPipeType() || RHSTy->isPipeType() ||
13744 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13745 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13746 return ExprError();
13747 }
13748 }
13749
13750 switch (Opc) {
13751 case BO_Assign:
13752 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13753 if (getLangOpts().CPlusPlus &&
13754 LHS.get()->getObjectKind() != OK_ObjCProperty) {
13755 VK = LHS.get()->getValueKind();
13756 OK = LHS.get()->getObjectKind();
13757 }
13758 if (!ResultTy.isNull()) {
13759 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13760 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13761
13762 // Avoid copying a block to the heap if the block is assigned to a local
13763 // auto variable that is declared in the same scope as the block. This
13764 // optimization is unsafe if the local variable is declared in an outer
13765 // scope. For example:
13766 //
13767 // BlockTy b;
13768 // {
13769 // b = ^{...};
13770 // }
13771 // // It is unsafe to invoke the block here if it wasn't copied to the
13772 // // heap.
13773 // b();
13774
13775 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13776 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13777 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13778 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13779 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13780
13781 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13782 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13783 NTCUC_Assignment, NTCUK_Copy);
13784 }
13785 RecordModifiableNonNullParam(*this, LHS.get());
13786 break;
13787 case BO_PtrMemD:
13788 case BO_PtrMemI:
13789 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13790 Opc == BO_PtrMemI);
13791 break;
13792 case BO_Mul:
13793 case BO_Div:
13794 ConvertHalfVec = true;
13795 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13796 Opc == BO_Div);
13797 break;
13798 case BO_Rem:
13799 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13800 break;
13801 case BO_Add:
13802 ConvertHalfVec = true;
13803 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13804 break;
13805 case BO_Sub:
13806 ConvertHalfVec = true;
13807 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13808 break;
13809 case BO_Shl:
13810 case BO_Shr:
13811 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13812 break;
13813 case BO_LE:
13814 case BO_LT:
13815 case BO_GE:
13816 case BO_GT:
13817 ConvertHalfVec = true;
13818 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13819 break;
13820 case BO_EQ:
13821 case BO_NE:
13822 ConvertHalfVec = true;
13823 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13824 break;
13825 case BO_Cmp:
13826 ConvertHalfVec = true;
13827 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13828 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())((ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()) ? static_cast
<void> (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13828, __PRETTY_FUNCTION__))
;
13829 break;
13830 case BO_And:
13831 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13832 LLVM_FALLTHROUGH[[gnu::fallthrough]];
13833 case BO_Xor:
13834 case BO_Or:
13835 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13836 break;
13837 case BO_LAnd:
13838 case BO_LOr:
13839 ConvertHalfVec = true;
13840 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13841 break;
13842 case BO_MulAssign:
13843 case BO_DivAssign:
13844 ConvertHalfVec = true;
13845 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13846 Opc == BO_DivAssign);
13847 CompLHSTy = CompResultTy;
13848 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13849 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13850 break;
13851 case BO_RemAssign:
13852 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13853 CompLHSTy = CompResultTy;
13854 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13855 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13856 break;
13857 case BO_AddAssign:
13858 ConvertHalfVec = true;
13859 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13860 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13861 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13862 break;
13863 case BO_SubAssign:
13864 ConvertHalfVec = true;
13865 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13866 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13867 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13868 break;
13869 case BO_ShlAssign:
13870 case BO_ShrAssign:
13871 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13872 CompLHSTy = CompResultTy;
13873 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13874 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13875 break;
13876 case BO_AndAssign:
13877 case BO_OrAssign: // fallthrough
13878 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13879 LLVM_FALLTHROUGH[[gnu::fallthrough]];
13880 case BO_XorAssign:
13881 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13882 CompLHSTy = CompResultTy;
13883 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13884 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13885 break;
13886 case BO_Comma:
13887 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13888 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13889 VK = RHS.get()->getValueKind();
13890 OK = RHS.get()->getObjectKind();
13891 }
13892 break;
13893 }
13894 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13895 return ExprError();
13896
13897 // Some of the binary operations require promoting operands of half vector to
13898 // float vectors and truncating the result back to half vector. For now, we do
13899 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13900 // arm64).
13901 assert(isVector(RHS.get()->getType(), Context.HalfTy) ==((isVector(RHS.get()->getType(), Context.HalfTy) == isVector
(LHS.get()->getType(), Context.HalfTy) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13903, __PRETTY_FUNCTION__))
13902 isVector(LHS.get()->getType(), Context.HalfTy) &&((isVector(RHS.get()->getType(), Context.HalfTy) == isVector
(LHS.get()->getType(), Context.HalfTy) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13903, __PRETTY_FUNCTION__))
13903 "both sides are half vectors or neither sides are")((isVector(RHS.get()->getType(), Context.HalfTy) == isVector
(LHS.get()->getType(), Context.HalfTy) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 13903, __PRETTY_FUNCTION__))
;
13904 ConvertHalfVec =
13905 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13906
13907 // Check for array bounds violations for both sides of the BinaryOperator
13908 CheckArrayAccess(LHS.get());
13909 CheckArrayAccess(RHS.get());
13910
13911 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13912 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13913 &Context.Idents.get("object_setClass"),
13914 SourceLocation(), LookupOrdinaryName);
13915 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13916 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13917 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13918 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13919 "object_setClass(")
13920 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13921 ",")
13922 << FixItHint::CreateInsertion(RHSLocEnd, ")");
13923 }
13924 else
13925 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13926 }
13927 else if (const ObjCIvarRefExpr *OIRE =
13928 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13929 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13930
13931 // Opc is not a compound assignment if CompResultTy is null.
13932 if (CompResultTy.isNull()) {
13933 if (ConvertHalfVec)
13934 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13935 OpLoc, CurFPFeatureOverrides());
13936 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13937 VK, OK, OpLoc, CurFPFeatureOverrides());
13938 }
13939
13940 // Handle compound assignments.
13941 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13942 OK_ObjCProperty) {
13943 VK = VK_LValue;
13944 OK = LHS.get()->getObjectKind();
13945 }
13946
13947 // The LHS is not converted to the result type for fixed-point compound
13948 // assignment as the common type is computed on demand. Reset the CompLHSTy
13949 // to the LHS type we would have gotten after unary conversions.
13950 if (CompResultTy->isFixedPointType())
13951 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13952
13953 if (ConvertHalfVec)
13954 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13955 OpLoc, CurFPFeatureOverrides());
13956
13957 return CompoundAssignOperator::Create(
13958 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
13959 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
13960}
13961
13962/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13963/// operators are mixed in a way that suggests that the programmer forgot that
13964/// comparison operators have higher precedence. The most typical example of
13965/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13966static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13967 SourceLocation OpLoc, Expr *LHSExpr,
13968 Expr *RHSExpr) {
13969 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13970 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13971
13972 // Check that one of the sides is a comparison operator and the other isn't.
13973 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13974 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13975 if (isLeftComp == isRightComp)
13976 return;
13977
13978 // Bitwise operations are sometimes used as eager logical ops.
13979 // Don't diagnose this.
13980 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13981 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13982 if (isLeftBitwise || isRightBitwise)
13983 return;
13984
13985 SourceRange DiagRange = isLeftComp
13986 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13987 : SourceRange(OpLoc, RHSExpr->getEndLoc());
13988 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13989 SourceRange ParensRange =
13990 isLeftComp
13991 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13992 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13993
13994 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13995 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13996 SuggestParentheses(Self, OpLoc,
13997 Self.PDiag(diag::note_precedence_silence) << OpStr,
13998 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13999 SuggestParentheses(Self, OpLoc,
14000 Self.PDiag(diag::note_precedence_bitwise_first)
14001 << BinaryOperator::getOpcodeStr(Opc),
14002 ParensRange);
14003}
14004
14005/// It accepts a '&&' expr that is inside a '||' one.
14006/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14007/// in parentheses.
14008static void
14009EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14010 BinaryOperator *Bop) {
14011 assert(Bop->getOpcode() == BO_LAnd)((Bop->getOpcode() == BO_LAnd) ? static_cast<void> (
0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14011, __PRETTY_FUNCTION__))
;
14012 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14013 << Bop->getSourceRange() << OpLoc;
14014 SuggestParentheses(Self, Bop->getOperatorLoc(),
14015 Self.PDiag(diag::note_precedence_silence)
14016 << Bop->getOpcodeStr(),
14017 Bop->getSourceRange());
14018}
14019
14020/// Returns true if the given expression can be evaluated as a constant
14021/// 'true'.
14022static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14023 bool Res;
14024 return !E->isValueDependent() &&
14025 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14026}
14027
14028/// Returns true if the given expression can be evaluated as a constant
14029/// 'false'.
14030static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14031 bool Res;
14032 return !E->isValueDependent() &&
14033 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14034}
14035
14036/// Look for '&&' in the left hand of a '||' expr.
14037static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14038 Expr *LHSExpr, Expr *RHSExpr) {
14039 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14040 if (Bop->getOpcode() == BO_LAnd) {
14041 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14042 if (EvaluatesAsFalse(S, RHSExpr))
14043 return;
14044 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14045 if (!EvaluatesAsTrue(S, Bop->getLHS()))
14046 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14047 } else if (Bop->getOpcode() == BO_LOr) {
14048 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14049 // If it's "a || b && 1 || c" we didn't warn earlier for
14050 // "a || b && 1", but warn now.
14051 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14052 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14053 }
14054 }
14055 }
14056}
14057
14058/// Look for '&&' in the right hand of a '||' expr.
14059static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14060 Expr *LHSExpr, Expr *RHSExpr) {
14061 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14062 if (Bop->getOpcode() == BO_LAnd) {
14063 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14064 if (EvaluatesAsFalse(S, LHSExpr))
14065 return;
14066 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14067 if (!EvaluatesAsTrue(S, Bop->getRHS()))
14068 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14069 }
14070 }
14071}
14072
14073/// Look for bitwise op in the left or right hand of a bitwise op with
14074/// lower precedence and emit a diagnostic together with a fixit hint that wraps
14075/// the '&' expression in parentheses.
14076static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14077 SourceLocation OpLoc, Expr *SubExpr) {
14078 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14079 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14080 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14081 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14082 << Bop->getSourceRange() << OpLoc;
14083 SuggestParentheses(S, Bop->getOperatorLoc(),
14084 S.PDiag(diag::note_precedence_silence)
14085 << Bop->getOpcodeStr(),
14086 Bop->getSourceRange());
14087 }
14088 }
14089}
14090
14091static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14092 Expr *SubExpr, StringRef Shift) {
14093 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14094 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14095 StringRef Op = Bop->getOpcodeStr();
14096 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14097 << Bop->getSourceRange() << OpLoc << Shift << Op;
14098 SuggestParentheses(S, Bop->getOperatorLoc(),
14099 S.PDiag(diag::note_precedence_silence) << Op,
14100 Bop->getSourceRange());
14101 }
14102 }
14103}
14104
14105static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14106 Expr *LHSExpr, Expr *RHSExpr) {
14107 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14108 if (!OCE)
14109 return;
14110
14111 FunctionDecl *FD = OCE->getDirectCallee();
14112 if (!FD || !FD->isOverloadedOperator())
14113 return;
14114
14115 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14116 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14117 return;
14118
14119 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14120 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14121 << (Kind == OO_LessLess);
14122 SuggestParentheses(S, OCE->getOperatorLoc(),
14123 S.PDiag(diag::note_precedence_silence)
14124 << (Kind == OO_LessLess ? "<<" : ">>"),
14125 OCE->getSourceRange());
14126 SuggestParentheses(
14127 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14128 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14129}
14130
14131/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14132/// precedence.
14133static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14134 SourceLocation OpLoc, Expr *LHSExpr,
14135 Expr *RHSExpr){
14136 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14137 if (BinaryOperator::isBitwiseOp(Opc))
14138 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14139
14140 // Diagnose "arg1 & arg2 | arg3"
14141 if ((Opc == BO_Or || Opc == BO_Xor) &&
14142 !OpLoc.isMacroID()/* Don't warn in macros. */) {
14143 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14144 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14145 }
14146
14147 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14148 // We don't warn for 'assert(a || b && "bad")' since this is safe.
14149 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14150 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14151 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14152 }
14153
14154 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14155 || Opc == BO_Shr) {
14156 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14157 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14158 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14159 }
14160
14161 // Warn on overloaded shift operators and comparisons, such as:
14162 // cout << 5 == 4;
14163 if (BinaryOperator::isComparisonOp(Opc))
14164 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14165}
14166
14167// Binary Operators. 'Tok' is the token for the operator.
14168ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14169 tok::TokenKind Kind,
14170 Expr *LHSExpr, Expr *RHSExpr) {
14171 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14172 assert(LHSExpr && "ActOnBinOp(): missing left expression")((LHSExpr && "ActOnBinOp(): missing left expression")
? static_cast<void> (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14172, __PRETTY_FUNCTION__))
;
14173 assert(RHSExpr && "ActOnBinOp(): missing right expression")((RHSExpr && "ActOnBinOp(): missing right expression"
) ? static_cast<void> (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14173, __PRETTY_FUNCTION__))
;
14174
14175 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14176 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14177
14178 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14179}
14180
14181/// Build an overloaded binary operator expression in the given scope.
14182static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14183 BinaryOperatorKind Opc,
14184 Expr *LHS, Expr *RHS) {
14185 switch (Opc) {
14186 case BO_Assign:
14187 case BO_DivAssign:
14188 case BO_RemAssign:
14189 case BO_SubAssign:
14190 case BO_AndAssign:
14191 case BO_OrAssign:
14192 case BO_XorAssign:
14193 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14194 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14195 break;
14196 default:
14197 break;
14198 }
14199
14200 // Find all of the overloaded operators visible from this
14201 // point. We perform both an operator-name lookup from the local
14202 // scope and an argument-dependent lookup based on the types of
14203 // the arguments.
14204 UnresolvedSet<16> Functions;
14205 OverloadedOperatorKind OverOp
14206 = BinaryOperator::getOverloadedOperator(Opc);
14207 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
14208 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
14209 RHS->getType(), Functions);
14210
14211 // In C++20 onwards, we may have a second operator to look up.
14212 if (S.getLangOpts().CPlusPlus20) {
14213 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14214 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
14215 RHS->getType(), Functions);
14216 }
14217
14218 // Build the (potentially-overloaded, potentially-dependent)
14219 // binary operation.
14220 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14221}
14222
14223ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14224 BinaryOperatorKind Opc,
14225 Expr *LHSExpr, Expr *RHSExpr) {
14226 ExprResult LHS, RHS;
14227 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14228 if (!LHS.isUsable() || !RHS.isUsable())
14229 return ExprError();
14230 LHSExpr = LHS.get();
14231 RHSExpr = RHS.get();
14232
14233 // We want to end up calling one of checkPseudoObjectAssignment
14234 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14235 // both expressions are overloadable or either is type-dependent),
14236 // or CreateBuiltinBinOp (in any other case). We also want to get
14237 // any placeholder types out of the way.
14238
14239 // Handle pseudo-objects in the LHS.
14240 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14241 // Assignments with a pseudo-object l-value need special analysis.
14242 if (pty->getKind() == BuiltinType::PseudoObject &&
14243 BinaryOperator::isAssignmentOp(Opc))
14244 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14245
14246 // Don't resolve overloads if the other type is overloadable.
14247 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14248 // We can't actually test that if we still have a placeholder,
14249 // though. Fortunately, none of the exceptions we see in that
14250 // code below are valid when the LHS is an overload set. Note
14251 // that an overload set can be dependently-typed, but it never
14252 // instantiates to having an overloadable type.
14253 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14254 if (resolvedRHS.isInvalid()) return ExprError();
14255 RHSExpr = resolvedRHS.get();
14256
14257 if (RHSExpr->isTypeDependent() ||
14258 RHSExpr->getType()->isOverloadableType())
14259 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14260 }
14261
14262 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14263 // template, diagnose the missing 'template' keyword instead of diagnosing
14264 // an invalid use of a bound member function.
14265 //
14266 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14267 // to C++1z [over.over]/1.4, but we already checked for that case above.
14268 if (Opc == BO_LT && inTemplateInstantiation() &&
14269 (pty->getKind() == BuiltinType::BoundMember ||
14270 pty->getKind() == BuiltinType::Overload)) {
14271 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14272 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14273 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14274 return isa<FunctionTemplateDecl>(ND);
14275 })) {
14276 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14277 : OE->getNameLoc(),
14278 diag::err_template_kw_missing)
14279 << OE->getName().getAsString() << "";
14280 return ExprError();
14281 }
14282 }
14283
14284 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14285 if (LHS.isInvalid()) return ExprError();
14286 LHSExpr = LHS.get();
14287 }
14288
14289 // Handle pseudo-objects in the RHS.
14290 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14291 // An overload in the RHS can potentially be resolved by the type
14292 // being assigned to.
14293 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14294 if (getLangOpts().CPlusPlus &&
14295 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14296 LHSExpr->getType()->isOverloadableType()))
14297 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14298
14299 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14300 }
14301
14302 // Don't resolve overloads if the other type is overloadable.
14303 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14304 LHSExpr->getType()->isOverloadableType())
14305 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14306
14307 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14308 if (!resolvedRHS.isUsable()) return ExprError();
14309 RHSExpr = resolvedRHS.get();
14310 }
14311
14312 if (getLangOpts().CPlusPlus) {
14313 // If either expression is type-dependent, always build an
14314 // overloaded op.
14315 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14316 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14317
14318 // Otherwise, build an overloaded op if either expression has an
14319 // overloadable type.
14320 if (LHSExpr->getType()->isOverloadableType() ||
14321 RHSExpr->getType()->isOverloadableType())
14322 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14323 }
14324
14325 // Build a built-in binary operation.
14326 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14327}
14328
14329static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14330 if (T.isNull() || T->isDependentType())
14331 return false;
14332
14333 if (!T->isPromotableIntegerType())
14334 return true;
14335
14336 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14337}
14338
14339ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14340 UnaryOperatorKind Opc,
14341 Expr *InputExpr) {
14342 ExprResult Input = InputExpr;
14343 ExprValueKind VK = VK_RValue;
14344 ExprObjectKind OK = OK_Ordinary;
14345 QualType resultType;
14346 bool CanOverflow = false;
14347
14348 bool ConvertHalfVec = false;
14349 if (getLangOpts().OpenCL) {
14350 QualType Ty = InputExpr->getType();
14351 // The only legal unary operation for atomics is '&'.
14352 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14353 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14354 // only with a builtin functions and therefore should be disallowed here.
14355 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14356 || Ty->isBlockPointerType())) {
14357 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14358 << InputExpr->getType()
14359 << Input.get()->getSourceRange());
14360 }
14361 }
14362
14363 switch (Opc) {
14364 case UO_PreInc:
14365 case UO_PreDec:
14366 case UO_PostInc:
14367 case UO_PostDec:
14368 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14369 OpLoc,
14370 Opc == UO_PreInc ||
14371 Opc == UO_PostInc,
14372 Opc == UO_PreInc ||
14373 Opc == UO_PreDec);
14374 CanOverflow = isOverflowingIntegerType(Context, resultType);
14375 break;
14376 case UO_AddrOf:
14377 resultType = CheckAddressOfOperand(Input, OpLoc);
14378 CheckAddressOfNoDeref(InputExpr);
14379 RecordModifiableNonNullParam(*this, InputExpr);
14380 break;
14381 case UO_Deref: {
14382 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14383 if (Input.isInvalid()) return ExprError();
14384 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14385 break;
14386 }
14387 case UO_Plus:
14388 case UO_Minus:
14389 CanOverflow = Opc == UO_Minus &&
14390 isOverflowingIntegerType(Context, Input.get()->getType());
14391 Input = UsualUnaryConversions(Input.get());
14392 if (Input.isInvalid()) return ExprError();
14393 // Unary plus and minus require promoting an operand of half vector to a
14394 // float vector and truncating the result back to a half vector. For now, we
14395 // do this only when HalfArgsAndReturns is set (that is, when the target is
14396 // arm or arm64).
14397 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14398
14399 // If the operand is a half vector, promote it to a float vector.
14400 if (ConvertHalfVec)
14401 Input = convertVector(Input.get(), Context.FloatTy, *this);
14402 resultType = Input.get()->getType();
14403 if (resultType->isDependentType())
14404 break;
14405 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14406 break;
14407 else if (resultType->isVectorType() &&
14408 // The z vector extensions don't allow + or - with bool vectors.
14409 (!Context.getLangOpts().ZVector ||
14410 resultType->castAs<VectorType>()->getVectorKind() !=
14411 VectorType::AltiVecBool))
14412 break;
14413 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14414 Opc == UO_Plus &&
14415 resultType->isPointerType())
14416 break;
14417
14418 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14419 << resultType << Input.get()->getSourceRange());
14420
14421 case UO_Not: // bitwise complement
14422 Input = UsualUnaryConversions(Input.get());
14423 if (Input.isInvalid())
14424 return ExprError();
14425 resultType = Input.get()->getType();
14426 if (resultType->isDependentType())
14427 break;
14428 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14429 if (resultType->isComplexType() || resultType->isComplexIntegerType())
14430 // C99 does not support '~' for complex conjugation.
14431 Diag(OpLoc, diag::ext_integer_complement_complex)
14432 << resultType << Input.get()->getSourceRange();
14433 else if (resultType->hasIntegerRepresentation())
14434 break;
14435 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14436 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14437 // on vector float types.
14438 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14439 if (!T->isIntegerType())
14440 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14441 << resultType << Input.get()->getSourceRange());
14442 } else {
14443 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14444 << resultType << Input.get()->getSourceRange());
14445 }
14446 break;
14447
14448 case UO_LNot: // logical negation
14449 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14450 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14451 if (Input.isInvalid()) return ExprError();
14452 resultType = Input.get()->getType();
14453
14454 // Though we still have to promote half FP to float...
14455 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14456 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14457 resultType = Context.FloatTy;
14458 }
14459
14460 if (resultType->isDependentType())
14461 break;
14462 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14463 // C99 6.5.3.3p1: ok, fallthrough;
14464 if (Context.getLangOpts().CPlusPlus) {
14465 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14466 // operand contextually converted to bool.
14467 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14468 ScalarTypeToBooleanCastKind(resultType));
14469 } else if (Context.getLangOpts().OpenCL &&
14470 Context.getLangOpts().OpenCLVersion < 120) {
14471 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14472 // operate on scalar float types.
14473 if (!resultType->isIntegerType() && !resultType->isPointerType())
14474 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14475 << resultType << Input.get()->getSourceRange());
14476 }
14477 } else if (resultType->isExtVectorType()) {
14478 if (Context.getLangOpts().OpenCL &&
14479 Context.getLangOpts().OpenCLVersion < 120 &&
14480 !Context.getLangOpts().OpenCLCPlusPlus) {
14481 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14482 // operate on vector float types.
14483 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14484 if (!T->isIntegerType())
14485 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14486 << resultType << Input.get()->getSourceRange());
14487 }
14488 // Vector logical not returns the signed variant of the operand type.
14489 resultType = GetSignedVectorType(resultType);
14490 break;
14491 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14492 const VectorType *VTy = resultType->castAs<VectorType>();
14493 if (VTy->getVectorKind() != VectorType::GenericVector)
14494 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14495 << resultType << Input.get()->getSourceRange());
14496
14497 // Vector logical not returns the signed variant of the operand type.
14498 resultType = GetSignedVectorType(resultType);
14499 break;
14500 } else {
14501 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14502 << resultType << Input.get()->getSourceRange());
14503 }
14504
14505 // LNot always has type int. C99 6.5.3.3p5.
14506 // In C++, it's bool. C++ 5.3.1p8
14507 resultType = Context.getLogicalOperationType();
14508 break;
14509 case UO_Real:
14510 case UO_Imag:
14511 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14512 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14513 // complex l-values to ordinary l-values and all other values to r-values.
14514 if (Input.isInvalid()) return ExprError();
14515 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14516 if (Input.get()->getValueKind() != VK_RValue &&
14517 Input.get()->getObjectKind() == OK_Ordinary)
14518 VK = Input.get()->getValueKind();
14519 } else if (!getLangOpts().CPlusPlus) {
14520 // In C, a volatile scalar is read by __imag. In C++, it is not.
14521 Input = DefaultLvalueConversion(Input.get());
14522 }
14523 break;
14524 case UO_Extension:
14525 resultType = Input.get()->getType();
14526 VK = Input.get()->getValueKind();
14527 OK = Input.get()->getObjectKind();
14528 break;
14529 case UO_Coawait:
14530 // It's unnecessary to represent the pass-through operator co_await in the
14531 // AST; just return the input expression instead.
14532 assert(!Input.get()->getType()->isDependentType() &&((!Input.get()->getType()->isDependentType() &&
"the co_await expression must be non-dependant before " "building operator co_await"
) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14534, __PRETTY_FUNCTION__))
14533 "the co_await expression must be non-dependant before "((!Input.get()->getType()->isDependentType() &&
"the co_await expression must be non-dependant before " "building operator co_await"
) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14534, __PRETTY_FUNCTION__))
14534 "building operator co_await")((!Input.get()->getType()->isDependentType() &&
"the co_await expression must be non-dependant before " "building operator co_await"
) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14534, __PRETTY_FUNCTION__))
;
14535 return Input;
14536 }
14537 if (resultType.isNull() || Input.isInvalid())
14538 return ExprError();
14539
14540 // Check for array bounds violations in the operand of the UnaryOperator,
14541 // except for the '*' and '&' operators that have to be handled specially
14542 // by CheckArrayAccess (as there are special cases like &array[arraysize]
14543 // that are explicitly defined as valid by the standard).
14544 if (Opc != UO_AddrOf && Opc != UO_Deref)
14545 CheckArrayAccess(Input.get());
14546
14547 auto *UO =
14548 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14549 OpLoc, CanOverflow, CurFPFeatureOverrides());
14550
14551 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14552 !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14553 ExprEvalContexts.back().PossibleDerefs.insert(UO);
14554
14555 // Convert the result back to a half vector.
14556 if (ConvertHalfVec)
14557 return convertVector(UO, Context.HalfTy, *this);
14558 return UO;
14559}
14560
14561/// Determine whether the given expression is a qualified member
14562/// access expression, of a form that could be turned into a pointer to member
14563/// with the address-of operator.
14564bool Sema::isQualifiedMemberAccess(Expr *E) {
14565 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14566 if (!DRE->getQualifier())
14567 return false;
14568
14569 ValueDecl *VD = DRE->getDecl();
14570 if (!VD->isCXXClassMember())
14571 return false;
14572
14573 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14574 return true;
14575 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14576 return Method->isInstance();
14577
14578 return false;
14579 }
14580
14581 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14582 if (!ULE->getQualifier())
14583 return false;
14584
14585 for (NamedDecl *D : ULE->decls()) {
14586 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14587 if (Method->isInstance())
14588 return true;
14589 } else {
14590 // Overload set does not contain methods.
14591 break;
14592 }
14593 }
14594
14595 return false;
14596 }
14597
14598 return false;
14599}
14600
14601ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14602 UnaryOperatorKind Opc, Expr *Input) {
14603 // First things first: handle placeholders so that the
14604 // overloaded-operator check considers the right type.
14605 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14606 // Increment and decrement of pseudo-object references.
14607 if (pty->getKind() == BuiltinType::PseudoObject &&
14608 UnaryOperator::isIncrementDecrementOp(Opc))
14609 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14610
14611 // extension is always a builtin operator.
14612 if (Opc == UO_Extension)
14613 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14614
14615 // & gets special logic for several kinds of placeholder.
14616 // The builtin code knows what to do.
14617 if (Opc == UO_AddrOf &&
14618 (pty->getKind() == BuiltinType::Overload ||
14619 pty->getKind() == BuiltinType::UnknownAny ||
14620 pty->getKind() == BuiltinType::BoundMember))
14621 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14622
14623 // Anything else needs to be handled now.
14624 ExprResult Result = CheckPlaceholderExpr(Input);
14625 if (Result.isInvalid()) return ExprError();
14626 Input = Result.get();
14627 }
14628
14629 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14630 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14631 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14632 // Find all of the overloaded operators visible from this
14633 // point. We perform both an operator-name lookup from the local
14634 // scope and an argument-dependent lookup based on the types of
14635 // the arguments.
14636 UnresolvedSet<16> Functions;
14637 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14638 if (S && OverOp != OO_None)
14639 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14640 Functions);
14641
14642 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14643 }
14644
14645 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14646}
14647
14648// Unary Operators. 'Tok' is the token for the operator.
14649ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14650 tok::TokenKind Op, Expr *Input) {
14651 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14652}
14653
14654/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14655ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14656 LabelDecl *TheDecl) {
14657 TheDecl->markUsed(Context);
14658 // Create the AST node. The address of a label always has type 'void*'.
14659 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14660 Context.getPointerType(Context.VoidTy));
14661}
14662
14663void Sema::ActOnStartStmtExpr() {
14664 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14665}
14666
14667void Sema::ActOnStmtExprError() {
14668 // Note that function is also called by TreeTransform when leaving a
14669 // StmtExpr scope without rebuilding anything.
14670
14671 DiscardCleanupsInEvaluationContext();
14672 PopExpressionEvaluationContext();
14673}
14674
14675ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14676 SourceLocation RPLoc) {
14677 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14678}
14679
14680ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14681 SourceLocation RPLoc, unsigned TemplateDepth) {
14682 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")((SubStmt && isa<CompoundStmt>(SubStmt) &&
"Invalid action invocation!") ? static_cast<void> (0) :
__assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14682, __PRETTY_FUNCTION__))
;
14683 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14684
14685 if (hasAnyUnrecoverableErrorsInThisFunction())
14686 DiscardCleanupsInEvaluationContext();
14687 assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14688, __PRETTY_FUNCTION__))
14688 "cleanups within StmtExpr not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14688, __PRETTY_FUNCTION__))
;
14689 PopExpressionEvaluationContext();
14690
14691 // FIXME: there are a variety of strange constraints to enforce here, for
14692 // example, it is not possible to goto into a stmt expression apparently.
14693 // More semantic analysis is needed.
14694
14695 // If there are sub-stmts in the compound stmt, take the type of the last one
14696 // as the type of the stmtexpr.
14697 QualType Ty = Context.VoidTy;
14698 bool StmtExprMayBindToTemp = false;
14699 if (!Compound->body_empty()) {
14700 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14701 if (const auto *LastStmt =
14702 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14703 if (const Expr *Value = LastStmt->getExprStmt()) {
14704 StmtExprMayBindToTemp = true;
14705 Ty = Value->getType();
14706 }
14707 }
14708 }
14709
14710 // FIXME: Check that expression type is complete/non-abstract; statement
14711 // expressions are not lvalues.
14712 Expr *ResStmtExpr =
14713 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14714 if (StmtExprMayBindToTemp)
14715 return MaybeBindToTemporary(ResStmtExpr);
14716 return ResStmtExpr;
14717}
14718
14719ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14720 if (ER.isInvalid())
14721 return ExprError();
14722
14723 // Do function/array conversion on the last expression, but not
14724 // lvalue-to-rvalue. However, initialize an unqualified type.
14725 ER = DefaultFunctionArrayConversion(ER.get());
14726 if (ER.isInvalid())
14727 return ExprError();
14728 Expr *E = ER.get();
14729
14730 if (E->isTypeDependent())
14731 return E;
14732
14733 // In ARC, if the final expression ends in a consume, splice
14734 // the consume out and bind it later. In the alternate case
14735 // (when dealing with a retainable type), the result
14736 // initialization will create a produce. In both cases the
14737 // result will be +1, and we'll need to balance that out with
14738 // a bind.
14739 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14740 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14741 return Cast->getSubExpr();
14742
14743 // FIXME: Provide a better location for the initialization.
14744 return PerformCopyInitialization(
14745 InitializedEntity::InitializeStmtExprResult(
14746 E->getBeginLoc(), E->getType().getUnqualifiedType()),
14747 SourceLocation(), E);
14748}
14749
14750ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14751 TypeSourceInfo *TInfo,
14752 ArrayRef<OffsetOfComponent> Components,
14753 SourceLocation RParenLoc) {
14754 QualType ArgTy = TInfo->getType();
14755 bool Dependent = ArgTy->isDependentType();
14756 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14757
14758 // We must have at least one component that refers to the type, and the first
14759 // one is known to be a field designator. Verify that the ArgTy represents
14760 // a struct/union/class.
14761 if (!Dependent && !ArgTy->isRecordType())
14762 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14763 << ArgTy << TypeRange);
14764
14765 // Type must be complete per C99 7.17p3 because a declaring a variable
14766 // with an incomplete type would be ill-formed.
14767 if (!Dependent
14768 && RequireCompleteType(BuiltinLoc, ArgTy,
14769 diag::err_offsetof_incomplete_type, TypeRange))
14770 return ExprError();
14771
14772 bool DidWarnAboutNonPOD = false;
14773 QualType CurrentType = ArgTy;
14774 SmallVector<OffsetOfNode, 4> Comps;
14775 SmallVector<Expr*, 4> Exprs;
14776 for (const OffsetOfComponent &OC : Components) {
14777 if (OC.isBrackets) {
14778 // Offset of an array sub-field. TODO: Should we allow vector elements?
14779 if (!CurrentType->isDependentType()) {
14780 const ArrayType *AT = Context.getAsArrayType(CurrentType);
14781 if(!AT)
14782 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14783 << CurrentType);
14784 CurrentType = AT->getElementType();
14785 } else
14786 CurrentType = Context.DependentTy;
14787
14788 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14789 if (IdxRval.isInvalid())
14790 return ExprError();
14791 Expr *Idx = IdxRval.get();
14792
14793 // The expression must be an integral expression.
14794 // FIXME: An integral constant expression?
14795 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14796 !Idx->getType()->isIntegerType())
14797 return ExprError(
14798 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14799 << Idx->getSourceRange());
14800
14801 // Record this array index.
14802 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14803 Exprs.push_back(Idx);
14804 continue;
14805 }
14806
14807 // Offset of a field.
14808 if (CurrentType->isDependentType()) {
14809 // We have the offset of a field, but we can't look into the dependent
14810 // type. Just record the identifier of the field.
14811 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14812 CurrentType = Context.DependentTy;
14813 continue;
14814 }
14815
14816 // We need to have a complete type to look into.
14817 if (RequireCompleteType(OC.LocStart, CurrentType,
14818 diag::err_offsetof_incomplete_type))
14819 return ExprError();
14820
14821 // Look for the designated field.
14822 const RecordType *RC = CurrentType->getAs<RecordType>();
14823 if (!RC)
14824 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14825 << CurrentType);
14826 RecordDecl *RD = RC->getDecl();
14827
14828 // C++ [lib.support.types]p5:
14829 // The macro offsetof accepts a restricted set of type arguments in this
14830 // International Standard. type shall be a POD structure or a POD union
14831 // (clause 9).
14832 // C++11 [support.types]p4:
14833 // If type is not a standard-layout class (Clause 9), the results are
14834 // undefined.
14835 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14836 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14837 unsigned DiagID =
14838 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14839 : diag::ext_offsetof_non_pod_type;
14840
14841 if (!IsSafe && !DidWarnAboutNonPOD &&
14842 DiagRuntimeBehavior(BuiltinLoc, nullptr,
14843 PDiag(DiagID)
14844 << SourceRange(Components[0].LocStart, OC.LocEnd)
14845 << CurrentType))
14846 DidWarnAboutNonPOD = true;
14847 }
14848
14849 // Look for the field.
14850 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14851 LookupQualifiedName(R, RD);
14852 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14853 IndirectFieldDecl *IndirectMemberDecl = nullptr;
14854 if (!MemberDecl) {
14855 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14856 MemberDecl = IndirectMemberDecl->getAnonField();
14857 }
14858
14859 if (!MemberDecl)
14860 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14861 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14862 OC.LocEnd));
14863
14864 // C99 7.17p3:
14865 // (If the specified member is a bit-field, the behavior is undefined.)
14866 //
14867 // We diagnose this as an error.
14868 if (MemberDecl->isBitField()) {
14869 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14870 << MemberDecl->getDeclName()
14871 << SourceRange(BuiltinLoc, RParenLoc);
14872 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14873 return ExprError();
14874 }
14875
14876 RecordDecl *Parent = MemberDecl->getParent();
14877 if (IndirectMemberDecl)
14878 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14879
14880 // If the member was found in a base class, introduce OffsetOfNodes for
14881 // the base class indirections.
14882 CXXBasePaths Paths;
14883 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14884 Paths)) {
14885 if (Paths.getDetectedVirtual()) {
14886 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14887 << MemberDecl->getDeclName()
14888 << SourceRange(BuiltinLoc, RParenLoc);
14889 return ExprError();
14890 }
14891
14892 CXXBasePath &Path = Paths.front();
14893 for (const CXXBasePathElement &B : Path)
14894 Comps.push_back(OffsetOfNode(B.Base));
14895 }
14896
14897 if (IndirectMemberDecl) {
14898 for (auto *FI : IndirectMemberDecl->chain()) {
14899 assert(isa<FieldDecl>(FI))((isa<FieldDecl>(FI)) ? static_cast<void> (0) : __assert_fail
("isa<FieldDecl>(FI)", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14899, __PRETTY_FUNCTION__))
;
14900 Comps.push_back(OffsetOfNode(OC.LocStart,
14901 cast<FieldDecl>(FI), OC.LocEnd));
14902 }
14903 } else
14904 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14905
14906 CurrentType = MemberDecl->getType().getNonReferenceType();
14907 }
14908
14909 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14910 Comps, Exprs, RParenLoc);
14911}
14912
14913ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14914 SourceLocation BuiltinLoc,
14915 SourceLocation TypeLoc,
14916 ParsedType ParsedArgTy,
14917 ArrayRef<OffsetOfComponent> Components,
14918 SourceLocation RParenLoc) {
14919
14920 TypeSourceInfo *ArgTInfo;
14921 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14922 if (ArgTy.isNull())
14923 return ExprError();
14924
14925 if (!ArgTInfo)
14926 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14927
14928 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14929}
14930
14931
14932ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14933 Expr *CondExpr,
14934 Expr *LHSExpr, Expr *RHSExpr,
14935 SourceLocation RPLoc) {
14936 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(((CondExpr && LHSExpr && RHSExpr) &&
"Missing type argument(s)") ? static_cast<void> (0) : __assert_fail
("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 14936, __PRETTY_FUNCTION__))
;
14937
14938 ExprValueKind VK = VK_RValue;
14939 ExprObjectKind OK = OK_Ordinary;
14940 QualType resType;
14941 bool CondIsTrue = false;
14942 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14943 resType = Context.DependentTy;
14944 } else {
14945 // The conditional expression is required to be a constant expression.
14946 llvm::APSInt condEval(32);
14947 ExprResult CondICE
14948 = VerifyIntegerConstantExpression(CondExpr, &condEval,
14949 diag::err_typecheck_choose_expr_requires_constant, false);
14950 if (CondICE.isInvalid())
14951 return ExprError();
14952 CondExpr = CondICE.get();
14953 CondIsTrue = condEval.getZExtValue();
14954
14955 // If the condition is > zero, then the AST type is the same as the LHSExpr.
14956 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14957
14958 resType = ActiveExpr->getType();
14959 VK = ActiveExpr->getValueKind();
14960 OK = ActiveExpr->getObjectKind();
14961 }
14962
14963 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14964 resType, VK, OK, RPLoc, CondIsTrue);
14965}
14966
14967//===----------------------------------------------------------------------===//
14968// Clang Extensions.
14969//===----------------------------------------------------------------------===//
14970
14971/// ActOnBlockStart - This callback is invoked when a block literal is started.
14972void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14973 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14974
14975 if (LangOpts.CPlusPlus) {
14976 MangleNumberingContext *MCtx;
14977 Decl *ManglingContextDecl;
14978 std::tie(MCtx, ManglingContextDecl) =
14979 getCurrentMangleNumberContext(Block->getDeclContext());
14980 if (MCtx) {
14981 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14982 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14983 }
14984 }
14985
14986 PushBlockScope(CurScope, Block);
14987 CurContext->addDecl(Block);
14988 if (CurScope)
14989 PushDeclContext(CurScope, Block);
14990 else
14991 CurContext = Block;
14992
14993 getCurBlock()->HasImplicitReturnType = true;
14994
14995 // Enter a new evaluation context to insulate the block from any
14996 // cleanups from the enclosing full-expression.
14997 PushExpressionEvaluationContext(
14998 ExpressionEvaluationContext::PotentiallyEvaluated);
14999}
15000
15001void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15002 Scope *CurScope) {
15003 assert(ParamInfo.getIdentifier() == nullptr &&((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!"
) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15004, __PRETTY_FUNCTION__))
15004 "block-id should have no identifier!")((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!"
) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15004, __PRETTY_FUNCTION__))
;
15005 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext)((ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext
) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15005, __PRETTY_FUNCTION__))
;
15006 BlockScopeInfo *CurBlock = getCurBlock();
15007
15008 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15009 QualType T = Sig->getType();
15010
15011 // FIXME: We should allow unexpanded parameter packs here, but that would,
15012 // in turn, make the block expression contain unexpanded parameter packs.
15013 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15014 // Drop the parameters.
15015 FunctionProtoType::ExtProtoInfo EPI;
15016 EPI.HasTrailingReturn = false;
15017 EPI.TypeQuals.addConst();
15018 T = Context.getFunctionType(Context.DependentTy, None, EPI);
15019 Sig = Context.getTrivialTypeSourceInfo(T);
15020 }
15021
15022 // GetTypeForDeclarator always produces a function type for a block
15023 // literal signature. Furthermore, it is always a FunctionProtoType
15024 // unless the function was written with a typedef.
15025 assert(T->isFunctionType() &&((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15026, __PRETTY_FUNCTION__))
15026 "GetTypeForDeclarator made a non-function block signature")((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15026, __PRETTY_FUNCTION__))
;
15027
15028 // Look for an explicit signature in that function type.
15029 FunctionProtoTypeLoc ExplicitSignature;
15030
15031 if ((ExplicitSignature = Sig->getTypeLoc()
15032 .getAsAdjusted<FunctionProtoTypeLoc>())) {
15033
15034 // Check whether that explicit signature was synthesized by
15035 // GetTypeForDeclarator. If so, don't save that as part of the
15036 // written signature.
15037 if (ExplicitSignature.getLocalRangeBegin() ==
15038 ExplicitSignature.getLocalRangeEnd()) {
15039 // This would be much cheaper if we stored TypeLocs instead of
15040 // TypeSourceInfos.
15041 TypeLoc Result = ExplicitSignature.getReturnLoc();
15042 unsigned Size = Result.getFullDataSize();
15043 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15044 Sig->getTypeLoc().initializeFullCopy(Result, Size);
15045
15046 ExplicitSignature = FunctionProtoTypeLoc();
15047 }
15048 }
15049
15050 CurBlock->TheDecl->setSignatureAsWritten(Sig);
15051 CurBlock->FunctionType = T;
15052
15053 const FunctionType *Fn = T->getAs<FunctionType>();
15054 QualType RetTy = Fn->getReturnType();
15055 bool isVariadic =
15056 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15057
15058 CurBlock->TheDecl->setIsVariadic(isVariadic);
15059
15060 // Context.DependentTy is used as a placeholder for a missing block
15061 // return type. TODO: what should we do with declarators like:
15062 // ^ * { ... }
15063 // If the answer is "apply template argument deduction"....
15064 if (RetTy != Context.DependentTy) {
15065 CurBlock->ReturnType = RetTy;
15066 CurBlock->TheDecl->setBlockMissingReturnType(false);
15067 CurBlock->HasImplicitReturnType = false;
15068 }
15069
15070 // Push block parameters from the declarator if we had them.
15071 SmallVector<ParmVarDecl*, 8> Params;
15072 if (ExplicitSignature) {
15073 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15074 ParmVarDecl *Param = ExplicitSignature.getParam(I);
15075 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15076 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15077 // Diagnose this as an extension in C17 and earlier.
15078 if (!getLangOpts().C2x)
15079 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15080 }
15081 Params.push_back(Param);
15082 }
15083
15084 // Fake up parameter variables if we have a typedef, like
15085 // ^ fntype { ... }
15086 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15087 for (const auto &I : Fn->param_types()) {
15088 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15089 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15090 Params.push_back(Param);
15091 }
15092 }
15093
15094 // Set the parameters on the block decl.
15095 if (!Params.empty()) {
15096 CurBlock->TheDecl->setParams(Params);
15097 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15098 /*CheckParameterNames=*/false);
15099 }
15100
15101 // Finally we can process decl attributes.
15102 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15103
15104 // Put the parameter variables in scope.
15105 for (auto AI : CurBlock->TheDecl->parameters()) {
15106 AI->setOwningFunction(CurBlock->TheDecl);
15107
15108 // If this has an identifier, add it to the scope stack.
15109 if (AI->getIdentifier()) {
15110 CheckShadow(CurBlock->TheScope, AI);
15111
15112 PushOnScopeChains(AI, CurBlock->TheScope);
15113 }
15114 }
15115}
15116
15117/// ActOnBlockError - If there is an error parsing a block, this callback
15118/// is invoked to pop the information about the block from the action impl.
15119void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15120 // Leave the expression-evaluation context.
15121 DiscardCleanupsInEvaluationContext();
15122 PopExpressionEvaluationContext();
15123
15124 // Pop off CurBlock, handle nested blocks.
15125 PopDeclContext();
15126 PopFunctionScopeInfo();
15127}
15128
15129/// ActOnBlockStmtExpr - This is called when the body of a block statement
15130/// literal was successfully completed. ^(int x){...}
15131ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15132 Stmt *Body, Scope *CurScope) {
15133 // If blocks are disabled, emit an error.
15134 if (!LangOpts.Blocks)
15135 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15136
15137 // Leave the expression-evaluation context.
15138 if (hasAnyUnrecoverableErrorsInThisFunction())
15139 DiscardCleanupsInEvaluationContext();
15140 assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15141, __PRETTY_FUNCTION__))
15141 "cleanups within block not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15141, __PRETTY_FUNCTION__))
;
15142 PopExpressionEvaluationContext();
15143
15144 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15145 BlockDecl *BD = BSI->TheDecl;
15146
15147 if (BSI->HasImplicitReturnType)
15148 deduceClosureReturnType(*BSI);
15149
15150 QualType RetTy = Context.VoidTy;
15151 if (!BSI->ReturnType.isNull())
15152 RetTy = BSI->ReturnType;
15153
15154 bool NoReturn = BD->hasAttr<NoReturnAttr>();
15155 QualType BlockTy;
15156
15157 // If the user wrote a function type in some form, try to use that.
15158 if (!BSI->FunctionType.isNull()) {
15159 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15160
15161 FunctionType::ExtInfo Ext = FTy->getExtInfo();
15162 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15163
15164 // Turn protoless block types into nullary block types.
15165 if (isa<FunctionNoProtoType>(FTy)) {
15166 FunctionProtoType::ExtProtoInfo EPI;
15167 EPI.ExtInfo = Ext;
15168 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15169
15170 // Otherwise, if we don't need to change anything about the function type,
15171 // preserve its sugar structure.
15172 } else if (FTy->getReturnType() == RetTy &&
15173 (!NoReturn || FTy->getNoReturnAttr())) {
15174 BlockTy = BSI->FunctionType;
15175
15176 // Otherwise, make the minimal modifications to the function type.
15177 } else {
15178 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15179 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15180 EPI.TypeQuals = Qualifiers();
15181 EPI.ExtInfo = Ext;
15182 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15183 }
15184
15185 // If we don't have a function type, just build one from nothing.
15186 } else {
15187 FunctionProtoType::ExtProtoInfo EPI;
15188 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15189 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15190 }
15191
15192 DiagnoseUnusedParameters(BD->parameters());
15193 BlockTy = Context.getBlockPointerType(BlockTy);
15194
15195 // If needed, diagnose invalid gotos and switches in the block.
15196 if (getCurFunction()->NeedsScopeChecking() &&
15197 !PP.isCodeCompletionEnabled())
15198 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15199
15200 BD->setBody(cast<CompoundStmt>(Body));
15201
15202 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15203 DiagnoseUnguardedAvailabilityViolations(BD);
15204
15205 // Try to apply the named return value optimization. We have to check again
15206 // if we can do this, though, because blocks keep return statements around
15207 // to deduce an implicit return type.
15208 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15209 !BD->isDependentContext())
15210 computeNRVO(Body, BSI);
15211
15212 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15213 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15214 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15215 NTCUK_Destruct|NTCUK_Copy);
15216
15217 PopDeclContext();
15218
15219 // Pop the block scope now but keep it alive to the end of this function.
15220 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15221 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15222
15223 // Set the captured variables on the block.
15224 SmallVector<BlockDecl::Capture, 4> Captures;
15225 for (Capture &Cap : BSI->Captures) {
15226 if (Cap.isInvalid() || Cap.isThisCapture())
15227 continue;
15228
15229 VarDecl *Var = Cap.getVariable();
15230 Expr *CopyExpr = nullptr;
15231 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15232 if (const RecordType *Record =
15233 Cap.getCaptureType()->getAs<RecordType>()) {
15234 // The capture logic needs the destructor, so make sure we mark it.
15235 // Usually this is unnecessary because most local variables have
15236 // their destructors marked at declaration time, but parameters are
15237 // an exception because it's technically only the call site that
15238 // actually requires the destructor.
15239 if (isa<ParmVarDecl>(Var))
15240 FinalizeVarWithDestructor(Var, Record);
15241
15242 // Enter a separate potentially-evaluated context while building block
15243 // initializers to isolate their cleanups from those of the block
15244 // itself.
15245 // FIXME: Is this appropriate even when the block itself occurs in an
15246 // unevaluated operand?
15247 EnterExpressionEvaluationContext EvalContext(
15248 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15249
15250 SourceLocation Loc = Cap.getLocation();
15251
15252 ExprResult Result = BuildDeclarationNameExpr(
15253 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15254
15255 // According to the blocks spec, the capture of a variable from
15256 // the stack requires a const copy constructor. This is not true
15257 // of the copy/move done to move a __block variable to the heap.
15258 if (!Result.isInvalid() &&
15259 !Result.get()->getType().isConstQualified()) {
15260 Result = ImpCastExprToType(Result.get(),
15261 Result.get()->getType().withConst(),
15262 CK_NoOp, VK_LValue);
15263 }
15264
15265 if (!Result.isInvalid()) {
15266 Result = PerformCopyInitialization(
15267 InitializedEntity::InitializeBlock(Var->getLocation(),
15268 Cap.getCaptureType(), false),
15269 Loc, Result.get());
15270 }
15271
15272 // Build a full-expression copy expression if initialization
15273 // succeeded and used a non-trivial constructor. Recover from
15274 // errors by pretending that the copy isn't necessary.
15275 if (!Result.isInvalid() &&
15276 !cast<CXXConstructExpr>(Result.get())->getConstructor()
15277 ->isTrivial()) {
15278 Result = MaybeCreateExprWithCleanups(Result);
15279 CopyExpr = Result.get();
15280 }
15281 }
15282 }
15283
15284 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15285 CopyExpr);
15286 Captures.push_back(NewCap);
15287 }
15288 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15289
15290 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15291
15292 // If the block isn't obviously global, i.e. it captures anything at
15293 // all, then we need to do a few things in the surrounding context:
15294 if (Result->getBlockDecl()->hasCaptures()) {
15295 // First, this expression has a new cleanup object.
15296 ExprCleanupObjects.push_back(Result->getBlockDecl());
15297 Cleanup.setExprNeedsCleanups(true);
15298
15299 // It also gets a branch-protected scope if any of the captured
15300 // variables needs destruction.
15301 for (const auto &CI : Result->getBlockDecl()->captures()) {
15302 const VarDecl *var = CI.getVariable();
15303 if (var->getType().isDestructedType() != QualType::DK_none) {
15304 setFunctionHasBranchProtectedScope();
15305 break;
15306 }
15307 }
15308 }
15309
15310 if (getCurFunction())
15311 getCurFunction()->addBlock(BD);
15312
15313 return Result;
15314}
15315
15316ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15317 SourceLocation RPLoc) {
15318 TypeSourceInfo *TInfo;
15319 GetTypeFromParser(Ty, &TInfo);
15320 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15321}
15322
15323ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15324 Expr *E, TypeSourceInfo *TInfo,
15325 SourceLocation RPLoc) {
15326 Expr *OrigExpr = E;
15327 bool IsMS = false;
15328
15329 // CUDA device code does not support varargs.
15330 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15331 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15332 CUDAFunctionTarget T = IdentifyCUDATarget(F);
15333 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15334 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15335 }
15336 }
15337
15338 // NVPTX does not support va_arg expression.
15339 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15340 Context.getTargetInfo().getTriple().isNVPTX())
15341 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15342
15343 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15344 // as Microsoft ABI on an actual Microsoft platform, where
15345 // __builtin_ms_va_list and __builtin_va_list are the same.)
15346 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15347 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15348 QualType MSVaListType = Context.getBuiltinMSVaListType();
15349 if (Context.hasSameType(MSVaListType, E->getType())) {
15350 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15351 return ExprError();
15352 IsMS = true;
15353 }
15354 }
15355
15356 // Get the va_list type
15357 QualType VaListType = Context.getBuiltinVaListType();
15358 if (!IsMS) {
15359 if (VaListType->isArrayType()) {
15360 // Deal with implicit array decay; for example, on x86-64,
15361 // va_list is an array, but it's supposed to decay to
15362 // a pointer for va_arg.
15363 VaListType = Context.getArrayDecayedType(VaListType);
15364 // Make sure the input expression also decays appropriately.
15365 ExprResult Result = UsualUnaryConversions(E);
15366 if (Result.isInvalid())
15367 return ExprError();
15368 E = Result.get();
15369 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15370 // If va_list is a record type and we are compiling in C++ mode,
15371 // check the argument using reference binding.
15372 InitializedEntity Entity = InitializedEntity::InitializeParameter(
15373 Context, Context.getLValueReferenceType(VaListType), false);
15374 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15375 if (Init.isInvalid())
15376 return ExprError();
15377 E = Init.getAs<Expr>();
15378 } else {
15379 // Otherwise, the va_list argument must be an l-value because
15380 // it is modified by va_arg.
15381 if (!E->isTypeDependent() &&
15382 CheckForModifiableLvalue(E, BuiltinLoc, *this))
15383 return ExprError();
15384 }
15385 }
15386
15387 if (!IsMS && !E->isTypeDependent() &&
15388 !Context.hasSameType(VaListType, E->getType()))
15389 return ExprError(
15390 Diag(E->getBeginLoc(),
15391 diag::err_first_argument_to_va_arg_not_of_type_va_list)
15392 << OrigExpr->getType() << E->getSourceRange());
15393
15394 if (!TInfo->getType()->isDependentType()) {
15395 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15396 diag::err_second_parameter_to_va_arg_incomplete,
15397 TInfo->getTypeLoc()))
15398 return ExprError();
15399
15400 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15401 TInfo->getType(),
15402 diag::err_second_parameter_to_va_arg_abstract,
15403 TInfo->getTypeLoc()))
15404 return ExprError();
15405
15406 if (!TInfo->getType().isPODType(Context)) {
15407 Diag(TInfo->getTypeLoc().getBeginLoc(),
15408 TInfo->getType()->isObjCLifetimeType()
15409 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15410 : diag::warn_second_parameter_to_va_arg_not_pod)
15411 << TInfo->getType()
15412 << TInfo->getTypeLoc().getSourceRange();
15413 }
15414
15415 // Check for va_arg where arguments of the given type will be promoted
15416 // (i.e. this va_arg is guaranteed to have undefined behavior).
15417 QualType PromoteType;
15418 if (TInfo->getType()->isPromotableIntegerType()) {
15419 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15420 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15421 PromoteType = QualType();
15422 }
15423 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15424 PromoteType = Context.DoubleTy;
15425 if (!PromoteType.isNull())
15426 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15427 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15428 << TInfo->getType()
15429 << PromoteType
15430 << TInfo->getTypeLoc().getSourceRange());
15431 }
15432
15433 QualType T = TInfo->getType().getNonLValueExprType(Context);
15434 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15435}
15436
15437ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15438 // The type of __null will be int or long, depending on the size of
15439 // pointers on the target.
15440 QualType Ty;
15441 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15442 if (pw == Context.getTargetInfo().getIntWidth())
15443 Ty = Context.IntTy;
15444 else if (pw == Context.getTargetInfo().getLongWidth())
15445 Ty = Context.LongTy;
15446 else if (pw == Context.getTargetInfo().getLongLongWidth())
15447 Ty = Context.LongLongTy;
15448 else {
15449 llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15449)
;
15450 }
15451
15452 return new (Context) GNUNullExpr(Ty, TokenLoc);
15453}
15454
15455ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15456 SourceLocation BuiltinLoc,
15457 SourceLocation RPLoc) {
15458 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15459}
15460
15461ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15462 SourceLocation BuiltinLoc,
15463 SourceLocation RPLoc,
15464 DeclContext *ParentContext) {
15465 return new (Context)
15466 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15467}
15468
15469bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15470 bool Diagnose) {
15471 if (!getLangOpts().ObjC)
15472 return false;
15473
15474 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15475 if (!PT)
15476 return false;
15477 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15478
15479 // Ignore any parens, implicit casts (should only be
15480 // array-to-pointer decays), and not-so-opaque values. The last is
15481 // important for making this trigger for property assignments.
15482 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15483 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15484 if (OV->getSourceExpr())
15485 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15486
15487 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15488 if (!PT->isObjCIdType() &&
15489 !(ID && ID->getIdentifier()->isStr("NSString")))
15490 return false;
15491 if (!SL->isAscii())
15492 return false;
15493
15494 if (Diagnose) {
15495 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15496 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15497 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15498 }
15499 return true;
15500 }
15501
15502 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15503 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15504 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15505 !SrcExpr->isNullPointerConstant(
15506 getASTContext(), Expr::NPC_NeverValueDependent)) {
15507 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15508 return false;
15509 if (Diagnose) {
15510 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15511 << /*number*/1
15512 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15513 Expr *NumLit =
15514 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15515 if (NumLit)
15516 Exp = NumLit;
15517 }
15518 return true;
15519 }
15520
15521 return false;
15522}
15523
15524static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15525 const Expr *SrcExpr) {
15526 if (!DstType->isFunctionPointerType() ||
15527 !SrcExpr->getType()->isFunctionType())
15528 return false;
15529
15530 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15531 if (!DRE)
15532 return false;
15533
15534 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15535 if (!FD)
15536 return false;
15537
15538 return !S.checkAddressOfFunctionIsAvailable(FD,
15539 /*Complain=*/true,
15540 SrcExpr->getBeginLoc());
15541}
15542
15543bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15544 SourceLocation Loc,
15545 QualType DstType, QualType SrcType,
15546 Expr *SrcExpr, AssignmentAction Action,
15547 bool *Complained) {
15548 if (Complained)
15549 *Complained = false;
15550
15551 // Decode the result (notice that AST's are still created for extensions).
15552 bool CheckInferredResultType = false;
15553 bool isInvalid = false;
15554 unsigned DiagKind = 0;
15555 ConversionFixItGenerator ConvHints;
15556 bool MayHaveConvFixit = false;
15557 bool MayHaveFunctionDiff = false;
15558 const ObjCInterfaceDecl *IFace = nullptr;
15559 const ObjCProtocolDecl *PDecl = nullptr;
15560
15561 switch (ConvTy) {
15562 case Compatible:
15563 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15564 return false;
15565
15566 case PointerToInt:
15567 if (getLangOpts().CPlusPlus) {
15568 DiagKind = diag::err_typecheck_convert_pointer_int;
15569 isInvalid = true;
15570 } else {
15571 DiagKind = diag::ext_typecheck_convert_pointer_int;
15572 }
15573 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15574 MayHaveConvFixit = true;
15575 break;
15576 case IntToPointer:
15577 if (getLangOpts().CPlusPlus) {
15578 DiagKind = diag::err_typecheck_convert_int_pointer;
15579 isInvalid = true;
15580 } else {
15581 DiagKind = diag::ext_typecheck_convert_int_pointer;
15582 }
15583 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15584 MayHaveConvFixit = true;
15585 break;
15586 case IncompatibleFunctionPointer:
15587 if (getLangOpts().CPlusPlus) {
15588 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15589 isInvalid = true;
15590 } else {
15591 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15592 }
15593 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15594 MayHaveConvFixit = true;
15595 break;
15596 case IncompatiblePointer:
15597 if (Action == AA_Passing_CFAudited) {
15598 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15599 } else if (getLangOpts().CPlusPlus) {
15600 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15601 isInvalid = true;
15602 } else {
15603 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15604 }
15605 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15606 SrcType->isObjCObjectPointerType();
15607 if (!CheckInferredResultType) {
15608 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15609 } else if (CheckInferredResultType) {
15610 SrcType = SrcType.getUnqualifiedType();
15611 DstType = DstType.getUnqualifiedType();
15612 }
15613 MayHaveConvFixit = true;
15614 break;
15615 case IncompatiblePointerSign:
15616 if (getLangOpts().CPlusPlus) {
15617 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15618 isInvalid = true;
15619 } else {
15620 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15621 }
15622 break;
15623 case FunctionVoidPointer:
15624 if (getLangOpts().CPlusPlus) {
15625 DiagKind = diag::err_typecheck_convert_pointer_void_func;
15626 isInvalid = true;
15627 } else {
15628 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15629 }
15630 break;
15631 case IncompatiblePointerDiscardsQualifiers: {
15632 // Perform array-to-pointer decay if necessary.
15633 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15634
15635 isInvalid = true;
15636
15637 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15638 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15639 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15640 DiagKind = diag::err_typecheck_incompatible_address_space;
15641 break;
15642
15643 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15644 DiagKind = diag::err_typecheck_incompatible_ownership;
15645 break;
15646 }
15647
15648 llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15648)
;
15649 // fallthrough
15650 }
15651 case CompatiblePointerDiscardsQualifiers:
15652 // If the qualifiers lost were because we were applying the
15653 // (deprecated) C++ conversion from a string literal to a char*
15654 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
15655 // Ideally, this check would be performed in
15656 // checkPointerTypesForAssignment. However, that would require a
15657 // bit of refactoring (so that the second argument is an
15658 // expression, rather than a type), which should be done as part
15659 // of a larger effort to fix checkPointerTypesForAssignment for
15660 // C++ semantics.
15661 if (getLangOpts().CPlusPlus &&
15662 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15663 return false;
15664 if (getLangOpts().CPlusPlus) {
15665 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
15666 isInvalid = true;
15667 } else {
15668 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
15669 }
15670
15671 break;
15672 case IncompatibleNestedPointerQualifiers:
15673 if (getLangOpts().CPlusPlus) {
15674 isInvalid = true;
15675 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15676 } else {
15677 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15678 }
15679 break;
15680 case IncompatibleNestedPointerAddressSpaceMismatch:
15681 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15682 isInvalid = true;
15683 break;
15684 case IntToBlockPointer:
15685 DiagKind = diag::err_int_to_block_pointer;
15686 isInvalid = true;
15687 break;
15688 case IncompatibleBlockPointer:
15689 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15690 isInvalid = true;
15691 break;
15692 case IncompatibleObjCQualifiedId: {
15693 if (SrcType->isObjCQualifiedIdType()) {
15694 const ObjCObjectPointerType *srcOPT =
15695 SrcType->castAs<ObjCObjectPointerType>();
15696 for (auto *srcProto : srcOPT->quals()) {
15697 PDecl = srcProto;
15698 break;
15699 }
15700 if (const ObjCInterfaceType *IFaceT =
15701 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15702 IFace = IFaceT->getDecl();
15703 }
15704 else if (DstType->isObjCQualifiedIdType()) {
15705 const ObjCObjectPointerType *dstOPT =
15706 DstType->castAs<ObjCObjectPointerType>();
15707 for (auto *dstProto : dstOPT->quals()) {
15708 PDecl = dstProto;
15709 break;
15710 }
15711 if (const ObjCInterfaceType *IFaceT =
15712 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15713 IFace = IFaceT->getDecl();
15714 }
15715 if (getLangOpts().CPlusPlus) {
15716 DiagKind = diag::err_incompatible_qualified_id;
15717 isInvalid = true;
15718 } else {
15719 DiagKind = diag::warn_incompatible_qualified_id;
15720 }
15721 break;
15722 }
15723 case IncompatibleVectors:
15724 if (getLangOpts().CPlusPlus) {
15725 DiagKind = diag::err_incompatible_vectors;
15726 isInvalid = true;
15727 } else {
15728 DiagKind = diag::warn_incompatible_vectors;
15729 }
15730 break;
15731 case IncompatibleObjCWeakRef:
15732 DiagKind = diag::err_arc_weak_unavailable_assign;
15733 isInvalid = true;
15734 break;
15735 case Incompatible:
15736 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15737 if (Complained)
15738 *Complained = true;
15739 return true;
15740 }
15741
15742 DiagKind = diag::err_typecheck_convert_incompatible;
15743 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15744 MayHaveConvFixit = true;
15745 isInvalid = true;
15746 MayHaveFunctionDiff = true;
15747 break;
15748 }
15749
15750 QualType FirstType, SecondType;
15751 switch (Action) {
15752 case AA_Assigning:
15753 case AA_Initializing:
15754 // The destination type comes first.
15755 FirstType = DstType;
15756 SecondType = SrcType;
15757 break;
15758
15759 case AA_Returning:
15760 case AA_Passing:
15761 case AA_Passing_CFAudited:
15762 case AA_Converting:
15763 case AA_Sending:
15764 case AA_Casting:
15765 // The source type comes first.
15766 FirstType = SrcType;
15767 SecondType = DstType;
15768 break;
15769 }
15770
15771 PartialDiagnostic FDiag = PDiag(DiagKind);
15772 if (Action == AA_Passing_CFAudited)
15773 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15774 else
15775 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15776
15777 // If we can fix the conversion, suggest the FixIts.
15778 if (!ConvHints.isNull()) {
15779 for (FixItHint &H : ConvHints.Hints)
15780 FDiag << H;
15781 }
15782
15783 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15784
15785 if (MayHaveFunctionDiff)
15786 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15787
15788 Diag(Loc, FDiag);
15789 if ((DiagKind == diag::warn_incompatible_qualified_id ||
15790 DiagKind == diag::err_incompatible_qualified_id) &&
15791 PDecl && IFace && !IFace->hasDefinition())
15792 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15793 << IFace << PDecl;
15794
15795 if (SecondType == Context.OverloadTy)
15796 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15797 FirstType, /*TakingAddress=*/true);
15798
15799 if (CheckInferredResultType)
15800 EmitRelatedResultTypeNote(SrcExpr);
15801
15802 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15803 EmitRelatedResultTypeNoteForReturn(DstType);
15804
15805 if (Complained)
15806 *Complained = true;
15807 return isInvalid;
15808}
15809
15810ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15811 llvm::APSInt *Result) {
15812 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15813 public:
15814 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15815 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15816 }
15817 } Diagnoser;
15818
15819 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15820}
15821
15822ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15823 llvm::APSInt *Result,
15824 unsigned DiagID,
15825 bool AllowFold) {
15826 class IDDiagnoser : public VerifyICEDiagnoser {
15827 unsigned DiagID;
15828
15829 public:
15830 IDDiagnoser(unsigned DiagID)
15831 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15832
15833 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15834 S.Diag(Loc, DiagID) << SR;
15835 }
15836 } Diagnoser(DiagID);
15837
15838 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15839}
15840
15841void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15842 SourceRange SR) {
15843 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15844}
15845
15846ExprResult
15847Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15848 VerifyICEDiagnoser &Diagnoser,
15849 bool AllowFold) {
15850 SourceLocation DiagLoc = E->getBeginLoc();
15851
15852 if (getLangOpts().CPlusPlus11) {
15853 // C++11 [expr.const]p5:
15854 // If an expression of literal class type is used in a context where an
15855 // integral constant expression is required, then that class type shall
15856 // have a single non-explicit conversion function to an integral or
15857 // unscoped enumeration type
15858 ExprResult Converted;
15859 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15860 public:
15861 CXX11ConvertDiagnoser(bool Silent)
15862 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15863 Silent, true) {}
15864
15865 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15866 QualType T) override {
15867 return S.Diag(Loc, diag::err_ice_not_integral) << T;
15868 }
15869
15870 SemaDiagnosticBuilder diagnoseIncomplete(
15871 Sema &S, SourceLocation Loc, QualType T) override {
15872 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15873 }
15874
15875 SemaDiagnosticBuilder diagnoseExplicitConv(
15876 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15877 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15878 }
15879
15880 SemaDiagnosticBuilder noteExplicitConv(
15881 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15882 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15883 << ConvTy->isEnumeralType() << ConvTy;
15884 }
15885
15886 SemaDiagnosticBuilder diagnoseAmbiguous(
15887 Sema &S, SourceLocation Loc, QualType T) override {
15888 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15889 }
15890
15891 SemaDiagnosticBuilder noteAmbiguous(
15892 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15893 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15894 << ConvTy->isEnumeralType() << ConvTy;
15895 }
15896
15897 SemaDiagnosticBuilder diagnoseConversion(
15898 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15899 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 15899)
;
15900 }
15901 } ConvertDiagnoser(Diagnoser.Suppress);
15902
15903 Converted = PerformContextualImplicitConversion(DiagLoc, E,
15904 ConvertDiagnoser);
15905 if (Converted.isInvalid())
15906 return Converted;
15907 E = Converted.get();
15908 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15909 return ExprError();
15910 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15911 // An ICE must be of integral or unscoped enumeration type.
15912 if (!Diagnoser.Suppress)
15913 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15914 return ExprError();
15915 }
15916
15917 ExprResult RValueExpr = DefaultLvalueConversion(E);
15918 if (RValueExpr.isInvalid())
15919 return ExprError();
15920
15921 E = RValueExpr.get();
15922
15923 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15924 // in the non-ICE case.
15925 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15926 if (Result)
15927 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15928 if (!isa<ConstantExpr>(E))
15929 E = ConstantExpr::Create(Context, E);
15930 return E;
15931 }
15932
15933 Expr::EvalResult EvalResult;
15934 SmallVector<PartialDiagnosticAt, 8> Notes;
15935 EvalResult.Diag = &Notes;
15936
15937 // Try to evaluate the expression, and produce diagnostics explaining why it's
15938 // not a constant expression as a side-effect.
15939 bool Folded =
15940 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15941 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15942
15943 if (!isa<ConstantExpr>(E))
15944 E = ConstantExpr::Create(Context, E, EvalResult.Val);
15945
15946 // In C++11, we can rely on diagnostics being produced for any expression
15947 // which is not a constant expression. If no diagnostics were produced, then
15948 // this is a constant expression.
15949 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15950 if (Result)
15951 *Result = EvalResult.Val.getInt();
15952 return E;
15953 }
15954
15955 // If our only note is the usual "invalid subexpression" note, just point
15956 // the caret at its location rather than producing an essentially
15957 // redundant note.
15958 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15959 diag::note_invalid_subexpr_in_const_expr) {
15960 DiagLoc = Notes[0].first;
15961 Notes.clear();
15962 }
15963
15964 if (!Folded || !AllowFold) {
15965 if (!Diagnoser.Suppress) {
15966 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15967 for (const PartialDiagnosticAt &Note : Notes)
15968 Diag(Note.first, Note.second);
15969 }
15970
15971 return ExprError();
15972 }
15973
15974 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15975 for (const PartialDiagnosticAt &Note : Notes)
15976 Diag(Note.first, Note.second);
15977
15978 if (Result)
15979 *Result = EvalResult.Val.getInt();
15980 return E;
15981}
15982
15983namespace {
15984 // Handle the case where we conclude a expression which we speculatively
15985 // considered to be unevaluated is actually evaluated.
15986 class TransformToPE : public TreeTransform<TransformToPE> {
15987 typedef TreeTransform<TransformToPE> BaseTransform;
15988
15989 public:
15990 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15991
15992 // Make sure we redo semantic analysis
15993 bool AlwaysRebuild() { return true; }
15994 bool ReplacingOriginal() { return true; }
15995
15996 // We need to special-case DeclRefExprs referring to FieldDecls which
15997 // are not part of a member pointer formation; normal TreeTransforming
15998 // doesn't catch this case because of the way we represent them in the AST.
15999 // FIXME: This is a bit ugly; is it really the best way to handle this
16000 // case?
16001 //
16002 // Error on DeclRefExprs referring to FieldDecls.
16003 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16004 if (isa<FieldDecl>(E->getDecl()) &&
16005 !SemaRef.isUnevaluatedContext())
16006 return SemaRef.Diag(E->getLocation(),
16007 diag::err_invalid_non_static_member_use)
16008 << E->getDecl() << E->getSourceRange();
16009
16010 return BaseTransform::TransformDeclRefExpr(E);
16011 }
16012
16013 // Exception: filter out member pointer formation
16014 ExprResult TransformUnaryOperator(UnaryOperator *E) {
16015 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16016 return E;
16017
16018 return BaseTransform::TransformUnaryOperator(E);
16019 }
16020
16021 // The body of a lambda-expression is in a separate expression evaluation
16022 // context so never needs to be transformed.
16023 // FIXME: Ideally we wouldn't transform the closure type either, and would
16024 // just recreate the capture expressions and lambda expression.
16025 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16026 return SkipLambdaBody(E, Body);
16027 }
16028 };
16029}
16030
16031ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16032 assert(isUnevaluatedContext() &&((isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16033, __PRETTY_FUNCTION__))
16033 "Should only transform unevaluated expressions")((isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16033, __PRETTY_FUNCTION__))
;
16034 ExprEvalContexts.back().Context =
16035 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16036 if (isUnevaluatedContext())
16037 return E;
16038 return TransformToPE(*this).TransformExpr(E);
16039}
16040
16041void
16042Sema::PushExpressionEvaluationContext(
16043 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16044 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16045 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16046 LambdaContextDecl, ExprContext);
16047 Cleanup.reset();
16048 if (!MaybeODRUseExprs.empty())
16049 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16050}
16051
16052void
16053Sema::PushExpressionEvaluationContext(
16054 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16055 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16056 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16057 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16058}
16059
16060namespace {
16061
16062const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16063 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16064 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16065 if (E->getOpcode() == UO_Deref)
16066 return CheckPossibleDeref(S, E->getSubExpr());
16067 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16068 return CheckPossibleDeref(S, E->getBase());
16069 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16070 return CheckPossibleDeref(S, E->getBase());
16071 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16072 QualType Inner;
16073 QualType Ty = E->getType();
16074 if (const auto *Ptr = Ty->getAs<PointerType>())
16075 Inner = Ptr->getPointeeType();
16076 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16077 Inner = Arr->getElementType();
16078 else
16079 return nullptr;
16080
16081 if (Inner->hasAttr(attr::NoDeref))
16082 return E;
16083 }
16084 return nullptr;
16085}
16086
16087} // namespace
16088
16089void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16090 for (const Expr *E : Rec.PossibleDerefs) {
16091 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16092 if (DeclRef) {
16093 const ValueDecl *Decl = DeclRef->getDecl();
16094 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16095 << Decl->getName() << E->getSourceRange();
16096 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16097 } else {
16098 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16099 << E->getSourceRange();
16100 }
16101 }
16102 Rec.PossibleDerefs.clear();
16103}
16104
16105/// Check whether E, which is either a discarded-value expression or an
16106/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16107/// and if so, remove it from the list of volatile-qualified assignments that
16108/// we are going to warn are deprecated.
16109void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16110 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16111 return;
16112
16113 // Note: ignoring parens here is not justified by the standard rules, but
16114 // ignoring parentheses seems like a more reasonable approach, and this only
16115 // drives a deprecation warning so doesn't affect conformance.
16116 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16117 if (BO->getOpcode() == BO_Assign) {
16118 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16119 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16120 LHSs.end());
16121 }
16122 }
16123}
16124
16125ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16126 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16127 RebuildingImmediateInvocation)
16128 return E;
16129
16130 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16131 /// It's OK if this fails; we'll also remove this in
16132 /// HandleImmediateInvocations, but catching it here allows us to avoid
16133 /// walking the AST looking for it in simple cases.
16134 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16135 if (auto *DeclRef =
16136 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16137 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16138
16139 E = MaybeCreateExprWithCleanups(E);
16140
16141 ConstantExpr *Res = ConstantExpr::Create(
16142 getASTContext(), E.get(),
16143 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16144 getASTContext()),
16145 /*IsImmediateInvocation*/ true);
16146 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16147 return Res;
16148}
16149
16150static void EvaluateAndDiagnoseImmediateInvocation(
16151 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16152 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16153 Expr::EvalResult Eval;
16154 Eval.Diag = &Notes;
16155 ConstantExpr *CE = Candidate.getPointer();
16156 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16157 SemaRef.getASTContext(), true);
16158 if (!Result || !Notes.empty()) {
16159 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16160 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16161 InnerExpr = FunctionalCast->getSubExpr();
16162 FunctionDecl *FD = nullptr;
16163 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16164 FD = cast<FunctionDecl>(Call->getCalleeDecl());
16165 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16166 FD = Call->getConstructor();
16167 else
16168 llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16168)
;
16169 assert(FD->isConsteval())((FD->isConsteval()) ? static_cast<void> (0) : __assert_fail
("FD->isConsteval()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16169, __PRETTY_FUNCTION__))
;
16170 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16171 for (auto &Note : Notes)
16172 SemaRef.Diag(Note.first, Note.second);
16173 return;
16174 }
16175 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16176}
16177
16178static void RemoveNestedImmediateInvocation(
16179 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16180 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16181 struct ComplexRemove : TreeTransform<ComplexRemove> {
16182 using Base = TreeTransform<ComplexRemove>;
16183 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16184 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16185 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16186 CurrentII;
16187 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16188 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16189 SmallVector<Sema::ImmediateInvocationCandidate,
16190 4>::reverse_iterator Current)
16191 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16192 void RemoveImmediateInvocation(ConstantExpr* E) {
16193 auto It = std::find_if(CurrentII, IISet.rend(),
16194 [E](Sema::ImmediateInvocationCandidate Elem) {
16195 return Elem.getPointer() == E;
16196 });
16197 assert(It != IISet.rend() &&((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? static_cast<void> (0) : __assert_fail (
"It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16199, __PRETTY_FUNCTION__))
16198 "ConstantExpr marked IsImmediateInvocation should "((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? static_cast<void> (0) : __assert_fail (
"It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16199, __PRETTY_FUNCTION__))
16199 "be present")((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? static_cast<void> (0) : __assert_fail (
"It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16199, __PRETTY_FUNCTION__))
;
16200 It->setInt(1); // Mark as deleted
16201 }
16202 ExprResult TransformConstantExpr(ConstantExpr *E) {
16203 if (!E->isImmediateInvocation())
16204 return Base::TransformConstantExpr(E);
16205 RemoveImmediateInvocation(E);
16206 return Base::TransformExpr(E->getSubExpr());
16207 }
16208 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16209 /// we need to remove its DeclRefExpr from the DRSet.
16210 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16211 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16212 return Base::TransformCXXOperatorCallExpr(E);
16213 }
16214 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16215 /// here.
16216 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16217 if (!Init)
16218 return Init;
16219 /// ConstantExpr are the first layer of implicit node to be removed so if
16220 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16221 if (auto *CE = dyn_cast<ConstantExpr>(Init))
16222 if (CE->isImmediateInvocation())
16223 RemoveImmediateInvocation(CE);
16224 return Base::TransformInitializer(Init, NotCopyInit);
16225 }
16226 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16227 DRSet.erase(E);
16228 return E;
16229 }
16230 bool AlwaysRebuild() { return false; }
16231 bool ReplacingOriginal() { return true; }
16232 bool AllowSkippingCXXConstructExpr() {
16233 bool Res = AllowSkippingFirstCXXConstructExpr;
16234 AllowSkippingFirstCXXConstructExpr = true;
16235 return Res;
16236 }
16237 bool AllowSkippingFirstCXXConstructExpr = true;
16238 } Transformer(SemaRef, Rec.ReferenceToConsteval,
16239 Rec.ImmediateInvocationCandidates, It);
16240
16241 /// CXXConstructExpr with a single argument are getting skipped by
16242 /// TreeTransform in some situtation because they could be implicit. This
16243 /// can only occur for the top-level CXXConstructExpr because it is used
16244 /// nowhere in the expression being transformed therefore will not be rebuilt.
16245 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16246 /// skipping the first CXXConstructExpr.
16247 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16248 Transformer.AllowSkippingFirstCXXConstructExpr = false;
16249
16250 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16251 assert(Res.isUsable())((Res.isUsable()) ? static_cast<void> (0) : __assert_fail
("Res.isUsable()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16251, __PRETTY_FUNCTION__))
;
16252 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16253 It->getPointer()->setSubExpr(Res.get());
16254}
16255
16256static void
16257HandleImmediateInvocations(Sema &SemaRef,
16258 Sema::ExpressionEvaluationContextRecord &Rec) {
16259 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16260 Rec.ReferenceToConsteval.size() == 0) ||
16261 SemaRef.RebuildingImmediateInvocation)
16262 return;
16263
16264 /// When we have more then 1 ImmediateInvocationCandidates we need to check
16265 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16266 /// need to remove ReferenceToConsteval in the immediate invocation.
16267 if (Rec.ImmediateInvocationCandidates.size() > 1) {
16268
16269 /// Prevent sema calls during the tree transform from adding pointers that
16270 /// are already in the sets.
16271 llvm::SaveAndRestore<bool> DisableIITracking(
16272 SemaRef.RebuildingImmediateInvocation, true);
16273
16274 /// Prevent diagnostic during tree transfrom as they are duplicates
16275 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16276
16277 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16278 It != Rec.ImmediateInvocationCandidates.rend(); It++)
16279 if (!It->getInt())
16280 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16281 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16282 Rec.ReferenceToConsteval.size()) {
16283 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16284 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16285 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16286 bool VisitDeclRefExpr(DeclRefExpr *E) {
16287 DRSet.erase(E);
16288 return DRSet.size();
16289 }
16290 } Visitor(Rec.ReferenceToConsteval);
16291 Visitor.TraverseStmt(
16292 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16293 }
16294 for (auto CE : Rec.ImmediateInvocationCandidates)
16295 if (!CE.getInt())
16296 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16297 for (auto DR : Rec.ReferenceToConsteval) {
16298 auto *FD = cast<FunctionDecl>(DR->getDecl());
16299 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16300 << FD;
16301 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16302 }
16303}
16304
16305void Sema::PopExpressionEvaluationContext() {
16306 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16307 unsigned NumTypos = Rec.NumTypos;
16308
16309 if (!Rec.Lambdas.empty()) {
16310 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16311 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16312 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16313 unsigned D;
16314 if (Rec.isUnevaluated()) {
16315 // C++11 [expr.prim.lambda]p2:
16316 // A lambda-expression shall not appear in an unevaluated operand
16317 // (Clause 5).
16318 D = diag::err_lambda_unevaluated_operand;
16319 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16320 // C++1y [expr.const]p2:
16321 // A conditional-expression e is a core constant expression unless the
16322 // evaluation of e, following the rules of the abstract machine, would
16323 // evaluate [...] a lambda-expression.
16324 D = diag::err_lambda_in_constant_expression;
16325 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16326 // C++17 [expr.prim.lamda]p2:
16327 // A lambda-expression shall not appear [...] in a template-argument.
16328 D = diag::err_lambda_in_invalid_context;
16329 } else
16330 llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message."
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16330)
;
16331
16332 for (const auto *L : Rec.Lambdas)
16333 Diag(L->getBeginLoc(), D);
16334 }
16335 }
16336
16337 WarnOnPendingNoDerefs(Rec);
16338 HandleImmediateInvocations(*this, Rec);
16339
16340 // Warn on any volatile-qualified simple-assignments that are not discarded-
16341 // value expressions nor unevaluated operands (those cases get removed from
16342 // this list by CheckUnusedVolatileAssignment).
16343 for (auto *BO : Rec.VolatileAssignmentLHSs)
16344 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16345 << BO->getType();
16346
16347 // When are coming out of an unevaluated context, clear out any
16348 // temporaries that we may have created as part of the evaluation of
16349 // the expression in that context: they aren't relevant because they
16350 // will never be constructed.
16351 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16352 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16353 ExprCleanupObjects.end());
16354 Cleanup = Rec.ParentCleanup;
16355 CleanupVarDeclMarking();
16356 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16357 // Otherwise, merge the contexts together.
16358 } else {
16359 Cleanup.mergeFrom(Rec.ParentCleanup);
16360 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16361 Rec.SavedMaybeODRUseExprs.end());
16362 }
16363
16364 // Pop the current expression evaluation context off the stack.
16365 ExprEvalContexts.pop_back();
16366
16367 // The global expression evaluation context record is never popped.
16368 ExprEvalContexts.back().NumTypos += NumTypos;
16369}
16370
16371void Sema::DiscardCleanupsInEvaluationContext() {
16372 ExprCleanupObjects.erase(
16373 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16374 ExprCleanupObjects.end());
16375 Cleanup.reset();
16376 MaybeODRUseExprs.clear();
16377}
16378
16379ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16380 ExprResult Result = CheckPlaceholderExpr(E);
16381 if (Result.isInvalid())
16382 return ExprError();
16383 E = Result.get();
16384 if (!E->getType()->isVariablyModifiedType())
16385 return E;
16386 return TransformToPotentiallyEvaluated(E);
16387}
16388
16389/// Are we in a context that is potentially constant evaluated per C++20
16390/// [expr.const]p12?
16391static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16392 /// C++2a [expr.const]p12:
16393 // An expression or conversion is potentially constant evaluated if it is
16394 switch (SemaRef.ExprEvalContexts.back().Context) {
16395 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16396 // -- a manifestly constant-evaluated expression,
16397 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16398 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16399 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16400 // -- a potentially-evaluated expression,
16401 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16402 // -- an immediate subexpression of a braced-init-list,
16403
16404 // -- [FIXME] an expression of the form & cast-expression that occurs
16405 // within a templated entity
16406 // -- a subexpression of one of the above that is not a subexpression of
16407 // a nested unevaluated operand.
16408 return true;
16409
16410 case Sema::ExpressionEvaluationContext::Unevaluated:
16411 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16412 // Expressions in this context are never evaluated.
16413 return false;
16414 }
16415 llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16415)
;
16416}
16417
16418/// Return true if this function has a calling convention that requires mangling
16419/// in the size of the parameter pack.
16420static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16421 // These manglings don't do anything on non-Windows or non-x86 platforms, so
16422 // we don't need parameter type sizes.
16423 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16424 if (!TT.isOSWindows() || !TT.isX86())
16425 return false;
16426
16427 // If this is C++ and this isn't an extern "C" function, parameters do not
16428 // need to be complete. In this case, C++ mangling will apply, which doesn't
16429 // use the size of the parameters.
16430 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16431 return false;
16432
16433 // Stdcall, fastcall, and vectorcall need this special treatment.
16434 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16435 switch (CC) {
16436 case CC_X86StdCall:
16437 case CC_X86FastCall:
16438 case CC_X86VectorCall:
16439 return true;
16440 default:
16441 break;
16442 }
16443 return false;
16444}
16445
16446/// Require that all of the parameter types of function be complete. Normally,
16447/// parameter types are only required to be complete when a function is called
16448/// or defined, but to mangle functions with certain calling conventions, the
16449/// mangler needs to know the size of the parameter list. In this situation,
16450/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16451/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16452/// result in a linker error. Clang doesn't implement this behavior, and instead
16453/// attempts to error at compile time.
16454static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16455 SourceLocation Loc) {
16456 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16457 FunctionDecl *FD;
16458 ParmVarDecl *Param;
16459
16460 public:
16461 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16462 : FD(FD), Param(Param) {}
16463
16464 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16465 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16466 StringRef CCName;
16467 switch (CC) {
16468 case CC_X86StdCall:
16469 CCName = "stdcall";
16470 break;
16471 case CC_X86FastCall:
16472 CCName = "fastcall";
16473 break;
16474 case CC_X86VectorCall:
16475 CCName = "vectorcall";
16476 break;
16477 default:
16478 llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16478)
;
16479 }
16480
16481 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16482 << Param->getDeclName() << FD->getDeclName() << CCName;
16483 }
16484 };
16485
16486 for (ParmVarDecl *Param : FD->parameters()) {
16487 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16488 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16489 }
16490}
16491
16492namespace {
16493enum class OdrUseContext {
16494 /// Declarations in this context are not odr-used.
16495 None,
16496 /// Declarations in this context are formally odr-used, but this is a
16497 /// dependent context.
16498 Dependent,
16499 /// Declarations in this context are odr-used but not actually used (yet).
16500 FormallyOdrUsed,
16501 /// Declarations in this context are used.
16502 Used
16503};
16504}
16505
16506/// Are we within a context in which references to resolved functions or to
16507/// variables result in odr-use?
16508static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16509 OdrUseContext Result;
16510
16511 switch (SemaRef.ExprEvalContexts.back().Context) {
16512 case Sema::ExpressionEvaluationContext::Unevaluated:
16513 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16514 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16515 return OdrUseContext::None;
16516
16517 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16518 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16519 Result = OdrUseContext::Used;
16520 break;
16521
16522 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16523 Result = OdrUseContext::FormallyOdrUsed;
16524 break;
16525
16526 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16527 // A default argument formally results in odr-use, but doesn't actually
16528 // result in a use in any real sense until it itself is used.
16529 Result = OdrUseContext::FormallyOdrUsed;
16530 break;
16531 }
16532
16533 if (SemaRef.CurContext->isDependentContext())
16534 return OdrUseContext::Dependent;
16535
16536 return Result;
16537}
16538
16539static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16540 return Func->isConstexpr() &&
16541 (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16542}
16543
16544/// Mark a function referenced, and check whether it is odr-used
16545/// (C++ [basic.def.odr]p2, C99 6.9p3)
16546void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16547 bool MightBeOdrUse) {
16548 assert(Func && "No function?")((Func && "No function?") ? static_cast<void> (
0) : __assert_fail ("Func && \"No function?\"", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 16548, __PRETTY_FUNCTION__))
;
16549
16550 Func->setReferenced();
16551
16552 // Recursive functions aren't really used until they're used from some other
16553 // context.
16554 bool IsRecursiveCall = CurContext == Func;
16555
16556 // C++11 [basic.def.odr]p3:
16557 // A function whose name appears as a potentially-evaluated expression is
16558 // odr-used if it is the unique lookup result or the selected member of a
16559 // set of overloaded functions [...].
16560 //
16561 // We (incorrectly) mark overload resolution as an unevaluated context, so we
16562 // can just check that here.
16563 OdrUseContext OdrUse =
16564 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16565 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16566 OdrUse = OdrUseContext::FormallyOdrUsed;
16567
16568 // Trivial default constructors and destructors are never actually used.
16569 // FIXME: What about other special members?
16570 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16571 OdrUse == OdrUseContext::Used) {
16572 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16573 if (Constructor->isDefaultConstructor())
16574 OdrUse = OdrUseContext::FormallyOdrUsed;
16575 if (isa<CXXDestructorDecl>(Func))
16576 OdrUse = OdrUseContext::FormallyOdrUsed;
16577 }
16578
16579 // C++20 [expr.const]p12:
16580 // A function [...] is needed for constant evaluation if it is [...] a
16581 // constexpr function that is named by an expression that is potentially
16582 // constant evaluated
16583 bool NeededForConstantEvaluation =
16584 isPotentiallyConstantEvaluatedContext(*this) &&
16585 isImplicitlyDefinableConstexprFunction(Func);
16586
16587 // Determine whether we require a function definition to exist, per
16588 // C++11 [temp.inst]p3:
16589 // Unless a function template specialization has been explicitly
16590 // instantiated or explicitly specialized, the function template
16591 // specialization is implicitly instantiated when the specialization is
16592 // referenced in a context that requires a function definition to exist.
16593 // C++20 [temp.inst]p7:
16594 // The existence of a definition of a [...] function is considered to
16595 // affect the semantics of the program if the [...] function is needed for
16596 // constant evaluation by an expression
16597 // C++20 [basic.def.odr]p10:
16598 // Every program shall contain exactly one definition of every non-inline
16599 // function or variable that is odr-used in that program outside of a
16600 // discarded statement
16601 // C++20 [special]p1:
16602 // The implementation will implicitly define [defaulted special members]
16603 // if they are odr-used or needed for constant evaluation.
16604 //
16605 // Note that we skip the implicit instantiation of templates that are only
16606 // used in unused default arguments or by recursive calls to themselves.
16607 // This is formally non-conforming, but seems reasonable in practice.
16608 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16609 NeededForConstantEvaluation);
16610
16611 // C++14 [temp.expl.spec]p6:
16612 // If a template [...] is explicitly specialized then that specialization
16613 // shall be declared before the first use of that specialization that would
16614 // cause an implicit instantiation to take place, in every translation unit
16615 // in which such a use occurs
16616 if (NeedDefinition &&
16617 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16618 Func->getMemberSpecializationInfo()))
16619 checkSpecializationVisibility(Loc, Func);
16620
16621 if (getLangOpts().CUDA)
16622 CheckCUDACall(Loc, Func);
16623
16624 if (getLangOpts().SYCLIsDevice)
16625 checkSYCLDeviceFunction(Loc, Func);
16626
16627 // If we need a definition, try to create one.
16628 if (NeedDefinition && !Func->getBody()) {
16629 runWithSufficientStackSpace(Loc, [&] {
16630 if (CXXConstructorDecl *Constructor =
16631 dyn_cast<CXXConstructorDecl>(Func)) {
16632 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16633 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16634 if (Constructor->isDefaultConstructor()) {
16635 if (Constructor->isTrivial() &&
16636 !Constructor->hasAttr<DLLExportAttr>())
16637 return;
16638 DefineImplicitDefaultConstructor(Loc, Constructor);
16639 } else if (Constructor->isCopyConstructor()) {
16640 DefineImplicitCopyConstructor(Loc, Constructor);
16641 } else if (Constructor->isMoveConstructor()) {
16642 DefineImplicitMoveConstructor(Loc, Constructor);
16643 }
16644 } else if (Constructor->getInheritedConstructor()) {
16645 DefineInheritingConstructor(Loc, Constructor);
16646 }
16647 } else if (CXXDestructorDecl *Destructor =
16648 dyn_cast<CXXDestructorDecl>(Func)) {
16649 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16650 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16651 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16652 return;
16653 DefineImplicitDestructor(Loc, Destructor);
16654 }
16655 if (Destructor->isVirtual() && getLangOpts().AppleKext)
16656 MarkVTableUsed(Loc, Destructor->getParent());
16657 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16658 if (MethodDecl->isOverloadedOperator() &&
16659 MethodDecl->getOverloadedOperator() == OO_Equal) {
16660 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16661 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16662 if (MethodDecl->isCopyAssignmentOperator())
16663 DefineImplicitCopyAssignment(Loc, MethodDecl);
16664 else if (MethodDecl->isMoveAssignmentOperator())
16665 DefineImplicitMoveAssignment(Loc, MethodDecl);
16666 }
16667 } else if (isa<CXXConversionDecl>(MethodDecl) &&
16668 MethodDecl->getParent()->isLambda()) {
16669 CXXConversionDecl *Conversion =
16670 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16671 if (Conversion->isLambdaToBlockPointerConversion())
16672 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16673 else
16674 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16675 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16676 MarkVTableUsed(Loc, MethodDecl->getParent());
16677 }
16678
16679 if (Func->isDefaulted() && !Func->isDeleted()) {
16680 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16681 if (DCK != DefaultedComparisonKind::None)
16682 DefineDefaultedComparison(Loc, Func, DCK);
16683 }
16684
16685 // Implicit instantiation of function templates and member functions of
16686 // class templates.
16687 if (Func->isImplicitlyInstantiable()) {
16688 TemplateSpecializationKind TSK =
16689 Func->getTemplateSpecializationKindForInstantiation();
16690 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16691 bool FirstInstantiation = PointOfInstantiation.isInvalid();
16692 if (FirstInstantiation) {
16693 PointOfInstantiation = Loc;
16694 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16695 } else if (TSK != TSK_ImplicitInstantiation) {
16696 // Use the point of use as the point of instantiation, instead of the
16697 // point of explicit instantiation (which we track as the actual point
16698 // of instantiation). This gives better backtraces in diagnostics.
16699 PointOfInstantiation = Loc;
16700 }
16701
16702 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16703 Func->isConstexpr()) {
16704 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16705 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16706 CodeSynthesisContexts.size())
16707 PendingLocalImplicitInstantiations.push_back(
16708 std::make_pair(Func, PointOfInstantiation));
16709 else if (Func->isConstexpr())
16710 // Do not defer instantiations of constexpr functions, to avoid the
16711 // expression evaluator needing to call back into Sema if it sees a
16712 // call to such a function.
16713 InstantiateFunctionDefinition(PointOfInstantiation, Func);
16714 else {
16715 Func->setInstantiationIsPending(true);
16716 PendingInstantiations.push_back(
16717 std::make_pair(Func, PointOfInstantiation));
16718 // Notify the consumer that a function was implicitly instantiated.
16719 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16720 }
16721 }
16722 } else {
16723 // Walk redefinitions, as some of them may be instantiable.
16724 for (auto i : Func->redecls()) {
16725 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16726 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16727 }
16728 }
16729 });
16730 }
16731
16732 // C++14 [except.spec]p17:
16733 // An exception-specification is considered to be needed when:
16734 // - the function is odr-used or, if it appears in an unevaluated operand,
16735 // would be odr-used if the expression were potentially-evaluated;
16736 //
16737 // Note, we do this even if MightBeOdrUse is false. That indicates that the
16738 // function is a pure virtual function we're calling, and in that case the
16739 // function was selected by overload resolution and we need to resolve its
16740 // exception specification for a different reason.
16741 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16742 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16743 ResolveExceptionSpec(Loc, FPT);
16744
16745 // If this is the first "real" use, act on that.
16746 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16747 // Keep track of used but undefined functions.
16748 if (!Func->isDefined()) {
16749 if (mightHaveNonExternalLinkage(Func))
16750 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16751 else if (Func->getMostRecentDecl()->isInlined() &&
16752 !LangOpts.GNUInline &&
16753 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16754 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16755 else if (isExternalWithNoLinkageType(Func))
16756 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16757 }
16758
16759 // Some x86 Windows calling conventions mangle the size of the parameter
16760 // pack into the name. Computing the size of the parameters requires the
16761 // parameter types to be complete. Check that now.
16762 if (funcHasParameterSizeMangling(*this, Func))
16763 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16764
16765 // In the MS C++ ABI, the compiler emits destructor variants where they are
16766 // used. If the destructor is used here but defined elsewhere, mark the
16767 // virtual base destructors referenced. If those virtual base destructors
16768 // are inline, this will ensure they are defined when emitting the complete
16769 // destructor variant. This checking may be redundant if the destructor is
16770 // provided later in this TU.
16771 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16772 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16773 CXXRecordDecl *Parent = Dtor->getParent();
16774 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16775 CheckCompleteDestructorVariant(Loc, Dtor);
16776 }
16777 }
16778
16779 Func->markUsed(Context);
16780 }
16781}
16782
16783/// Directly mark a variable odr-used. Given a choice, prefer to use
16784/// MarkVariableReferenced since it does additional checks and then
16785/// calls MarkVarDeclODRUsed.
16786/// If the variable must be captured:
16787/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16788/// - else capture it in the DeclContext that maps to the
16789/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16790static void
16791MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16792 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16793 // Keep track of used but undefined variables.
16794 // FIXME: We shouldn't suppress this warning for static data members.
16795 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16796 (!Var->isExternallyVisible() || Var->isInline() ||
16797 SemaRef.isExternalWithNoLinkageType(Var)) &&
16798 !(Var->isStaticDataMember() && Var->hasInit())) {
16799 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16800 if (old.isInvalid())
16801 old = Loc;
16802 }
16803 QualType CaptureType, DeclRefType;
16804 if (SemaRef.LangOpts.OpenMP)
16805 SemaRef.tryCaptureOpenMPLambdas(Var);
16806 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16807 /*EllipsisLoc*/ SourceLocation(),
16808 /*BuildAndDiagnose*/ true,
16809 CaptureType, DeclRefType,
16810 FunctionScopeIndexToStopAt);
16811
16812 Var->markUsed(SemaRef.Context);
16813}
16814
16815void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16816 SourceLocation Loc,
16817 unsigned CapturingScopeIndex) {
16818 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16819}
16820
16821static void
16822diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16823 ValueDecl *var, DeclContext *DC) {
16824 DeclContext *VarDC = var->getDeclContext();
16825
16826 // If the parameter still belongs to the translation unit, then
16827 // we're actually just using one parameter in the declaration of
16828 // the next.
16829 if (isa<ParmVarDecl>(var) &&
16830 isa<TranslationUnitDecl>(VarDC))
16831 return;
16832
16833 // For C code, don't diagnose about capture if we're not actually in code
16834 // right now; it's impossible to write a non-constant expression outside of
16835 // function context, so we'll get other (more useful) diagnostics later.
16836 //
16837 // For C++, things get a bit more nasty... it would be nice to suppress this
16838 // diagnostic for certain cases like using a local variable in an array bound
16839 // for a member of a local class, but the correct predicate is not obvious.
16840 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16841 return;
16842
16843 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16844 unsigned ContextKind = 3; // unknown
16845 if (isa<CXXMethodDecl>(VarDC) &&
16846 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16847 ContextKind = 2;
16848 } else if (isa<FunctionDecl>(VarDC)) {
16849 ContextKind = 0;
16850 } else if (isa<BlockDecl>(VarDC)) {
16851 ContextKind = 1;
16852 }
16853
16854 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16855 << var << ValueKind << ContextKind << VarDC;
16856 S.Diag(var->getLocation(), diag::note_entity_declared_at)
16857 << var;
16858
16859 // FIXME: Add additional diagnostic info about class etc. which prevents
16860 // capture.
16861}
16862
16863
16864static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16865 bool &SubCapturesAreNested,
16866 QualType &CaptureType,
16867 QualType &DeclRefType) {
16868 // Check whether we've already captured it.
16869 if (CSI->CaptureMap.count(Var)) {
16870 // If we found a capture, any subcaptures are nested.
16871 SubCapturesAreNested = true;
16872
16873 // Retrieve the capture type for this variable.
16874 CaptureType = CSI->getCapture(Var).getCaptureType();
16875
16876 // Compute the type of an expression that refers to this variable.
16877 DeclRefType = CaptureType.getNonReferenceType();
16878
16879 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16880 // are mutable in the sense that user can change their value - they are
16881 // private instances of the captured declarations.
16882 const Capture &Cap = CSI->getCapture(Var);
16883 if (Cap.isCopyCapture() &&
16884 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16885 !(isa<CapturedRegionScopeInfo>(CSI) &&
16886 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16887 DeclRefType.addConst();
16888 return true;
16889 }
16890 return false;
16891}
16892
16893// Only block literals, captured statements, and lambda expressions can
16894// capture; other scopes don't work.
16895static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16896 SourceLocation Loc,
16897 const bool Diagnose, Sema &S) {
16898 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16899 return getLambdaAwareParentOfDeclContext(DC);
16900 else if (Var->hasLocalStorage()) {
16901 if (Diagnose)
16902 diagnoseUncapturableValueReference(S, Loc, Var, DC);
16903 }
16904 return nullptr;
16905}
16906
16907// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16908// certain types of variables (unnamed, variably modified types etc.)
16909// so check for eligibility.
16910static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16911 SourceLocation Loc,
16912 const bool Diagnose, Sema &S) {
16913
16914 bool IsBlock = isa<BlockScopeInfo>(CSI);
16915 bool IsLambda = isa<LambdaScopeInfo>(CSI);
16916
16917 // Lambdas are not allowed to capture unnamed variables
16918 // (e.g. anonymous unions).
16919 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16920 // assuming that's the intent.
16921 if (IsLambda && !Var->getDeclName()) {
16922 if (Diagnose) {
16923 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16924 S.Diag(Var->getLocation(), diag::note_declared_at);
16925 }
16926 return false;
16927 }
16928
16929 // Prohibit variably-modified types in blocks; they're difficult to deal with.
16930 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16931 if (Diagnose) {
16932 S.Diag(Loc, diag::err_ref_vm_type);
16933 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16934 }
16935 return false;
16936 }
16937 // Prohibit structs with flexible array members too.
16938 // We cannot capture what is in the tail end of the struct.
16939 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16940 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16941 if (Diagnose) {
16942 if (IsBlock)
16943 S.Diag(Loc, diag::err_ref_flexarray_type);
16944 else
16945 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
16946 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16947 }
16948 return false;
16949 }
16950 }
16951 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16952 // Lambdas and captured statements are not allowed to capture __block
16953 // variables; they don't support the expected semantics.
16954 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16955 if (Diagnose) {
16956 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
16957 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16958 }
16959 return false;
16960 }
16961 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16962 if (S.getLangOpts().OpenCL && IsBlock &&
16963 Var->getType()->isBlockPointerType()) {
16964 if (Diagnose)
16965 S.Diag(Loc, diag::err_opencl_block_ref_block);
16966 return false;
16967 }
16968
16969 return true;
16970}
16971
16972// Returns true if the capture by block was successful.
16973static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16974 SourceLocation Loc,
16975 const bool BuildAndDiagnose,
16976 QualType &CaptureType,
16977 QualType &DeclRefType,
16978 const bool Nested,
16979 Sema &S, bool Invalid) {
16980 bool ByRef = false;
16981
16982 // Blocks are not allowed to capture arrays, excepting OpenCL.
16983 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16984 // (decayed to pointers).
16985 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16986 if (BuildAndDiagnose) {
16987 S.Diag(Loc, diag::err_ref_array_type);
16988 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
16989 Invalid = true;
16990 } else {
16991 return false;
16992 }
16993 }
16994
16995 // Forbid the block-capture of autoreleasing variables.
16996 if (!Invalid &&
16997 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16998 if (BuildAndDiagnose) {
16999 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17000 << /*block*/ 0;
17001 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17002 Invalid = true;
17003 } else {
17004 return false;
17005 }
17006 }
17007
17008 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17009 if (const auto *PT = CaptureType->getAs<PointerType>()) {
17010 QualType PointeeTy = PT->getPointeeType();
17011
17012 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17013 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17014 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17015 if (BuildAndDiagnose) {
17016 SourceLocation VarLoc = Var->getLocation();
17017 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17018 S.Diag(VarLoc, diag::note_declare_parameter_strong);
17019 }
17020 }
17021 }
17022
17023 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17024 if (HasBlocksAttr || CaptureType->isReferenceType() ||
17025 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17026 // Block capture by reference does not change the capture or
17027 // declaration reference types.
17028 ByRef = true;
17029 } else {
17030 // Block capture by copy introduces 'const'.
17031 CaptureType = CaptureType.getNonReferenceType().withConst();
17032 DeclRefType = CaptureType;
17033 }
17034
17035 // Actually capture the variable.
17036 if (BuildAndDiagnose)
17037 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17038 CaptureType, Invalid);
17039
17040 return !Invalid;
17041}
17042
17043
17044/// Capture the given variable in the captured region.
17045static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17046 VarDecl *Var,
17047 SourceLocation Loc,
17048 const bool BuildAndDiagnose,
17049 QualType &CaptureType,
17050 QualType &DeclRefType,
17051 const bool RefersToCapturedVariable,
17052 Sema &S, bool Invalid) {
17053 // By default, capture variables by reference.
17054 bool ByRef = true;
17055 // Using an LValue reference type is consistent with Lambdas (see below).
17056 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17057 if (S.isOpenMPCapturedDecl(Var)) {
17058 bool HasConst = DeclRefType.isConstQualified();
17059 DeclRefType = DeclRefType.getUnqualifiedType();
17060 // Don't lose diagnostics about assignments to const.
17061 if (HasConst)
17062 DeclRefType.addConst();
17063 }
17064 // Do not capture firstprivates in tasks.
17065 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17066 OMPC_unknown)
17067 return true;
17068 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17069 RSI->OpenMPCaptureLevel);
17070 }
17071
17072 if (ByRef)
17073 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17074 else
17075 CaptureType = DeclRefType;
17076
17077 // Actually capture the variable.
17078 if (BuildAndDiagnose)
17079 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17080 Loc, SourceLocation(), CaptureType, Invalid);
17081
17082 return !Invalid;
17083}
17084
17085/// Capture the given variable in the lambda.
17086static bool captureInLambda(LambdaScopeInfo *LSI,
17087 VarDecl *Var,
17088 SourceLocation Loc,
17089 const bool BuildAndDiagnose,
17090 QualType &CaptureType,
17091 QualType &DeclRefType,
17092 const bool RefersToCapturedVariable,
17093 const Sema::TryCaptureKind Kind,
17094 SourceLocation EllipsisLoc,
17095 const bool IsTopScope,
17096 Sema &S, bool Invalid) {
17097 // Determine whether we are capturing by reference or by value.
17098 bool ByRef = false;
17099 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17100 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17101 } else {
17102 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17103 }
17104
17105 // Compute the type of the field that will capture this variable.
17106 if (ByRef) {
17107 // C++11 [expr.prim.lambda]p15:
17108 // An entity is captured by reference if it is implicitly or
17109 // explicitly captured but not captured by copy. It is
17110 // unspecified whether additional unnamed non-static data
17111 // members are declared in the closure type for entities
17112 // captured by reference.
17113 //
17114 // FIXME: It is not clear whether we want to build an lvalue reference
17115 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17116 // to do the former, while EDG does the latter. Core issue 1249 will
17117 // clarify, but for now we follow GCC because it's a more permissive and
17118 // easily defensible position.
17119 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17120 } else {
17121 // C++11 [expr.prim.lambda]p14:
17122 // For each entity captured by copy, an unnamed non-static
17123 // data member is declared in the closure type. The
17124 // declaration order of these members is unspecified. The type
17125 // of such a data member is the type of the corresponding
17126 // captured entity if the entity is not a reference to an
17127 // object, or the referenced type otherwise. [Note: If the
17128 // captured entity is a reference to a function, the
17129 // corresponding data member is also a reference to a
17130 // function. - end note ]
17131 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17132 if (!RefType->getPointeeType()->isFunctionType())
17133 CaptureType = RefType->getPointeeType();
17134 }
17135
17136 // Forbid the lambda copy-capture of autoreleasing variables.
17137 if (!Invalid &&
17138 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17139 if (BuildAndDiagnose) {
17140 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17141 S.Diag(Var->getLocation(), diag::note_previous_decl)
17142 << Var->getDeclName();
17143 Invalid = true;
17144 } else {
17145 return false;
17146 }
17147 }
17148
17149 // Make sure that by-copy captures are of a complete and non-abstract type.
17150 if (!Invalid && BuildAndDiagnose) {
17151 if (!CaptureType->isDependentType() &&
17152 S.RequireCompleteSizedType(
17153 Loc, CaptureType,
17154 diag::err_capture_of_incomplete_or_sizeless_type,
17155 Var->getDeclName()))
17156 Invalid = true;
17157 else if (S.RequireNonAbstractType(Loc, CaptureType,
17158 diag::err_capture_of_abstract_type))
17159 Invalid = true;
17160 }
17161 }
17162
17163 // Compute the type of a reference to this captured variable.
17164 if (ByRef)
17165 DeclRefType = CaptureType.getNonReferenceType();
17166 else {
17167 // C++ [expr.prim.lambda]p5:
17168 // The closure type for a lambda-expression has a public inline
17169 // function call operator [...]. This function call operator is
17170 // declared const (9.3.1) if and only if the lambda-expression's
17171 // parameter-declaration-clause is not followed by mutable.
17172 DeclRefType = CaptureType.getNonReferenceType();
17173 if (!LSI->Mutable && !CaptureType->isReferenceType())
17174 DeclRefType.addConst();
17175 }
17176
17177 // Add the capture.
17178 if (BuildAndDiagnose)
17179 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17180 Loc, EllipsisLoc, CaptureType, Invalid);
17181
17182 return !Invalid;
17183}
17184
17185bool Sema::tryCaptureVariable(
17186 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17187 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17188 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17189 // An init-capture is notionally from the context surrounding its
17190 // declaration, but its parent DC is the lambda class.
17191 DeclContext *VarDC = Var->getDeclContext();
17192 if (Var->isInitCapture())
17193 VarDC = VarDC->getParent();
17194
17195 DeclContext *DC = CurContext;
17196 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17197 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17198 // We need to sync up the Declaration Context with the
17199 // FunctionScopeIndexToStopAt
17200 if (FunctionScopeIndexToStopAt) {
17201 unsigned FSIndex = FunctionScopes.size() - 1;
17202 while (FSIndex != MaxFunctionScopesIndex) {
17203 DC = getLambdaAwareParentOfDeclContext(DC);
17204 --FSIndex;
17205 }
17206 }
17207
17208
17209 // If the variable is declared in the current context, there is no need to
17210 // capture it.
17211 if (VarDC == DC) return true;
17212
17213 // Capture global variables if it is required to use private copy of this
17214 // variable.
17215 bool IsGlobal = !Var->hasLocalStorage();
17216 if (IsGlobal &&
17217 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17218 MaxFunctionScopesIndex)))
17219 return true;
17220 Var = Var->getCanonicalDecl();
17221
17222 // Walk up the stack to determine whether we can capture the variable,
17223 // performing the "simple" checks that don't depend on type. We stop when
17224 // we've either hit the declared scope of the variable or find an existing
17225 // capture of that variable. We start from the innermost capturing-entity
17226 // (the DC) and ensure that all intervening capturing-entities
17227 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17228 // declcontext can either capture the variable or have already captured
17229 // the variable.
17230 CaptureType = Var->getType();
17231 DeclRefType = CaptureType.getNonReferenceType();
17232 bool Nested = false;
17233 bool Explicit = (Kind != TryCapture_Implicit);
17234 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17235 do {
17236 // Only block literals, captured statements, and lambda expressions can
17237 // capture; other scopes don't work.
17238 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17239 ExprLoc,
17240 BuildAndDiagnose,
17241 *this);
17242 // We need to check for the parent *first* because, if we *have*
17243 // private-captured a global variable, we need to recursively capture it in
17244 // intermediate blocks, lambdas, etc.
17245 if (!ParentDC) {
17246 if (IsGlobal) {
17247 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17248 break;
17249 }
17250 return true;
17251 }
17252
17253 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
17254 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17255
17256
17257 // Check whether we've already captured it.
17258 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17259 DeclRefType)) {
17260 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17261 break;
17262 }
17263 // If we are instantiating a generic lambda call operator body,
17264 // we do not want to capture new variables. What was captured
17265 // during either a lambdas transformation or initial parsing
17266 // should be used.
17267 if (isGenericLambdaCallOperatorSpecialization(DC)) {
17268 if (BuildAndDiagnose) {
17269 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17270 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17271 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17272 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17273 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17274 } else
17275 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17276 }
17277 return true;
17278 }
17279
17280 // Try to capture variable-length arrays types.
17281 if (Var->getType()->isVariablyModifiedType()) {
17282 // We're going to walk down into the type and look for VLA
17283 // expressions.
17284 QualType QTy = Var->getType();
17285 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17286 QTy = PVD->getOriginalType();
17287 captureVariablyModifiedType(Context, QTy, CSI);
17288 }
17289
17290 if (getLangOpts().OpenMP) {
17291 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17292 // OpenMP private variables should not be captured in outer scope, so
17293 // just break here. Similarly, global variables that are captured in a
17294 // target region should not be captured outside the scope of the region.
17295 if (RSI->CapRegionKind == CR_OpenMP) {
17296 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17297 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17298 // If the variable is private (i.e. not captured) and has variably
17299 // modified type, we still need to capture the type for correct
17300 // codegen in all regions, associated with the construct. Currently,
17301 // it is captured in the innermost captured region only.
17302 if (IsOpenMPPrivateDecl != OMPC_unknown &&
17303 Var->getType()->isVariablyModifiedType()) {
17304 QualType QTy = Var->getType();
17305 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17306 QTy = PVD->getOriginalType();
17307 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17308 I < E; ++I) {
17309 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17310 FunctionScopes[FunctionScopesIndex - I]);
17311 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? static_cast<void> (0) : __assert_fail
("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17313, __PRETTY_FUNCTION__))
17312 "Wrong number of captured regions associated with the "((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? static_cast<void> (0) : __assert_fail
("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17313, __PRETTY_FUNCTION__))
17313 "OpenMP construct.")((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? static_cast<void> (0) : __assert_fail
("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17313, __PRETTY_FUNCTION__))
;
17314 captureVariablyModifiedType(Context, QTy, OuterRSI);
17315 }
17316 }
17317 bool IsTargetCap =
17318 IsOpenMPPrivateDecl != OMPC_private &&
17319 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17320 RSI->OpenMPCaptureLevel);
17321 // Do not capture global if it is not privatized in outer regions.
17322 bool IsGlobalCap =
17323 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17324 RSI->OpenMPCaptureLevel);
17325
17326 // When we detect target captures we are looking from inside the
17327 // target region, therefore we need to propagate the capture from the
17328 // enclosing region. Therefore, the capture is not initially nested.
17329 if (IsTargetCap)
17330 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17331
17332 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17333 (IsGlobal && !IsGlobalCap)) {
17334 Nested = !IsTargetCap;
17335 DeclRefType = DeclRefType.getUnqualifiedType();
17336 CaptureType = Context.getLValueReferenceType(DeclRefType);
17337 break;
17338 }
17339 }
17340 }
17341 }
17342 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17343 // No capture-default, and this is not an explicit capture
17344 // so cannot capture this variable.
17345 if (BuildAndDiagnose) {
17346 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17347 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17348 if (cast<LambdaScopeInfo>(CSI)->Lambda)
17349 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17350 diag::note_lambda_decl);
17351 // FIXME: If we error out because an outer lambda can not implicitly
17352 // capture a variable that an inner lambda explicitly captures, we
17353 // should have the inner lambda do the explicit capture - because
17354 // it makes for cleaner diagnostics later. This would purely be done
17355 // so that the diagnostic does not misleadingly claim that a variable
17356 // can not be captured by a lambda implicitly even though it is captured
17357 // explicitly. Suggestion:
17358 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17359 // at the function head
17360 // - cache the StartingDeclContext - this must be a lambda
17361 // - captureInLambda in the innermost lambda the variable.
17362 }
17363 return true;
17364 }
17365
17366 FunctionScopesIndex--;
17367 DC = ParentDC;
17368 Explicit = false;
17369 } while (!VarDC->Equals(DC));
17370
17371 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17372 // computing the type of the capture at each step, checking type-specific
17373 // requirements, and adding captures if requested.
17374 // If the variable had already been captured previously, we start capturing
17375 // at the lambda nested within that one.
17376 bool Invalid = false;
17377 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17378 ++I) {
17379 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17380
17381 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17382 // certain types of variables (unnamed, variably modified types etc.)
17383 // so check for eligibility.
17384 if (!Invalid)
17385 Invalid =
17386 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17387
17388 // After encountering an error, if we're actually supposed to capture, keep
17389 // capturing in nested contexts to suppress any follow-on diagnostics.
17390 if (Invalid && !BuildAndDiagnose)
17391 return true;
17392
17393 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17394 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17395 DeclRefType, Nested, *this, Invalid);
17396 Nested = true;
17397 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17398 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17399 CaptureType, DeclRefType, Nested,
17400 *this, Invalid);
17401 Nested = true;
17402 } else {
17403 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17404 Invalid =
17405 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17406 DeclRefType, Nested, Kind, EllipsisLoc,
17407 /*IsTopScope*/ I == N - 1, *this, Invalid);
17408 Nested = true;
17409 }
17410
17411 if (Invalid && !BuildAndDiagnose)
17412 return true;
17413 }
17414 return Invalid;
17415}
17416
17417bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17418 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17419 QualType CaptureType;
17420 QualType DeclRefType;
17421 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17422 /*BuildAndDiagnose=*/true, CaptureType,
17423 DeclRefType, nullptr);
17424}
17425
17426bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17427 QualType CaptureType;
17428 QualType DeclRefType;
17429 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17430 /*BuildAndDiagnose=*/false, CaptureType,
17431 DeclRefType, nullptr);
17432}
17433
17434QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17435 QualType CaptureType;
17436 QualType DeclRefType;
17437
17438 // Determine whether we can capture this variable.
17439 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17440 /*BuildAndDiagnose=*/false, CaptureType,
17441 DeclRefType, nullptr))
17442 return QualType();
17443
17444 return DeclRefType;
17445}
17446
17447namespace {
17448// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17449// The produced TemplateArgumentListInfo* points to data stored within this
17450// object, so should only be used in contexts where the pointer will not be
17451// used after the CopiedTemplateArgs object is destroyed.
17452class CopiedTemplateArgs {
17453 bool HasArgs;
17454 TemplateArgumentListInfo TemplateArgStorage;
17455public:
17456 template<typename RefExpr>
17457 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17458 if (HasArgs)
17459 E->copyTemplateArgumentsInto(TemplateArgStorage);
17460 }
17461 operator TemplateArgumentListInfo*()
17462#ifdef __has_cpp_attribute
17463#if0 __has_cpp_attribute(clang::lifetimebound)1
17464 [[clang::lifetimebound]]
17465#endif
17466#endif
17467 {
17468 return HasArgs ? &TemplateArgStorage : nullptr;
17469 }
17470};
17471}
17472
17473/// Walk the set of potential results of an expression and mark them all as
17474/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17475///
17476/// \return A new expression if we found any potential results, ExprEmpty() if
17477/// not, and ExprError() if we diagnosed an error.
17478static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17479 NonOdrUseReason NOUR) {
17480 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17481 // an object that satisfies the requirements for appearing in a
17482 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17483 // is immediately applied." This function handles the lvalue-to-rvalue
17484 // conversion part.
17485 //
17486 // If we encounter a node that claims to be an odr-use but shouldn't be, we
17487 // transform it into the relevant kind of non-odr-use node and rebuild the
17488 // tree of nodes leading to it.
17489 //
17490 // This is a mini-TreeTransform that only transforms a restricted subset of
17491 // nodes (and only certain operands of them).
17492
17493 // Rebuild a subexpression.
17494 auto Rebuild = [&](Expr *Sub) {
17495 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17496 };
17497
17498 // Check whether a potential result satisfies the requirements of NOUR.
17499 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17500 // Any entity other than a VarDecl is always odr-used whenever it's named
17501 // in a potentially-evaluated expression.
17502 auto *VD = dyn_cast<VarDecl>(D);
17503 if (!VD)
17504 return true;
17505
17506 // C++2a [basic.def.odr]p4:
17507 // A variable x whose name appears as a potentially-evalauted expression
17508 // e is odr-used by e unless
17509 // -- x is a reference that is usable in constant expressions, or
17510 // -- x is a variable of non-reference type that is usable in constant
17511 // expressions and has no mutable subobjects, and e is an element of
17512 // the set of potential results of an expression of
17513 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
17514 // conversion is applied, or
17515 // -- x is a variable of non-reference type, and e is an element of the
17516 // set of potential results of a discarded-value expression to which
17517 // the lvalue-to-rvalue conversion is not applied
17518 //
17519 // We check the first bullet and the "potentially-evaluated" condition in
17520 // BuildDeclRefExpr. We check the type requirements in the second bullet
17521 // in CheckLValueToRValueConversionOperand below.
17522 switch (NOUR) {
17523 case NOUR_None:
17524 case NOUR_Unevaluated:
17525 llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17525)
;
17526
17527 case NOUR_Constant:
17528 // Constant references were handled when they were built.
17529 if (VD->getType()->isReferenceType())
17530 return true;
17531 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17532 if (RD->hasMutableFields())
17533 return true;
17534 if (!VD->isUsableInConstantExpressions(S.Context))
17535 return true;
17536 break;
17537
17538 case NOUR_Discarded:
17539 if (VD->getType()->isReferenceType())
17540 return true;
17541 break;
17542 }
17543 return false;
17544 };
17545
17546 // Mark that this expression does not constitute an odr-use.
17547 auto MarkNotOdrUsed = [&] {
17548 S.MaybeODRUseExprs.remove(E);
17549 if (LambdaScopeInfo *LSI = S.getCurLambda())
17550 LSI->markVariableExprAsNonODRUsed(E);
17551 };
17552
17553 // C++2a [basic.def.odr]p2:
17554 // The set of potential results of an expression e is defined as follows:
17555 switch (E->getStmtClass()) {
17556 // -- If e is an id-expression, ...
17557 case Expr::DeclRefExprClass: {
17558 auto *DRE = cast<DeclRefExpr>(E);
17559 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17560 break;
17561
17562 // Rebuild as a non-odr-use DeclRefExpr.
17563 MarkNotOdrUsed();
17564 return DeclRefExpr::Create(
17565 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17566 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17567 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17568 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17569 }
17570
17571 case Expr::FunctionParmPackExprClass: {
17572 auto *FPPE = cast<FunctionParmPackExpr>(E);
17573 // If any of the declarations in the pack is odr-used, then the expression
17574 // as a whole constitutes an odr-use.
17575 for (VarDecl *D : *FPPE)
17576 if (IsPotentialResultOdrUsed(D))
17577 return ExprEmpty();
17578
17579 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17580 // nothing cares about whether we marked this as an odr-use, but it might
17581 // be useful for non-compiler tools.
17582 MarkNotOdrUsed();
17583 break;
17584 }
17585
17586 // -- If e is a subscripting operation with an array operand...
17587 case Expr::ArraySubscriptExprClass: {
17588 auto *ASE = cast<ArraySubscriptExpr>(E);
17589 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17590 if (!OldBase->getType()->isArrayType())
17591 break;
17592 ExprResult Base = Rebuild(OldBase);
17593 if (!Base.isUsable())
17594 return Base;
17595 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17596 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17597 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17598 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17599 ASE->getRBracketLoc());
17600 }
17601
17602 case Expr::MemberExprClass: {
17603 auto *ME = cast<MemberExpr>(E);
17604 // -- If e is a class member access expression [...] naming a non-static
17605 // data member...
17606 if (isa<FieldDecl>(ME->getMemberDecl())) {
17607 ExprResult Base = Rebuild(ME->getBase());
17608 if (!Base.isUsable())
17609 return Base;
17610 return MemberExpr::Create(
17611 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17612 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17613 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17614 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17615 ME->getObjectKind(), ME->isNonOdrUse());
17616 }
17617
17618 if (ME->getMemberDecl()->isCXXInstanceMember())
17619 break;
17620
17621 // -- If e is a class member access expression naming a static data member,
17622 // ...
17623 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17624 break;
17625
17626 // Rebuild as a non-odr-use MemberExpr.
17627 MarkNotOdrUsed();
17628 return MemberExpr::Create(
17629 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17630 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17631 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17632 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17633 return ExprEmpty();
17634 }
17635
17636 case Expr::BinaryOperatorClass: {
17637 auto *BO = cast<BinaryOperator>(E);
17638 Expr *LHS = BO->getLHS();
17639 Expr *RHS = BO->getRHS();
17640 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17641 if (BO->getOpcode() == BO_PtrMemD) {
17642 ExprResult Sub = Rebuild(LHS);
17643 if (!Sub.isUsable())
17644 return Sub;
17645 LHS = Sub.get();
17646 // -- If e is a comma expression, ...
17647 } else if (BO->getOpcode() == BO_Comma) {
17648 ExprResult Sub = Rebuild(RHS);
17649 if (!Sub.isUsable())
17650 return Sub;
17651 RHS = Sub.get();
17652 } else {
17653 break;
17654 }
17655 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17656 LHS, RHS);
17657 }
17658
17659 // -- If e has the form (e1)...
17660 case Expr::ParenExprClass: {
17661 auto *PE = cast<ParenExpr>(E);
17662 ExprResult Sub = Rebuild(PE->getSubExpr());
17663 if (!Sub.isUsable())
17664 return Sub;
17665 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17666 }
17667
17668 // -- If e is a glvalue conditional expression, ...
17669 // We don't apply this to a binary conditional operator. FIXME: Should we?
17670 case Expr::ConditionalOperatorClass: {
17671 auto *CO = cast<ConditionalOperator>(E);
17672 ExprResult LHS = Rebuild(CO->getLHS());
17673 if (LHS.isInvalid())
17674 return ExprError();
17675 ExprResult RHS = Rebuild(CO->getRHS());
17676 if (RHS.isInvalid())
17677 return ExprError();
17678 if (!LHS.isUsable() && !RHS.isUsable())
17679 return ExprEmpty();
17680 if (!LHS.isUsable())
17681 LHS = CO->getLHS();
17682 if (!RHS.isUsable())
17683 RHS = CO->getRHS();
17684 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17685 CO->getCond(), LHS.get(), RHS.get());
17686 }
17687
17688 // [Clang extension]
17689 // -- If e has the form __extension__ e1...
17690 case Expr::UnaryOperatorClass: {
17691 auto *UO = cast<UnaryOperator>(E);
17692 if (UO->getOpcode() != UO_Extension)
17693 break;
17694 ExprResult Sub = Rebuild(UO->getSubExpr());
17695 if (!Sub.isUsable())
17696 return Sub;
17697 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17698 Sub.get());
17699 }
17700
17701 // [Clang extension]
17702 // -- If e has the form _Generic(...), the set of potential results is the
17703 // union of the sets of potential results of the associated expressions.
17704 case Expr::GenericSelectionExprClass: {
17705 auto *GSE = cast<GenericSelectionExpr>(E);
17706
17707 SmallVector<Expr *, 4> AssocExprs;
17708 bool AnyChanged = false;
17709 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17710 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17711 if (AssocExpr.isInvalid())
17712 return ExprError();
17713 if (AssocExpr.isUsable()) {
17714 AssocExprs.push_back(AssocExpr.get());
17715 AnyChanged = true;
17716 } else {
17717 AssocExprs.push_back(OrigAssocExpr);
17718 }
17719 }
17720
17721 return AnyChanged ? S.CreateGenericSelectionExpr(
17722 GSE->getGenericLoc(), GSE->getDefaultLoc(),
17723 GSE->getRParenLoc(), GSE->getControllingExpr(),
17724 GSE->getAssocTypeSourceInfos(), AssocExprs)
17725 : ExprEmpty();
17726 }
17727
17728 // [Clang extension]
17729 // -- If e has the form __builtin_choose_expr(...), the set of potential
17730 // results is the union of the sets of potential results of the
17731 // second and third subexpressions.
17732 case Expr::ChooseExprClass: {
17733 auto *CE = cast<ChooseExpr>(E);
17734
17735 ExprResult LHS = Rebuild(CE->getLHS());
17736 if (LHS.isInvalid())
17737 return ExprError();
17738
17739 ExprResult RHS = Rebuild(CE->getLHS());
17740 if (RHS.isInvalid())
17741 return ExprError();
17742
17743 if (!LHS.get() && !RHS.get())
17744 return ExprEmpty();
17745 if (!LHS.isUsable())
17746 LHS = CE->getLHS();
17747 if (!RHS.isUsable())
17748 RHS = CE->getRHS();
17749
17750 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17751 RHS.get(), CE->getRParenLoc());
17752 }
17753
17754 // Step through non-syntactic nodes.
17755 case Expr::ConstantExprClass: {
17756 auto *CE = cast<ConstantExpr>(E);
17757 ExprResult Sub = Rebuild(CE->getSubExpr());
17758 if (!Sub.isUsable())
17759 return Sub;
17760 return ConstantExpr::Create(S.Context, Sub.get());
17761 }
17762
17763 // We could mostly rely on the recursive rebuilding to rebuild implicit
17764 // casts, but not at the top level, so rebuild them here.
17765 case Expr::ImplicitCastExprClass: {
17766 auto *ICE = cast<ImplicitCastExpr>(E);
17767 // Only step through the narrow set of cast kinds we expect to encounter.
17768 // Anything else suggests we've left the region in which potential results
17769 // can be found.
17770 switch (ICE->getCastKind()) {
17771 case CK_NoOp:
17772 case CK_DerivedToBase:
17773 case CK_UncheckedDerivedToBase: {
17774 ExprResult Sub = Rebuild(ICE->getSubExpr());
17775 if (!Sub.isUsable())
17776 return Sub;
17777 CXXCastPath Path(ICE->path());
17778 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17779 ICE->getValueKind(), &Path);
17780 }
17781
17782 default:
17783 break;
17784 }
17785 break;
17786 }
17787
17788 default:
17789 break;
17790 }
17791
17792 // Can't traverse through this node. Nothing to do.
17793 return ExprEmpty();
17794}
17795
17796ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17797 // Check whether the operand is or contains an object of non-trivial C union
17798 // type.
17799 if (E->getType().isVolatileQualified() &&
17800 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17801 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17802 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17803 Sema::NTCUC_LValueToRValueVolatile,
17804 NTCUK_Destruct|NTCUK_Copy);
17805
17806 // C++2a [basic.def.odr]p4:
17807 // [...] an expression of non-volatile-qualified non-class type to which
17808 // the lvalue-to-rvalue conversion is applied [...]
17809 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17810 return E;
17811
17812 ExprResult Result =
17813 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17814 if (Result.isInvalid())
17815 return ExprError();
17816 return Result.get() ? Result : E;
17817}
17818
17819ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17820 Res = CorrectDelayedTyposInExpr(Res);
17821
17822 if (!Res.isUsable())
17823 return Res;
17824
17825 // If a constant-expression is a reference to a variable where we delay
17826 // deciding whether it is an odr-use, just assume we will apply the
17827 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
17828 // (a non-type template argument), we have special handling anyway.
17829 return CheckLValueToRValueConversionOperand(Res.get());
17830}
17831
17832void Sema::CleanupVarDeclMarking() {
17833 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17834 // call.
17835 MaybeODRUseExprSet LocalMaybeODRUseExprs;
17836 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17837
17838 for (Expr *E : LocalMaybeODRUseExprs) {
17839 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17840 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17841 DRE->getLocation(), *this);
17842 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17843 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17844 *this);
17845 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17846 for (VarDecl *VD : *FP)
17847 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17848 } else {
17849 llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17849)
;
17850 }
17851 }
17852
17853 assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17854, __PRETTY_FUNCTION__))
17854 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17854, __PRETTY_FUNCTION__))
;
17855}
17856
17857static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17858 VarDecl *Var, Expr *E) {
17859 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E
) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17861, __PRETTY_FUNCTION__))
17860 isa<FunctionParmPackExpr>(E)) &&(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E
) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17861, __PRETTY_FUNCTION__))
17861 "Invalid Expr argument to DoMarkVarDeclReferenced")(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E
) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17861, __PRETTY_FUNCTION__))
;
17862 Var->setReferenced();
17863
17864 if (Var->isInvalidDecl())
17865 return;
17866
17867 // Record a CUDA/HIP static device/constant variable if it is referenced
17868 // by host code. This is done conservatively, when the variable is referenced
17869 // in any of the following contexts:
17870 // - a non-function context
17871 // - a host function
17872 // - a host device function
17873 // This also requires the reference of the static device/constant variable by
17874 // host code to be visible in the device compilation for the compiler to be
17875 // able to externalize the static device/constant variable.
17876 if ((Var->hasAttr<CUDADeviceAttr>() || Var->hasAttr<CUDAConstantAttr>()) &&
17877 Var->isFileVarDecl() && Var->getStorageClass() == SC_Static) {
17878 auto *CurContext = SemaRef.CurContext;
17879 if (!CurContext || !isa<FunctionDecl>(CurContext) ||
17880 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
17881 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
17882 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
17883 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
17884 }
17885
17886 auto *MSI = Var->getMemberSpecializationInfo();
17887 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17888 : Var->getTemplateSpecializationKind();
17889
17890 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17891 bool UsableInConstantExpr =
17892 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17893
17894 // C++20 [expr.const]p12:
17895 // A variable [...] is needed for constant evaluation if it is [...] a
17896 // variable whose name appears as a potentially constant evaluated
17897 // expression that is either a contexpr variable or is of non-volatile
17898 // const-qualified integral type or of reference type
17899 bool NeededForConstantEvaluation =
17900 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17901
17902 bool NeedDefinition =
17903 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17904
17905 VarTemplateSpecializationDecl *VarSpec =
17906 dyn_cast<VarTemplateSpecializationDecl>(Var);
17907 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&((!isa<VarTemplatePartialSpecializationDecl>(Var) &&
"Can't instantiate a partial template specialization.") ? static_cast
<void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17908, __PRETTY_FUNCTION__))
17908 "Can't instantiate a partial template specialization.")((!isa<VarTemplatePartialSpecializationDecl>(Var) &&
"Can't instantiate a partial template specialization.") ? static_cast
<void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17908, __PRETTY_FUNCTION__))
;
17909
17910 // If this might be a member specialization of a static data member, check
17911 // the specialization is visible. We already did the checks for variable
17912 // template specializations when we created them.
17913 if (NeedDefinition && TSK != TSK_Undeclared &&
17914 !isa<VarTemplateSpecializationDecl>(Var))
17915 SemaRef.checkSpecializationVisibility(Loc, Var);
17916
17917 // Perform implicit instantiation of static data members, static data member
17918 // templates of class templates, and variable template specializations. Delay
17919 // instantiations of variable templates, except for those that could be used
17920 // in a constant expression.
17921 if (NeedDefinition && isTemplateInstantiation(TSK)) {
17922 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17923 // instantiation declaration if a variable is usable in a constant
17924 // expression (among other cases).
17925 bool TryInstantiating =
17926 TSK == TSK_ImplicitInstantiation ||
17927 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17928
17929 if (TryInstantiating) {
17930 SourceLocation PointOfInstantiation =
17931 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17932 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17933 if (FirstInstantiation) {
17934 PointOfInstantiation = Loc;
17935 if (MSI)
17936 MSI->setPointOfInstantiation(PointOfInstantiation);
17937 else
17938 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17939 }
17940
17941 bool InstantiationDependent = false;
17942 bool IsNonDependent =
17943 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17944 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17945 : true;
17946
17947 // Do not instantiate specializations that are still type-dependent.
17948 if (IsNonDependent) {
17949 if (UsableInConstantExpr) {
17950 // Do not defer instantiations of variables that could be used in a
17951 // constant expression.
17952 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17953 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17954 });
17955 } else if (FirstInstantiation ||
17956 isa<VarTemplateSpecializationDecl>(Var)) {
17957 // FIXME: For a specialization of a variable template, we don't
17958 // distinguish between "declaration and type implicitly instantiated"
17959 // and "implicit instantiation of definition requested", so we have
17960 // no direct way to avoid enqueueing the pending instantiation
17961 // multiple times.
17962 SemaRef.PendingInstantiations
17963 .push_back(std::make_pair(Var, PointOfInstantiation));
17964 }
17965 }
17966 }
17967 }
17968
17969 // C++2a [basic.def.odr]p4:
17970 // A variable x whose name appears as a potentially-evaluated expression e
17971 // is odr-used by e unless
17972 // -- x is a reference that is usable in constant expressions
17973 // -- x is a variable of non-reference type that is usable in constant
17974 // expressions and has no mutable subobjects [FIXME], and e is an
17975 // element of the set of potential results of an expression of
17976 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
17977 // conversion is applied
17978 // -- x is a variable of non-reference type, and e is an element of the set
17979 // of potential results of a discarded-value expression to which the
17980 // lvalue-to-rvalue conversion is not applied [FIXME]
17981 //
17982 // We check the first part of the second bullet here, and
17983 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17984 // FIXME: To get the third bullet right, we need to delay this even for
17985 // variables that are not usable in constant expressions.
17986
17987 // If we already know this isn't an odr-use, there's nothing more to do.
17988 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17989 if (DRE->isNonOdrUse())
17990 return;
17991 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17992 if (ME->isNonOdrUse())
17993 return;
17994
17995 switch (OdrUse) {
17996 case OdrUseContext::None:
17997 assert((!E || isa<FunctionParmPackExpr>(E)) &&(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17998, __PRETTY_FUNCTION__))
17998 "missing non-odr-use marking for unevaluated decl ref")(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 17998, __PRETTY_FUNCTION__))
;
17999 break;
18000
18001 case OdrUseContext::FormallyOdrUsed:
18002 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18003 // behavior.
18004 break;
18005
18006 case OdrUseContext::Used:
18007 // If we might later find that this expression isn't actually an odr-use,
18008 // delay the marking.
18009 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18010 SemaRef.MaybeODRUseExprs.insert(E);
18011 else
18012 MarkVarDeclODRUsed(Var, Loc, SemaRef);
18013 break;
18014
18015 case OdrUseContext::Dependent:
18016 // If this is a dependent context, we don't need to mark variables as
18017 // odr-used, but we may still need to track them for lambda capture.
18018 // FIXME: Do we also need to do this inside dependent typeid expressions
18019 // (which are modeled as unevaluated at this point)?
18020 const bool RefersToEnclosingScope =
18021 (SemaRef.CurContext != Var->getDeclContext() &&
18022 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18023 if (RefersToEnclosingScope) {
18024 LambdaScopeInfo *const LSI =
18025 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18026 if (LSI && (!LSI->CallOperator ||
18027 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18028 // If a variable could potentially be odr-used, defer marking it so
18029 // until we finish analyzing the full expression for any
18030 // lvalue-to-rvalue
18031 // or discarded value conversions that would obviate odr-use.
18032 // Add it to the list of potential captures that will be analyzed
18033 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18034 // unless the variable is a reference that was initialized by a constant
18035 // expression (this will never need to be captured or odr-used).
18036 //
18037 // FIXME: We can simplify this a lot after implementing P0588R1.
18038 assert(E && "Capture variable should be used in an expression.")((E && "Capture variable should be used in an expression."
) ? static_cast<void> (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18038, __PRETTY_FUNCTION__))
;
18039 if (!Var->getType()->isReferenceType() ||
18040 !Var->isUsableInConstantExpressions(SemaRef.Context))
18041 LSI->addPotentialCapture(E->IgnoreParens());
18042 }
18043 }
18044 break;
18045 }
18046}
18047
18048/// Mark a variable referenced, and check whether it is odr-used
18049/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
18050/// used directly for normal expressions referring to VarDecl.
18051void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18052 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18053}
18054
18055static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18056 Decl *D, Expr *E, bool MightBeOdrUse) {
18057 if (SemaRef.isInOpenMPDeclareTargetContext())
18058 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18059
18060 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18061 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18062 return;
18063 }
18064
18065 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18066
18067 // If this is a call to a method via a cast, also mark the method in the
18068 // derived class used in case codegen can devirtualize the call.
18069 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18070 if (!ME)
18071 return;
18072 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18073 if (!MD)
18074 return;
18075 // Only attempt to devirtualize if this is truly a virtual call.
18076 bool IsVirtualCall = MD->isVirtual() &&
18077 ME->performsVirtualDispatch(SemaRef.getLangOpts());
18078 if (!IsVirtualCall)
18079 return;
18080
18081 // If it's possible to devirtualize the call, mark the called function
18082 // referenced.
18083 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18084 ME->getBase(), SemaRef.getLangOpts().AppleKext);
18085 if (DM)
18086 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18087}
18088
18089/// Perform reference-marking and odr-use handling for a DeclRefExpr.
18090void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18091 // TODO: update this with DR# once a defect report is filed.
18092 // C++11 defect. The address of a pure member should not be an ODR use, even
18093 // if it's a qualified reference.
18094 bool OdrUse = true;
18095 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18096 if (Method->isVirtual() &&
18097 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18098 OdrUse = false;
18099
18100 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18101 if (!isConstantEvaluated() && FD->isConsteval() &&
18102 !RebuildingImmediateInvocation)
18103 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18104 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18105}
18106
18107/// Perform reference-marking and odr-use handling for a MemberExpr.
18108void Sema::MarkMemberReferenced(MemberExpr *E) {
18109 // C++11 [basic.def.odr]p2:
18110 // A non-overloaded function whose name appears as a potentially-evaluated
18111 // expression or a member of a set of candidate functions, if selected by
18112 // overload resolution when referred to from a potentially-evaluated
18113 // expression, is odr-used, unless it is a pure virtual function and its
18114 // name is not explicitly qualified.
18115 bool MightBeOdrUse = true;
18116 if (E->performsVirtualDispatch(getLangOpts())) {
18117 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18118 if (Method->isPure())
18119 MightBeOdrUse = false;
18120 }
18121 SourceLocation Loc =
18122 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18123 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18124}
18125
18126/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18127void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18128 for (VarDecl *VD : *E)
18129 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18130}
18131
18132/// Perform marking for a reference to an arbitrary declaration. It
18133/// marks the declaration referenced, and performs odr-use checking for
18134/// functions and variables. This method should not be used when building a
18135/// normal expression which refers to a variable.
18136void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18137 bool MightBeOdrUse) {
18138 if (MightBeOdrUse) {
18139 if (auto *VD = dyn_cast<VarDecl>(D)) {
18140 MarkVariableReferenced(Loc, VD);
18141 return;
18142 }
18143 }
18144 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18145 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18146 return;
18147 }
18148 D->setReferenced();
18149}
18150
18151namespace {
18152 // Mark all of the declarations used by a type as referenced.
18153 // FIXME: Not fully implemented yet! We need to have a better understanding
18154 // of when we're entering a context we should not recurse into.
18155 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18156 // TreeTransforms rebuilding the type in a new context. Rather than
18157 // duplicating the TreeTransform logic, we should consider reusing it here.
18158 // Currently that causes problems when rebuilding LambdaExprs.
18159 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18160 Sema &S;
18161 SourceLocation Loc;
18162
18163 public:
18164 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18165
18166 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18167
18168 bool TraverseTemplateArgument(const TemplateArgument &Arg);
18169 };
18170}
18171
18172bool MarkReferencedDecls::TraverseTemplateArgument(
18173 const TemplateArgument &Arg) {
18174 {
18175 // A non-type template argument is a constant-evaluated context.
18176 EnterExpressionEvaluationContext Evaluated(
18177 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18178 if (Arg.getKind() == TemplateArgument::Declaration) {
18179 if (Decl *D = Arg.getAsDecl())
18180 S.MarkAnyDeclReferenced(Loc, D, true);
18181 } else if (Arg.getKind() == TemplateArgument::Expression) {
18182 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18183 }
18184 }
18185
18186 return Inherited::TraverseTemplateArgument(Arg);
18187}
18188
18189void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18190 MarkReferencedDecls Marker(*this, Loc);
18191 Marker.TraverseType(T);
18192}
18193
18194namespace {
18195/// Helper class that marks all of the declarations referenced by
18196/// potentially-evaluated subexpressions as "referenced".
18197class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18198public:
18199 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18200 bool SkipLocalVariables;
18201
18202 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18203 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18204
18205 void visitUsedDecl(SourceLocation Loc, Decl *D) {
18206 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18207 }
18208
18209 void VisitDeclRefExpr(DeclRefExpr *E) {
18210 // If we were asked not to visit local variables, don't.
18211 if (SkipLocalVariables) {
18212 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18213 if (VD->hasLocalStorage())
18214 return;
18215 }
18216 S.MarkDeclRefReferenced(E);
18217 }
18218
18219 void VisitMemberExpr(MemberExpr *E) {
18220 S.MarkMemberReferenced(E);
18221 Visit(E->getBase());
18222 }
18223};
18224} // namespace
18225
18226/// Mark any declarations that appear within this expression or any
18227/// potentially-evaluated subexpressions as "referenced".
18228///
18229/// \param SkipLocalVariables If true, don't mark local variables as
18230/// 'referenced'.
18231void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18232 bool SkipLocalVariables) {
18233 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18234}
18235
18236/// Emit a diagnostic that describes an effect on the run-time behavior
18237/// of the program being compiled.
18238///
18239/// This routine emits the given diagnostic when the code currently being
18240/// type-checked is "potentially evaluated", meaning that there is a
18241/// possibility that the code will actually be executable. Code in sizeof()
18242/// expressions, code used only during overload resolution, etc., are not
18243/// potentially evaluated. This routine will suppress such diagnostics or,
18244/// in the absolutely nutty case of potentially potentially evaluated
18245/// expressions (C++ typeid), queue the diagnostic to potentially emit it
18246/// later.
18247///
18248/// This routine should be used for all diagnostics that describe the run-time
18249/// behavior of a program, such as passing a non-POD value through an ellipsis.
18250/// Failure to do so will likely result in spurious diagnostics or failures
18251/// during overload resolution or within sizeof/alignof/typeof/typeid.
18252bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18253 const PartialDiagnostic &PD) {
18254 switch (ExprEvalContexts.back().Context) {
18255 case ExpressionEvaluationContext::Unevaluated:
18256 case ExpressionEvaluationContext::UnevaluatedList:
18257 case ExpressionEvaluationContext::UnevaluatedAbstract:
18258 case ExpressionEvaluationContext::DiscardedStatement:
18259 // The argument will never be evaluated, so don't complain.
18260 break;
18261
18262 case ExpressionEvaluationContext::ConstantEvaluated:
18263 // Relevant diagnostics should be produced by constant evaluation.
18264 break;
18265
18266 case ExpressionEvaluationContext::PotentiallyEvaluated:
18267 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18268 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18269 FunctionScopes.back()->PossiblyUnreachableDiags.
18270 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18271 return true;
18272 }
18273
18274 // The initializer of a constexpr variable or of the first declaration of a
18275 // static data member is not syntactically a constant evaluated constant,
18276 // but nonetheless is always required to be a constant expression, so we
18277 // can skip diagnosing.
18278 // FIXME: Using the mangling context here is a hack.
18279 if (auto *VD = dyn_cast_or_null<VarDecl>(
18280 ExprEvalContexts.back().ManglingContextDecl)) {
18281 if (VD->isConstexpr() ||
18282 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18283 break;
18284 // FIXME: For any other kind of variable, we should build a CFG for its
18285 // initializer and check whether the context in question is reachable.
18286 }
18287
18288 Diag(Loc, PD);
18289 return true;
18290 }
18291
18292 return false;
18293}
18294
18295bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18296 const PartialDiagnostic &PD) {
18297 return DiagRuntimeBehavior(
18298 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18299}
18300
18301bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18302 CallExpr *CE, FunctionDecl *FD) {
18303 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18304 return false;
18305
18306 // If we're inside a decltype's expression, don't check for a valid return
18307 // type or construct temporaries until we know whether this is the last call.
18308 if (ExprEvalContexts.back().ExprContext ==
18309 ExpressionEvaluationContextRecord::EK_Decltype) {
18310 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18311 return false;
18312 }
18313
18314 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18315 FunctionDecl *FD;
18316 CallExpr *CE;
18317
18318 public:
18319 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18320 : FD(FD), CE(CE) { }
18321
18322 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18323 if (!FD) {
18324 S.Diag(Loc, diag::err_call_incomplete_return)
18325 << T << CE->getSourceRange();
18326 return;
18327 }
18328
18329 S.Diag(Loc, diag::err_call_function_incomplete_return)
18330 << CE->getSourceRange() << FD << T;
18331 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18332 << FD->getDeclName();
18333 }
18334 } Diagnoser(FD, CE);
18335
18336 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18337 return true;
18338
18339 return false;
18340}
18341
18342// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18343// will prevent this condition from triggering, which is what we want.
18344void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18345 SourceLocation Loc;
18346
18347 unsigned diagnostic = diag::warn_condition_is_assignment;
18348 bool IsOrAssign = false;
18349
18350 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18351 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18352 return;
18353
18354 IsOrAssign = Op->getOpcode() == BO_OrAssign;
18355
18356 // Greylist some idioms by putting them into a warning subcategory.
18357 if (ObjCMessageExpr *ME
18358 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18359 Selector Sel = ME->getSelector();
18360
18361 // self = [<foo> init...]
18362 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18363 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18364
18365 // <foo> = [<bar> nextObject]
18366 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18367 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18368 }
18369
18370 Loc = Op->getOperatorLoc();
18371 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18372 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18373 return;
18374
18375 IsOrAssign = Op->getOperator() == OO_PipeEqual;
18376 Loc = Op->getOperatorLoc();
18377 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18378 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18379 else {
18380 // Not an assignment.
18381 return;
18382 }
18383
18384 Diag(Loc, diagnostic) << E->getSourceRange();
18385
18386 SourceLocation Open = E->getBeginLoc();
18387 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18388 Diag(Loc, diag::note_condition_assign_silence)
18389 << FixItHint::CreateInsertion(Open, "(")
18390 << FixItHint::CreateInsertion(Close, ")");
18391
18392 if (IsOrAssign)
18393 Diag(Loc, diag::note_condition_or_assign_to_comparison)
18394 << FixItHint::CreateReplacement(Loc, "!=");
18395 else
18396 Diag(Loc, diag::note_condition_assign_to_comparison)
18397 << FixItHint::CreateReplacement(Loc, "==");
18398}
18399
18400/// Redundant parentheses over an equality comparison can indicate
18401/// that the user intended an assignment used as condition.
18402void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18403 // Don't warn if the parens came from a macro.
18404 SourceLocation parenLoc = ParenE->getBeginLoc();
18405 if (parenLoc.isInvalid() || parenLoc.isMacroID())
18406 return;
18407 // Don't warn for dependent expressions.
18408 if (ParenE->isTypeDependent())
18409 return;
18410
18411 Expr *E = ParenE->IgnoreParens();
18412
18413 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18414 if (opE->getOpcode() == BO_EQ &&
18415 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18416 == Expr::MLV_Valid) {
18417 SourceLocation Loc = opE->getOperatorLoc();
18418
18419 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18420 SourceRange ParenERange = ParenE->getSourceRange();
18421 Diag(Loc, diag::note_equality_comparison_silence)
18422 << FixItHint::CreateRemoval(ParenERange.getBegin())
18423 << FixItHint::CreateRemoval(ParenERange.getEnd());
18424 Diag(Loc, diag::note_equality_comparison_to_assign)
18425 << FixItHint::CreateReplacement(Loc, "=");
18426 }
18427}
18428
18429ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18430 bool IsConstexpr) {
18431 DiagnoseAssignmentAsCondition(E);
18432 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18433 DiagnoseEqualityWithExtraParens(parenE);
18434
18435 ExprResult result = CheckPlaceholderExpr(E);
18436 if (result.isInvalid()) return ExprError();
18437 E = result.get();
18438
18439 if (!E->isTypeDependent()) {
18440 if (getLangOpts().CPlusPlus)
18441 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18442
18443 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18444 if (ERes.isInvalid())
18445 return ExprError();
18446 E = ERes.get();
18447
18448 QualType T = E->getType();
18449 if (!T->isScalarType()) { // C99 6.8.4.1p1
18450 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18451 << T << E->getSourceRange();
18452 return ExprError();
18453 }
18454 CheckBoolLikeConversion(E, Loc);
18455 }
18456
18457 return E;
18458}
18459
18460Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18461 Expr *SubExpr, ConditionKind CK) {
18462 // Empty conditions are valid in for-statements.
18463 if (!SubExpr)
18464 return ConditionResult();
18465
18466 ExprResult Cond;
18467 switch (CK) {
18468 case ConditionKind::Boolean:
18469 Cond = CheckBooleanCondition(Loc, SubExpr);
18470 break;
18471
18472 case ConditionKind::ConstexprIf:
18473 Cond = CheckBooleanCondition(Loc, SubExpr, true);
18474 break;
18475
18476 case ConditionKind::Switch:
18477 Cond = CheckSwitchCondition(Loc, SubExpr);
18478 break;
18479 }
18480 if (Cond.isInvalid()) {
18481 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18482 {SubExpr});
18483 if (!Cond.get())
18484 return ConditionError();
18485 }
18486 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18487 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18488 if (!FullExpr.get())
18489 return ConditionError();
18490
18491 return ConditionResult(*this, nullptr, FullExpr,
18492 CK == ConditionKind::ConstexprIf);
18493}
18494
18495namespace {
18496 /// A visitor for rebuilding a call to an __unknown_any expression
18497 /// to have an appropriate type.
18498 struct RebuildUnknownAnyFunction
18499 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18500
18501 Sema &S;
18502
18503 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18504
18505 ExprResult VisitStmt(Stmt *S) {
18506 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18506)
;
18507 }
18508
18509 ExprResult VisitExpr(Expr *E) {
18510 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18511 << E->getSourceRange();
18512 return ExprError();
18513 }
18514
18515 /// Rebuild an expression which simply semantically wraps another
18516 /// expression which it shares the type and value kind of.
18517 template <class T> ExprResult rebuildSugarExpr(T *E) {
18518 ExprResult SubResult = Visit(E->getSubExpr());
18519 if (SubResult.isInvalid()) return ExprError();
18520
18521 Expr *SubExpr = SubResult.get();
18522 E->setSubExpr(SubExpr);
18523 E->setType(SubExpr->getType());
18524 E->setValueKind(SubExpr->getValueKind());
18525 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18525, __PRETTY_FUNCTION__))
;
18526 return E;
18527 }
18528
18529 ExprResult VisitParenExpr(ParenExpr *E) {
18530 return rebuildSugarExpr(E);
18531 }
18532
18533 ExprResult VisitUnaryExtension(UnaryOperator *E) {
18534 return rebuildSugarExpr(E);
18535 }
18536
18537 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18538 ExprResult SubResult = Visit(E->getSubExpr());
18539 if (SubResult.isInvalid()) return ExprError();
18540
18541 Expr *SubExpr = SubResult.get();
18542 E->setSubExpr(SubExpr);
18543 E->setType(S.Context.getPointerType(SubExpr->getType()));
18544 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18544, __PRETTY_FUNCTION__))
;
18545 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18545, __PRETTY_FUNCTION__))
;
18546 return E;
18547 }
18548
18549 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18550 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18551
18552 E->setType(VD->getType());
18553
18554 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18554, __PRETTY_FUNCTION__))
;
18555 if (S.getLangOpts().CPlusPlus &&
18556 !(isa<CXXMethodDecl>(VD) &&
18557 cast<CXXMethodDecl>(VD)->isInstance()))
18558 E->setValueKind(VK_LValue);
18559
18560 return E;
18561 }
18562
18563 ExprResult VisitMemberExpr(MemberExpr *E) {
18564 return resolveDecl(E, E->getMemberDecl());
18565 }
18566
18567 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18568 return resolveDecl(E, E->getDecl());
18569 }
18570 };
18571}
18572
18573/// Given a function expression of unknown-any type, try to rebuild it
18574/// to have a function type.
18575static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18576 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18577 if (Result.isInvalid()) return ExprError();
18578 return S.DefaultFunctionArrayConversion(Result.get());
18579}
18580
18581namespace {
18582 /// A visitor for rebuilding an expression of type __unknown_anytype
18583 /// into one which resolves the type directly on the referring
18584 /// expression. Strict preservation of the original source
18585 /// structure is not a goal.
18586 struct RebuildUnknownAnyExpr
18587 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18588
18589 Sema &S;
18590
18591 /// The current destination type.
18592 QualType DestType;
18593
18594 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18595 : S(S), DestType(CastType) {}
18596
18597 ExprResult VisitStmt(Stmt *S) {
18598 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18598)
;
18599 }
18600
18601 ExprResult VisitExpr(Expr *E) {
18602 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18603 << E->getSourceRange();
18604 return ExprError();
18605 }
18606
18607 ExprResult VisitCallExpr(CallExpr *E);
18608 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18609
18610 /// Rebuild an expression which simply semantically wraps another
18611 /// expression which it shares the type and value kind of.
18612 template <class T> ExprResult rebuildSugarExpr(T *E) {
18613 ExprResult SubResult = Visit(E->getSubExpr());
18614 if (SubResult.isInvalid()) return ExprError();
18615 Expr *SubExpr = SubResult.get();
18616 E->setSubExpr(SubExpr);
18617 E->setType(SubExpr->getType());
18618 E->setValueKind(SubExpr->getValueKind());
18619 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18619, __PRETTY_FUNCTION__))
;
18620 return E;
18621 }
18622
18623 ExprResult VisitParenExpr(ParenExpr *E) {
18624 return rebuildSugarExpr(E);
18625 }
18626
18627 ExprResult VisitUnaryExtension(UnaryOperator *E) {
18628 return rebuildSugarExpr(E);
18629 }
18630
18631 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18632 const PointerType *Ptr = DestType->getAs<PointerType>();
18633 if (!Ptr) {
18634 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18635 << E->getSourceRange();
18636 return ExprError();
18637 }
18638
18639 if (isa<CallExpr>(E->getSubExpr())) {
18640 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18641 << E->getSourceRange();
18642 return ExprError();
18643 }
18644
18645 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18645, __PRETTY_FUNCTION__))
;
18646 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18646, __PRETTY_FUNCTION__))
;
18647 E->setType(DestType);
18648
18649 // Build the sub-expression as if it were an object of the pointee type.
18650 DestType = Ptr->getPointeeType();
18651 ExprResult SubResult = Visit(E->getSubExpr());
18652 if (SubResult.isInvalid()) return ExprError();
18653 E->setSubExpr(SubResult.get());
18654 return E;
18655 }
18656
18657 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18658
18659 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18660
18661 ExprResult VisitMemberExpr(MemberExpr *E) {
18662 return resolveDecl(E, E->getMemberDecl());
18663 }
18664
18665 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18666 return resolveDecl(E, E->getDecl());
18667 }
18668 };
18669}
18670
18671/// Rebuilds a call expression which yielded __unknown_anytype.
18672ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18673 Expr *CalleeExpr = E->getCallee();
18674
18675 enum FnKind {
18676 FK_MemberFunction,
18677 FK_FunctionPointer,
18678 FK_BlockPointer
18679 };
18680
18681 FnKind Kind;
18682 QualType CalleeType = CalleeExpr->getType();
18683 if (CalleeType == S.Context.BoundMemberTy) {
18684 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))((isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr
>(E)) ? static_cast<void> (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18684, __PRETTY_FUNCTION__))
;
18685 Kind = FK_MemberFunction;
18686 CalleeType = Expr::findBoundMemberType(CalleeExpr);
18687 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18688 CalleeType = Ptr->getPointeeType();
18689 Kind = FK_FunctionPointer;
18690 } else {
18691 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18692 Kind = FK_BlockPointer;
18693 }
18694 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18695
18696 // Verify that this is a legal result type of a function.
18697 if (DestType->isArrayType() || DestType->isFunctionType()) {
18698 unsigned diagID = diag::err_func_returning_array_function;
18699 if (Kind == FK_BlockPointer)
18700 diagID = diag::err_block_returning_array_function;
18701
18702 S.Diag(E->getExprLoc(), diagID)
18703 << DestType->isFunctionType() << DestType;
18704 return ExprError();
18705 }
18706
18707 // Otherwise, go ahead and set DestType as the call's result.
18708 E->setType(DestType.getNonLValueExprType(S.Context));
18709 E->setValueKind(Expr::getValueKindForType(DestType));
18710 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18710, __PRETTY_FUNCTION__))
;
18711
18712 // Rebuild the function type, replacing the result type with DestType.
18713 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18714 if (Proto) {
18715 // __unknown_anytype(...) is a special case used by the debugger when
18716 // it has no idea what a function's signature is.
18717 //
18718 // We want to build this call essentially under the K&R
18719 // unprototyped rules, but making a FunctionNoProtoType in C++
18720 // would foul up all sorts of assumptions. However, we cannot
18721 // simply pass all arguments as variadic arguments, nor can we
18722 // portably just call the function under a non-variadic type; see
18723 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18724 // However, it turns out that in practice it is generally safe to
18725 // call a function declared as "A foo(B,C,D);" under the prototype
18726 // "A foo(B,C,D,...);". The only known exception is with the
18727 // Windows ABI, where any variadic function is implicitly cdecl
18728 // regardless of its normal CC. Therefore we change the parameter
18729 // types to match the types of the arguments.
18730 //
18731 // This is a hack, but it is far superior to moving the
18732 // corresponding target-specific code from IR-gen to Sema/AST.
18733
18734 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18735 SmallVector<QualType, 8> ArgTypes;
18736 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18737 ArgTypes.reserve(E->getNumArgs());
18738 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18739 Expr *Arg = E->getArg(i);
18740 QualType ArgType = Arg->getType();
18741 if (E->isLValue()) {
18742 ArgType = S.Context.getLValueReferenceType(ArgType);
18743 } else if (E->isXValue()) {
18744 ArgType = S.Context.getRValueReferenceType(ArgType);
18745 }
18746 ArgTypes.push_back(ArgType);
18747 }
18748 ParamTypes = ArgTypes;
18749 }
18750 DestType = S.Context.getFunctionType(DestType, ParamTypes,
18751 Proto->getExtProtoInfo());
18752 } else {
18753 DestType = S.Context.getFunctionNoProtoType(DestType,
18754 FnType->getExtInfo());
18755 }
18756
18757 // Rebuild the appropriate pointer-to-function type.
18758 switch (Kind) {
18759 case FK_MemberFunction:
18760 // Nothing to do.
18761 break;
18762
18763 case FK_FunctionPointer:
18764 DestType = S.Context.getPointerType(DestType);
18765 break;
18766
18767 case FK_BlockPointer:
18768 DestType = S.Context.getBlockPointerType(DestType);
18769 break;
18770 }
18771
18772 // Finally, we can recurse.
18773 ExprResult CalleeResult = Visit(CalleeExpr);
18774 if (!CalleeResult.isUsable()) return ExprError();
18775 E->setCallee(CalleeResult.get());
18776
18777 // Bind a temporary if necessary.
18778 return S.MaybeBindToTemporary(E);
18779}
18780
18781ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18782 // Verify that this is a legal result type of a call.
18783 if (DestType->isArrayType() || DestType->isFunctionType()) {
18784 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18785 << DestType->isFunctionType() << DestType;
18786 return ExprError();
18787 }
18788
18789 // Rewrite the method result type if available.
18790 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18791 assert(Method->getReturnType() == S.Context.UnknownAnyTy)((Method->getReturnType() == S.Context.UnknownAnyTy) ? static_cast
<void> (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18791, __PRETTY_FUNCTION__))
;
18792 Method->setReturnType(DestType);
18793 }
18794
18795 // Change the type of the message.
18796 E->setType(DestType.getNonReferenceType());
18797 E->setValueKind(Expr::getValueKindForType(DestType));
18798
18799 return S.MaybeBindToTemporary(E);
18800}
18801
18802ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18803 // The only case we should ever see here is a function-to-pointer decay.
18804 if (E->getCastKind() == CK_FunctionToPointerDecay) {
18805 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18805, __PRETTY_FUNCTION__))
;
18806 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18806, __PRETTY_FUNCTION__))
;
18807
18808 E->setType(DestType);
18809
18810 // Rebuild the sub-expression as the pointee (function) type.
18811 DestType = DestType->castAs<PointerType>()->getPointeeType();
18812
18813 ExprResult Result = Visit(E->getSubExpr());
18814 if (!Result.isUsable()) return ExprError();
18815
18816 E->setSubExpr(Result.get());
18817 return E;
18818 } else if (E->getCastKind() == CK_LValueToRValue) {
18819 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18819, __PRETTY_FUNCTION__))
;
18820 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18820, __PRETTY_FUNCTION__))
;
18821
18822 assert(isa<BlockPointerType>(E->getType()))((isa<BlockPointerType>(E->getType())) ? static_cast
<void> (0) : __assert_fail ("isa<BlockPointerType>(E->getType())"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18822, __PRETTY_FUNCTION__))
;
18823
18824 E->setType(DestType);
18825
18826 // The sub-expression has to be a lvalue reference, so rebuild it as such.
18827 DestType = S.Context.getLValueReferenceType(DestType);
18828
18829 ExprResult Result = Visit(E->getSubExpr());
18830 if (!Result.isUsable()) return ExprError();
18831
18832 E->setSubExpr(Result.get());
18833 return E;
18834 } else {
18835 llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18835)
;
18836 }
18837}
18838
18839ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18840 ExprValueKind ValueKind = VK_LValue;
18841 QualType Type = DestType;
18842
18843 // We know how to make this work for certain kinds of decls:
18844
18845 // - functions
18846 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18847 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18848 DestType = Ptr->getPointeeType();
18849 ExprResult Result = resolveDecl(E, VD);
18850 if (Result.isInvalid()) return ExprError();
18851 return S.ImpCastExprToType(Result.get(), Type,
18852 CK_FunctionToPointerDecay, VK_RValue);
18853 }
18854
18855 if (!Type->isFunctionType()) {
18856 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18857 << VD << E->getSourceRange();
18858 return ExprError();
18859 }
18860 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18861 // We must match the FunctionDecl's type to the hack introduced in
18862 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18863 // type. See the lengthy commentary in that routine.
18864 QualType FDT = FD->getType();
18865 const FunctionType *FnType = FDT->castAs<FunctionType>();
18866 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18867 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18868 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18869 SourceLocation Loc = FD->getLocation();
18870 FunctionDecl *NewFD = FunctionDecl::Create(
18871 S.Context, FD->getDeclContext(), Loc, Loc,
18872 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18873 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18874 /*ConstexprKind*/ CSK_unspecified);
18875
18876 if (FD->getQualifier())
18877 NewFD->setQualifierInfo(FD->getQualifierLoc());
18878
18879 SmallVector<ParmVarDecl*, 16> Params;
18880 for (const auto &AI : FT->param_types()) {
18881 ParmVarDecl *Param =
18882 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18883 Param->setScopeInfo(0, Params.size());
18884 Params.push_back(Param);
18885 }
18886 NewFD->setParams(Params);
18887 DRE->setDecl(NewFD);
18888 VD = DRE->getDecl();
18889 }
18890 }
18891
18892 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18893 if (MD->isInstance()) {
18894 ValueKind = VK_RValue;
18895 Type = S.Context.BoundMemberTy;
18896 }
18897
18898 // Function references aren't l-values in C.
18899 if (!S.getLangOpts().CPlusPlus)
18900 ValueKind = VK_RValue;
18901
18902 // - variables
18903 } else if (isa<VarDecl>(VD)) {
18904 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18905 Type = RefTy->getPointeeType();
18906 } else if (Type->isFunctionType()) {
18907 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18908 << VD << E->getSourceRange();
18909 return ExprError();
18910 }
18911
18912 // - nothing else
18913 } else {
18914 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18915 << VD << E->getSourceRange();
18916 return ExprError();
18917 }
18918
18919 // Modifying the declaration like this is friendly to IR-gen but
18920 // also really dangerous.
18921 VD->setType(DestType);
18922 E->setType(Type);
18923 E->setValueKind(ValueKind);
18924 return E;
18925}
18926
18927/// Check a cast of an unknown-any type. We intentionally only
18928/// trigger this for C-style casts.
18929ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18930 Expr *CastExpr, CastKind &CastKind,
18931 ExprValueKind &VK, CXXCastPath &Path) {
18932 // The type we're casting to must be either void or complete.
18933 if (!CastType->isVoidType() &&
18934 RequireCompleteType(TypeRange.getBegin(), CastType,
18935 diag::err_typecheck_cast_to_incomplete))
18936 return ExprError();
18937
18938 // Rewrite the casted expression from scratch.
18939 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18940 if (!result.isUsable()) return ExprError();
18941
18942 CastExpr = result.get();
18943 VK = CastExpr->getValueKind();
18944 CastKind = CK_NoOp;
18945
18946 return CastExpr;
18947}
18948
18949ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18950 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18951}
18952
18953ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18954 Expr *arg, QualType &paramType) {
18955 // If the syntactic form of the argument is not an explicit cast of
18956 // any sort, just do default argument promotion.
18957 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18958 if (!castArg) {
18959 ExprResult result = DefaultArgumentPromotion(arg);
18960 if (result.isInvalid()) return ExprError();
18961 paramType = result.get()->getType();
18962 return result;
18963 }
18964
18965 // Otherwise, use the type that was written in the explicit cast.
18966 assert(!arg->hasPlaceholderType())((!arg->hasPlaceholderType()) ? static_cast<void> (0
) : __assert_fail ("!arg->hasPlaceholderType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 18966, __PRETTY_FUNCTION__))
;
18967 paramType = castArg->getTypeAsWritten();
18968
18969 // Copy-initialize a parameter of that type.
18970 InitializedEntity entity =
18971 InitializedEntity::InitializeParameter(Context, paramType,
18972 /*consumed*/ false);
18973 return PerformCopyInitialization(entity, callLoc, arg);
18974}
18975
18976static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18977 Expr *orig = E;
18978 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18979 while (true) {
18980 E = E->IgnoreParenImpCasts();
18981 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18982 E = call->getCallee();
18983 diagID = diag::err_uncasted_call_of_unknown_any;
18984 } else {
18985 break;
18986 }
18987 }
18988
18989 SourceLocation loc;
18990 NamedDecl *d;
18991 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18992 loc = ref->getLocation();
18993 d = ref->getDecl();
18994 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18995 loc = mem->getMemberLoc();
18996 d = mem->getMemberDecl();
18997 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18998 diagID = diag::err_uncasted_call_of_unknown_any;
18999 loc = msg->getSelectorStartLoc();
19000 d = msg->getMethodDecl();
19001 if (!d) {
19002 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19003 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19004 << orig->getSourceRange();
19005 return ExprError();
19006 }
19007 } else {
19008 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19009 << E->getSourceRange();
19010 return ExprError();
19011 }
19012
19013 S.Diag(loc, diagID) << d << orig->getSourceRange();
19014
19015 // Never recoverable.
19016 return ExprError();
19017}
19018
19019/// Check for operands with placeholder types and complain if found.
19020/// Returns ExprError() if there was an error and no recovery was possible.
19021ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19022 if (!getLangOpts().CPlusPlus) {
19023 // C cannot handle TypoExpr nodes on either side of a binop because it
19024 // doesn't handle dependent types properly, so make sure any TypoExprs have
19025 // been dealt with before checking the operands.
19026 ExprResult Result = CorrectDelayedTyposInExpr(E);
19027 if (!Result.isUsable()) return ExprError();
19028 E = Result.get();
19029 }
19030
19031 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19032 if (!placeholderType) return E;
19033
19034 switch (placeholderType->getKind()) {
19035
19036 // Overloaded expressions.
19037 case BuiltinType::Overload: {
19038 // Try to resolve a single function template specialization.
19039 // This is obligatory.
19040 ExprResult Result = E;
19041 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19042 return Result;
19043
19044 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19045 // leaves Result unchanged on failure.
19046 Result = E;
19047 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19048 return Result;
19049
19050 // If that failed, try to recover with a call.
19051 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19052 /*complain*/ true);
19053 return Result;
19054 }
19055
19056 // Bound member functions.
19057 case BuiltinType::BoundMember: {
19058 ExprResult result = E;
19059 const Expr *BME = E->IgnoreParens();
19060 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19061 // Try to give a nicer diagnostic if it is a bound member that we recognize.
19062 if (isa<CXXPseudoDestructorExpr>(BME)) {
19063 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19064 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19065 if (ME->getMemberNameInfo().getName().getNameKind() ==
19066 DeclarationName::CXXDestructorName)
19067 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19068 }
19069 tryToRecoverWithCall(result, PD,
19070 /*complain*/ true);
19071 return result;
19072 }
19073
19074 // ARC unbridged casts.
19075 case BuiltinType::ARCUnbridgedCast: {
19076 Expr *realCast = stripARCUnbridgedCast(E);
19077 diagnoseARCUnbridgedCast(realCast);
19078 return realCast;
19079 }
19080
19081 // Expressions of unknown type.
19082 case BuiltinType::UnknownAny:
19083 return diagnoseUnknownAnyExpr(*this, E);
19084
19085 // Pseudo-objects.
19086 case BuiltinType::PseudoObject:
19087 return checkPseudoObjectRValue(E);
19088
19089 case BuiltinType::BuiltinFn: {
19090 // Accept __noop without parens by implicitly converting it to a call expr.
19091 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19092 if (DRE) {
19093 auto *FD = cast<FunctionDecl>(DRE->getDecl());
19094 if (FD->getBuiltinID() == Builtin::BI__noop) {
19095 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19096 CK_BuiltinFnToFnPtr)
19097 .get();
19098 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19099 VK_RValue, SourceLocation(),
19100 FPOptionsOverride());
19101 }
19102 }
19103
19104 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19105 return ExprError();
19106 }
19107
19108 case BuiltinType::IncompleteMatrixIdx:
19109 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19110 ->getRowIdx()
19111 ->getBeginLoc(),
19112 diag::err_matrix_incomplete_index);
19113 return ExprError();
19114
19115 // Expressions of unknown type.
19116 case BuiltinType::OMPArraySection:
19117 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19118 return ExprError();
19119
19120 // Expressions of unknown type.
19121 case BuiltinType::OMPArrayShaping:
19122 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19123
19124 case BuiltinType::OMPIterator:
19125 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19126
19127 // Everything else should be impossible.
19128#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19129 case BuiltinType::Id:
19130#include "clang/Basic/OpenCLImageTypes.def"
19131#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19132 case BuiltinType::Id:
19133#include "clang/Basic/OpenCLExtensionTypes.def"
19134#define SVE_TYPE(Name, Id, SingletonId) \
19135 case BuiltinType::Id:
19136#include "clang/Basic/AArch64SVEACLETypes.def"
19137#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19138#define PLACEHOLDER_TYPE(Id, SingletonId)
19139#include "clang/AST/BuiltinTypes.def"
19140 break;
19141 }
19142
19143 llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 19143)
;
19144}
19145
19146bool Sema::CheckCaseExpression(Expr *E) {
19147 if (E->isTypeDependent())
19148 return true;
19149 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19150 return E->getType()->isIntegralOrEnumerationType();
19151 return false;
19152}
19153
19154/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19155ExprResult
19156Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19157 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
"Unknown Objective-C Boolean value!") ? static_cast<void>
(0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 19158, __PRETTY_FUNCTION__))
19158 "Unknown Objective-C Boolean value!")(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
"Unknown Objective-C Boolean value!") ? static_cast<void>
(0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaExpr.cpp"
, 19158, __PRETTY_FUNCTION__))
;
19159 QualType BoolT = Context.ObjCBuiltinBoolTy;
19160 if (!Context.getBOOLDecl()) {
19161 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19162 Sema::LookupOrdinaryName);
19163 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19164 NamedDecl *ND = Result.getFoundDecl();
19165 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19166 Context.setBOOLDecl(TD);
19167 }
19168 }
19169 if (Context.getBOOLDecl())
19170 BoolT = Context.getBOOLType();
19171 return new (Context)
19172 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19173}
19174
19175ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19176 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19177 SourceLocation RParen) {
19178
19179 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19180
19181 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19182 return Spec.getPlatform() == Platform;
19183 });
19184
19185 VersionTuple Version;
19186 if (Spec != AvailSpecs.end())
19187 Version = Spec->getVersion();
19188
19189 // The use of `@available` in the enclosing function should be analyzed to
19190 // warn when it's used inappropriately (i.e. not if(@available)).
19191 if (getCurFunctionOrMethodDecl())
19192 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19193 else if (getCurBlock() || getCurLambda())
19194 getCurFunction()->HasPotentialAvailabilityViolations = true;
19195
19196 return new (Context)
19197 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19198}
19199
19200ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19201 ArrayRef<Expr *> SubExprs, QualType T) {
19202 if (!Context.getLangOpts().RecoveryAST)
19203 return ExprError();
19204
19205 if (isSFINAEContext())
19206 return ExprError();
19207
19208 if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19209 // We don't know the concrete type, fallback to dependent type.
19210 T = Context.DependentTy;
19211 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19212}

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

/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/ADT/PointerIntPair.h

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

/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
10// and dyn_cast_or_null<X>() templates.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CASTING_H
15#define LLVM_SUPPORT_CASTING_H
16
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <memory>
21#include <type_traits>
22
23namespace llvm {
24
25//===----------------------------------------------------------------------===//
26// isa<x> Support Templates
27//===----------------------------------------------------------------------===//
28
29// Define a template that can be specialized by smart pointers to reflect the
30// fact that they are automatically dereferenced, and are not involved with the
31// template selection process... the default implementation is a noop.
32//
33template<typename From> struct simplify_type {
34 using SimpleType = From; // The real type this represents...
35
36 // An accessor to get the real value...
37 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
38};
39
40template<typename From> struct simplify_type<const From> {
41 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
42 using SimpleType =
43 typename add_const_past_pointer<NonConstSimpleType>::type;
44 using RetType =
45 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
46
47 static RetType getSimplifiedValue(const From& Val) {
48 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
49 }
50};
51
52// The core of the implementation of isa<X> is here; To and From should be
53// the names of classes. This template can be specialized to customize the
54// implementation of isa<> without rewriting it from scratch.
55template <typename To, typename From, typename Enabler = void>
56struct isa_impl {
57 static inline bool doit(const From &Val) {
58 return To::classof(&Val);
59 }
60};
61
62/// Always allow upcasts, and perform no dynamic check for them.
63template <typename To, typename From>
64struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> {
65 static inline bool doit(const From &) { return true; }
66};
67
68template <typename To, typename From> struct isa_impl_cl {
69 static inline bool doit(const From &Val) {
70 return isa_impl<To, From>::doit(Val);
71 }
72};
73
74template <typename To, typename From> struct isa_impl_cl<To, const From> {
75 static inline bool doit(const From &Val) {
76 return isa_impl<To, From>::doit(Val);
77 }
78};
79
80template <typename To, typename From>
81struct isa_impl_cl<To, const std::unique_ptr<From>> {
82 static inline bool doit(const std::unique_ptr<From> &Val) {
83 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 83, __PRETTY_FUNCTION__))
;
84 return isa_impl_cl<To, From>::doit(*Val);
85 }
86};
87
88template <typename To, typename From> struct isa_impl_cl<To, From*> {
89 static inline bool doit(const From *Val) {
90 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 90, __PRETTY_FUNCTION__))
;
91 return isa_impl<To, From>::doit(*Val);
92 }
93};
94
95template <typename To, typename From> struct isa_impl_cl<To, From*const> {
96 static inline bool doit(const From *Val) {
97 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 97, __PRETTY_FUNCTION__))
;
98 return isa_impl<To, From>::doit(*Val);
99 }
100};
101
102template <typename To, typename From> struct isa_impl_cl<To, const From*> {
103 static inline bool doit(const From *Val) {
104 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 104, __PRETTY_FUNCTION__))
;
105 return isa_impl<To, From>::doit(*Val);
106 }
107};
108
109template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
110 static inline bool doit(const From *Val) {
111 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 111, __PRETTY_FUNCTION__))
;
112 return isa_impl<To, From>::doit(*Val);
113 }
114};
115
116template<typename To, typename From, typename SimpleFrom>
117struct isa_impl_wrap {
118 // When From != SimplifiedType, we can simplify the type some more by using
119 // the simplify_type template.
120 static bool doit(const From &Val) {
121 return isa_impl_wrap<To, SimpleFrom,
122 typename simplify_type<SimpleFrom>::SimpleType>::doit(
123 simplify_type<const From>::getSimplifiedValue(Val));
124 }
125};
126
127template<typename To, typename FromTy>
128struct isa_impl_wrap<To, FromTy, FromTy> {
129 // When From == SimpleType, we are as simple as we are going to get.
130 static bool doit(const FromTy &Val) {
131 return isa_impl_cl<To,FromTy>::doit(Val);
132 }
133};
134
135// isa<X> - Return true if the parameter to the template is an instance of one
136// of the template type arguments. Used like this:
137//
138// if (isa<Type>(myVal)) { ... }
139// if (isa<Type0, Type1, Type2>(myVal)) { ... }
140//
141template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
142 return isa_impl_wrap<X, const Y,
143 typename simplify_type<const Y>::SimpleType>::doit(Val);
144}
145
146template <typename First, typename Second, typename... Rest, typename Y>
147LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
148 return isa<First>(Val) || isa<Second, Rest...>(Val);
149}
150
151// isa_and_nonnull<X> - Functionally identical to isa, except that a null value
152// is accepted.
153//
154template <typename... X, class Y>
155LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa_and_nonnull(const Y &Val) {
156 if (!Val)
157 return false;
158 return isa<X...>(Val);
159}
160
161//===----------------------------------------------------------------------===//
162// cast<x> Support Templates
163//===----------------------------------------------------------------------===//
164
165template<class To, class From> struct cast_retty;
166
167// Calculate what type the 'cast' function should return, based on a requested
168// type of To and a source type of From.
169template<class To, class From> struct cast_retty_impl {
170 using ret_type = To &; // Normal case, return Ty&
171};
172template<class To, class From> struct cast_retty_impl<To, const From> {
173 using ret_type = const To &; // Normal case, return Ty&
174};
175
176template<class To, class From> struct cast_retty_impl<To, From*> {
177 using ret_type = To *; // Pointer arg case, return Ty*
178};
179
180template<class To, class From> struct cast_retty_impl<To, const From*> {
181 using ret_type = const To *; // Constant pointer arg case, return const Ty*
182};
183
184template<class To, class From> struct cast_retty_impl<To, const From*const> {
185 using ret_type = const To *; // Constant pointer arg case, return const Ty*
186};
187
188template <class To, class From>
189struct cast_retty_impl<To, std::unique_ptr<From>> {
190private:
191 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
192 using ResultType = std::remove_pointer_t<PointerType>;
193
194public:
195 using ret_type = std::unique_ptr<ResultType>;
196};
197
198template<class To, class From, class SimpleFrom>
199struct cast_retty_wrap {
200 // When the simplified type and the from type are not the same, use the type
201 // simplifier to reduce the type, then reuse cast_retty_impl to get the
202 // resultant type.
203 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
204};
205
206template<class To, class FromTy>
207struct cast_retty_wrap<To, FromTy, FromTy> {
208 // When the simplified type is equal to the from type, use it directly.
209 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
210};
211
212template<class To, class From>
213struct cast_retty {
214 using ret_type = typename cast_retty_wrap<
215 To, From, typename simplify_type<From>::SimpleType>::ret_type;
216};
217
218// Ensure the non-simple values are converted using the simplify_type template
219// that may be specialized by smart pointers...
220//
221template<class To, class From, class SimpleFrom> struct cast_convert_val {
222 // This is not a simple type, use the template to simplify it...
223 static typename cast_retty<To, From>::ret_type doit(From &Val) {
224 return cast_convert_val<To, SimpleFrom,
225 typename simplify_type<SimpleFrom>::SimpleType>::doit(
226 simplify_type<From>::getSimplifiedValue(Val));
227 }
228};
229
230template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
231 // This _is_ a simple type, just cast it.
232 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
233 typename cast_retty<To, FromTy>::ret_type Res2
234 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
235 return Res2;
236 }
237};
238
239template <class X> struct is_simple_type {
240 static const bool value =
241 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
242};
243
244// cast<X> - Return the argument parameter cast to the specified type. This
245// casting operator asserts that the type is correct, so it does not return null
246// on failure. It does not allow a null argument (use cast_or_null for that).
247// It is typically used like this:
248//
249// cast<Instruction>(myVal)->getParent()
250//
251template <class X, class Y>
252inline std::enable_if_t<!is_simple_type<Y>::value,
253 typename cast_retty<X, const Y>::ret_type>
254cast(const Y &Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 255, __PRETTY_FUNCTION__))
;
256 return cast_convert_val<
257 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
262 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 262, __PRETTY_FUNCTION__))
;
54
'Val' is a 'PointerType'
55
'?' condition is true
263 return cast_convert_val<X, Y,
56
Returning pointer, which participates in a condition later
264 typename simplify_type<Y>::SimpleType>::doit(Val);
265}
266
267template <class X, class Y>
268inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
269 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 269, __PRETTY_FUNCTION__))
;
270 return cast_convert_val<X, Y*,
271 typename simplify_type<Y*>::SimpleType>::doit(Val);
272}
273
274template <class X, class Y>
275inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
276cast(std::unique_ptr<Y> &&Val) {
277 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 277, __PRETTY_FUNCTION__))
;
278 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
279 return ret_type(
280 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
281 Val.release()));
282}
283
284// cast_or_null<X> - Functionally identical to cast, except that a null value is
285// accepted.
286//
287template <class X, class Y>
288LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
289 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
290cast_or_null(const Y &Val) {
291 if (!Val)
292 return nullptr;
293 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 293, __PRETTY_FUNCTION__))
;
294 return cast<X>(Val);
295}
296
297template <class X, class Y>
298LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
299 typename cast_retty<X, Y>::ret_type>
300cast_or_null(Y &Val) {
301 if (!Val)
302 return nullptr;
303 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 303, __PRETTY_FUNCTION__))
;
304 return cast<X>(Val);
305}
306
307template <class X, class Y>
308LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
309cast_or_null(Y *Val) {
310 if (!Val) return nullptr;
311 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include/llvm/Support/Casting.h"
, 311, __PRETTY_FUNCTION__))
;
312 return cast<X>(Val);
313}
314
315template <class X, class Y>
316inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
317cast_or_null(std::unique_ptr<Y> &&Val) {
318 if (!Val)
319 return nullptr;
320 return cast<X>(std::move(Val));
321}
322
323// dyn_cast<X> - Return the argument parameter cast to the specified type. This
324// casting operator returns null if the argument is of the wrong type, so it can
325// be used to test for a type as well as cast if successful. This should be
326// used in the context of an if statement like this:
327//
328// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
329//
330
331template <class X, class Y>
332LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
333 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
334dyn_cast(const Y &Val) {
335 return isa<X>(Val) ? cast<X>(Val) : nullptr;
66
Assuming 'Val' is not a 'BuiltinType'
67
'?' condition is false
68
Returning null pointer, which participates in a condition later
72
Assuming 'Val' is not a 'EnumType'
73
'?' condition is false
74
Returning null pointer, which participates in a condition later
336}
337
338template <class X, class Y>
339LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
340 return isa<X>(Val) ? cast<X>(Val) : nullptr;
10
Assuming 'Val' is not a 'AtomicType'
11
'?' condition is false
12
Returning null pointer, which participates in a condition later
51
Assuming 'Val' is a 'PointerType'
52
'?' condition is true
53
Calling 'cast<clang::PointerType, clang::QualType>'
57
Returning from 'cast<clang::PointerType, clang::QualType>'
58
Returning pointer, which participates in a condition later
341}
342
343template <class X, class Y>
344LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
345 return isa<X>(Val) ? cast<X>(Val) : nullptr;
346}
347
348// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
349// value is accepted.
350//
351template <class X, class Y>
352LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
353 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
354dyn_cast_or_null(const Y &Val) {
355 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
356}
357
358template <class X, class Y>
359LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
360 typename cast_retty<X, Y>::ret_type>
361dyn_cast_or_null(Y &Val) {
362 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
363}
364
365template <class X, class Y>
366LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
367dyn_cast_or_null(Y *Val) {
368 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
369}
370
371// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
372// taking ownership of the input pointer iff isa<X>(Val) is true. If the
373// cast is successful, From refers to nullptr on exit and the casted value
374// is returned. If the cast is unsuccessful, the function returns nullptr
375// and From is unchanged.
376template <class X, class Y>
377LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
378 -> decltype(cast<X>(Val)) {
379 if (!isa<X>(Val))
380 return nullptr;
381 return cast<X>(std::move(Val));
382}
383
384template <class X, class Y>
385LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
386 return unique_dyn_cast<X, Y>(Val);
387}
388
389// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
390// a null value is accepted.
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
393 -> decltype(cast<X>(Val)) {
394 if (!Val)
395 return nullptr;
396 return unique_dyn_cast<X, Y>(Val);
397}
398
399template <class X, class Y>
400LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
401 return unique_dyn_cast_or_null<X, Y>(Val);
402}
403
404} // end namespace llvm
405
406#endif // LLVM_SUPPORT_CASTING_H