Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp
35233 views
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 "CheckExprLifetime.h"
14
#include "TreeTransform.h"
15
#include "UsedDeclVisitor.h"
16
#include "clang/AST/ASTConsumer.h"
17
#include "clang/AST/ASTContext.h"
18
#include "clang/AST/ASTLambda.h"
19
#include "clang/AST/ASTMutationListener.h"
20
#include "clang/AST/CXXInheritance.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/EvaluatedExprVisitor.h"
24
#include "clang/AST/Expr.h"
25
#include "clang/AST/ExprCXX.h"
26
#include "clang/AST/ExprObjC.h"
27
#include "clang/AST/ExprOpenMP.h"
28
#include "clang/AST/OperationKinds.h"
29
#include "clang/AST/ParentMapContext.h"
30
#include "clang/AST/RecursiveASTVisitor.h"
31
#include "clang/AST/Type.h"
32
#include "clang/AST/TypeLoc.h"
33
#include "clang/Basic/Builtins.h"
34
#include "clang/Basic/DiagnosticSema.h"
35
#include "clang/Basic/PartialDiagnostic.h"
36
#include "clang/Basic/SourceManager.h"
37
#include "clang/Basic/Specifiers.h"
38
#include "clang/Basic/TargetInfo.h"
39
#include "clang/Basic/TypeTraits.h"
40
#include "clang/Lex/LiteralSupport.h"
41
#include "clang/Lex/Preprocessor.h"
42
#include "clang/Sema/AnalysisBasedWarnings.h"
43
#include "clang/Sema/DeclSpec.h"
44
#include "clang/Sema/DelayedDiagnostic.h"
45
#include "clang/Sema/Designator.h"
46
#include "clang/Sema/EnterExpressionEvaluationContext.h"
47
#include "clang/Sema/Initialization.h"
48
#include "clang/Sema/Lookup.h"
49
#include "clang/Sema/Overload.h"
50
#include "clang/Sema/ParsedTemplate.h"
51
#include "clang/Sema/Scope.h"
52
#include "clang/Sema/ScopeInfo.h"
53
#include "clang/Sema/SemaCUDA.h"
54
#include "clang/Sema/SemaFixItUtils.h"
55
#include "clang/Sema/SemaInternal.h"
56
#include "clang/Sema/SemaObjC.h"
57
#include "clang/Sema/SemaOpenMP.h"
58
#include "clang/Sema/SemaPseudoObject.h"
59
#include "clang/Sema/Template.h"
60
#include "llvm/ADT/STLExtras.h"
61
#include "llvm/ADT/STLForwardCompat.h"
62
#include "llvm/ADT/StringExtras.h"
63
#include "llvm/Support/Casting.h"
64
#include "llvm/Support/ConvertUTF.h"
65
#include "llvm/Support/SaveAndRestore.h"
66
#include "llvm/Support/TypeSize.h"
67
#include <optional>
68
69
using namespace clang;
70
using namespace sema;
71
72
bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
73
// See if this is an auto-typed variable whose initializer we are parsing.
74
if (ParsingInitForAutoVars.count(D))
75
return false;
76
77
// See if this is a deleted function.
78
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
79
if (FD->isDeleted())
80
return false;
81
82
// If the function has a deduced return type, and we can't deduce it,
83
// then we can't use it either.
84
if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
85
DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
86
return false;
87
88
// See if this is an aligned allocation/deallocation function that is
89
// unavailable.
90
if (TreatUnavailableAsInvalid &&
91
isUnavailableAlignedAllocationFunction(*FD))
92
return false;
93
}
94
95
// See if this function is unavailable.
96
if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
97
cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
98
return false;
99
100
if (isa<UnresolvedUsingIfExistsDecl>(D))
101
return false;
102
103
return true;
104
}
105
106
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
107
// Warn if this is used but marked unused.
108
if (const auto *A = D->getAttr<UnusedAttr>()) {
109
// [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
110
// should diagnose them.
111
if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
112
A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
113
const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
114
if (DC && !DC->hasAttr<UnusedAttr>())
115
S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
116
}
117
}
118
}
119
120
void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
121
assert(Decl && Decl->isDeleted());
122
123
if (Decl->isDefaulted()) {
124
// If the method was explicitly defaulted, point at that declaration.
125
if (!Decl->isImplicit())
126
Diag(Decl->getLocation(), diag::note_implicitly_deleted);
127
128
// Try to diagnose why this special member function was implicitly
129
// deleted. This might fail, if that reason no longer applies.
130
DiagnoseDeletedDefaultedFunction(Decl);
131
return;
132
}
133
134
auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
135
if (Ctor && Ctor->isInheritingConstructor())
136
return NoteDeletedInheritingConstructor(Ctor);
137
138
Diag(Decl->getLocation(), diag::note_availability_specified_here)
139
<< Decl << 1;
140
}
141
142
/// Determine whether a FunctionDecl was ever declared with an
143
/// explicit storage class.
144
static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
145
for (auto *I : D->redecls()) {
146
if (I->getStorageClass() != SC_None)
147
return true;
148
}
149
return false;
150
}
151
152
/// Check whether we're in an extern inline function and referring to a
153
/// variable or function with internal linkage (C11 6.7.4p3).
154
///
155
/// This is only a warning because we used to silently accept this code, but
156
/// in many cases it will not behave correctly. This is not enabled in C++ mode
157
/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
158
/// and so while there may still be user mistakes, most of the time we can't
159
/// prove that there are errors.
160
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
161
const NamedDecl *D,
162
SourceLocation Loc) {
163
// This is disabled under C++; there are too many ways for this to fire in
164
// contexts where the warning is a false positive, or where it is technically
165
// correct but benign.
166
if (S.getLangOpts().CPlusPlus)
167
return;
168
169
// Check if this is an inlined function or method.
170
FunctionDecl *Current = S.getCurFunctionDecl();
171
if (!Current)
172
return;
173
if (!Current->isInlined())
174
return;
175
if (!Current->isExternallyVisible())
176
return;
177
178
// Check if the decl has internal linkage.
179
if (D->getFormalLinkage() != Linkage::Internal)
180
return;
181
182
// Downgrade from ExtWarn to Extension if
183
// (1) the supposedly external inline function is in the main file,
184
// and probably won't be included anywhere else.
185
// (2) the thing we're referencing is a pure function.
186
// (3) the thing we're referencing is another inline function.
187
// This last can give us false negatives, but it's better than warning on
188
// wrappers for simple C library functions.
189
const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
190
bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
191
if (!DowngradeWarning && UsedFn)
192
DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
193
194
S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
195
: diag::ext_internal_in_extern_inline)
196
<< /*IsVar=*/!UsedFn << D;
197
198
S.MaybeSuggestAddingStaticToDecl(Current);
199
200
S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
201
<< D;
202
}
203
204
void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
205
const FunctionDecl *First = Cur->getFirstDecl();
206
207
// Suggest "static" on the function, if possible.
208
if (!hasAnyExplicitStorageClass(First)) {
209
SourceLocation DeclBegin = First->getSourceRange().getBegin();
210
Diag(DeclBegin, diag::note_convert_inline_to_static)
211
<< Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
212
}
213
}
214
215
bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
216
const ObjCInterfaceDecl *UnknownObjCClass,
217
bool ObjCPropertyAccess,
218
bool AvoidPartialAvailabilityChecks,
219
ObjCInterfaceDecl *ClassReceiver,
220
bool SkipTrailingRequiresClause) {
221
SourceLocation Loc = Locs.front();
222
if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
223
// If there were any diagnostics suppressed by template argument deduction,
224
// emit them now.
225
auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
226
if (Pos != SuppressedDiagnostics.end()) {
227
for (const PartialDiagnosticAt &Suppressed : Pos->second)
228
Diag(Suppressed.first, Suppressed.second);
229
230
// Clear out the list of suppressed diagnostics, so that we don't emit
231
// them again for this specialization. However, we don't obsolete this
232
// entry from the table, because we want to avoid ever emitting these
233
// diagnostics again.
234
Pos->second.clear();
235
}
236
237
// C++ [basic.start.main]p3:
238
// The function 'main' shall not be used within a program.
239
if (cast<FunctionDecl>(D)->isMain())
240
Diag(Loc, diag::ext_main_used);
241
242
diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
243
}
244
245
// See if this is an auto-typed variable whose initializer we are parsing.
246
if (ParsingInitForAutoVars.count(D)) {
247
if (isa<BindingDecl>(D)) {
248
Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
249
<< D->getDeclName();
250
} else {
251
Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
252
<< D->getDeclName() << cast<VarDecl>(D)->getType();
253
}
254
return true;
255
}
256
257
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
258
// See if this is a deleted function.
259
if (FD->isDeleted()) {
260
auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
261
if (Ctor && Ctor->isInheritingConstructor())
262
Diag(Loc, diag::err_deleted_inherited_ctor_use)
263
<< Ctor->getParent()
264
<< Ctor->getInheritedConstructor().getConstructor()->getParent();
265
else {
266
StringLiteral *Msg = FD->getDeletedMessage();
267
Diag(Loc, diag::err_deleted_function_use)
268
<< (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
269
}
270
NoteDeletedFunction(FD);
271
return true;
272
}
273
274
// [expr.prim.id]p4
275
// A program that refers explicitly or implicitly to a function with a
276
// trailing requires-clause whose constraint-expression is not satisfied,
277
// other than to declare it, is ill-formed. [...]
278
//
279
// See if this is a function with constraints that need to be satisfied.
280
// Check this before deducing the return type, as it might instantiate the
281
// definition.
282
if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
283
ConstraintSatisfaction Satisfaction;
284
if (CheckFunctionConstraints(FD, Satisfaction, Loc,
285
/*ForOverloadResolution*/ true))
286
// A diagnostic will have already been generated (non-constant
287
// constraint expression, for example)
288
return true;
289
if (!Satisfaction.IsSatisfied) {
290
Diag(Loc,
291
diag::err_reference_to_function_with_unsatisfied_constraints)
292
<< D;
293
DiagnoseUnsatisfiedConstraint(Satisfaction);
294
return true;
295
}
296
}
297
298
// If the function has a deduced return type, and we can't deduce it,
299
// then we can't use it either.
300
if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
301
DeduceReturnType(FD, Loc))
302
return true;
303
304
if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
305
return true;
306
307
}
308
309
if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
310
// Lambdas are only default-constructible or assignable in C++2a onwards.
311
if (MD->getParent()->isLambda() &&
312
((isa<CXXConstructorDecl>(MD) &&
313
cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
314
MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
315
Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
316
<< !isa<CXXConstructorDecl>(MD);
317
}
318
}
319
320
auto getReferencedObjCProp = [](const NamedDecl *D) ->
321
const ObjCPropertyDecl * {
322
if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
323
return MD->findPropertyDecl();
324
return nullptr;
325
};
326
if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
327
if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
328
return true;
329
} else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
330
return true;
331
}
332
333
// [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
334
// Only the variables omp_in and omp_out are allowed in the combiner.
335
// Only the variables omp_priv and omp_orig are allowed in the
336
// initializer-clause.
337
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
338
if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
339
isa<VarDecl>(D)) {
340
Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
341
<< getCurFunction()->HasOMPDeclareReductionCombiner;
342
Diag(D->getLocation(), diag::note_entity_declared_at) << D;
343
return true;
344
}
345
346
// [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
347
// List-items in map clauses on this construct may only refer to the declared
348
// variable var and entities that could be referenced by a procedure defined
349
// at the same location.
350
// [OpenMP 5.2] Also allow iterator declared variables.
351
if (LangOpts.OpenMP && isa<VarDecl>(D) &&
352
!OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
353
Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
354
<< OpenMP().getOpenMPDeclareMapperVarName();
355
Diag(D->getLocation(), diag::note_entity_declared_at) << D;
356
return true;
357
}
358
359
if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
360
Diag(Loc, diag::err_use_of_empty_using_if_exists);
361
Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
362
return true;
363
}
364
365
DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
366
AvoidPartialAvailabilityChecks, ClassReceiver);
367
368
DiagnoseUnusedOfDecl(*this, D, Loc);
369
370
diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
371
372
if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
373
if (getLangOpts().getFPEvalMethod() !=
374
LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
375
PP.getLastFPEvalPragmaLocation().isValid() &&
376
PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
377
Diag(D->getLocation(),
378
diag::err_type_available_only_in_default_eval_method)
379
<< D->getName();
380
}
381
382
if (auto *VD = dyn_cast<ValueDecl>(D))
383
checkTypeSupport(VD->getType(), Loc, VD);
384
385
if (LangOpts.SYCLIsDevice ||
386
(LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
387
if (!Context.getTargetInfo().isTLSSupported())
388
if (const auto *VD = dyn_cast<VarDecl>(D))
389
if (VD->getTLSKind() != VarDecl::TLS_None)
390
targetDiag(*Locs.begin(), diag::err_thread_unsupported);
391
}
392
393
if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
394
!isUnevaluatedContext()) {
395
// C++ [expr.prim.req.nested] p3
396
// A local parameter shall only appear as an unevaluated operand
397
// (Clause 8) within the constraint-expression.
398
Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
399
<< D;
400
Diag(D->getLocation(), diag::note_entity_declared_at) << D;
401
return true;
402
}
403
404
return false;
405
}
406
407
void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
408
ArrayRef<Expr *> Args) {
409
const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
410
if (!Attr)
411
return;
412
413
// The number of formal parameters of the declaration.
414
unsigned NumFormalParams;
415
416
// The kind of declaration. This is also an index into a %select in
417
// the diagnostic.
418
enum { CK_Function, CK_Method, CK_Block } CalleeKind;
419
420
if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
421
NumFormalParams = MD->param_size();
422
CalleeKind = CK_Method;
423
} else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
424
NumFormalParams = FD->param_size();
425
CalleeKind = CK_Function;
426
} else if (const auto *VD = dyn_cast<VarDecl>(D)) {
427
QualType Ty = VD->getType();
428
const FunctionType *Fn = nullptr;
429
if (const auto *PtrTy = Ty->getAs<PointerType>()) {
430
Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
431
if (!Fn)
432
return;
433
CalleeKind = CK_Function;
434
} else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
435
Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
436
CalleeKind = CK_Block;
437
} else {
438
return;
439
}
440
441
if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
442
NumFormalParams = proto->getNumParams();
443
else
444
NumFormalParams = 0;
445
} else {
446
return;
447
}
448
449
// "NullPos" is the number of formal parameters at the end which
450
// effectively count as part of the variadic arguments. This is
451
// useful if you would prefer to not have *any* formal parameters,
452
// but the language forces you to have at least one.
453
unsigned NullPos = Attr->getNullPos();
454
assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
455
NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
456
457
// The number of arguments which should follow the sentinel.
458
unsigned NumArgsAfterSentinel = Attr->getSentinel();
459
460
// If there aren't enough arguments for all the formal parameters,
461
// the sentinel, and the args after the sentinel, complain.
462
if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
463
Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
464
Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
465
return;
466
}
467
468
// Otherwise, find the sentinel expression.
469
const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
470
if (!SentinelExpr)
471
return;
472
if (SentinelExpr->isValueDependent())
473
return;
474
if (Context.isSentinelNullExpr(SentinelExpr))
475
return;
476
477
// Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
478
// or 'NULL' if those are actually defined in the context. Only use
479
// 'nil' for ObjC methods, where it's much more likely that the
480
// variadic arguments form a list of object pointers.
481
SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
482
std::string NullValue;
483
if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
484
NullValue = "nil";
485
else if (getLangOpts().CPlusPlus11)
486
NullValue = "nullptr";
487
else if (PP.isMacroDefined("NULL"))
488
NullValue = "NULL";
489
else
490
NullValue = "(void*) 0";
491
492
if (MissingNilLoc.isInvalid())
493
Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
494
else
495
Diag(MissingNilLoc, diag::warn_missing_sentinel)
496
<< int(CalleeKind)
497
<< FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
498
Diag(D->getLocation(), diag::note_sentinel_here)
499
<< int(CalleeKind) << Attr->getRange();
500
}
501
502
SourceRange Sema::getExprRange(Expr *E) const {
503
return E ? E->getSourceRange() : SourceRange();
504
}
505
506
//===----------------------------------------------------------------------===//
507
// Standard Promotions and Conversions
508
//===----------------------------------------------------------------------===//
509
510
/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
511
ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
512
// Handle any placeholder expressions which made it here.
513
if (E->hasPlaceholderType()) {
514
ExprResult result = CheckPlaceholderExpr(E);
515
if (result.isInvalid()) return ExprError();
516
E = result.get();
517
}
518
519
QualType Ty = E->getType();
520
assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
521
522
if (Ty->isFunctionType()) {
523
if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
524
if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
525
if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
526
return ExprError();
527
528
E = ImpCastExprToType(E, Context.getPointerType(Ty),
529
CK_FunctionToPointerDecay).get();
530
} else if (Ty->isArrayType()) {
531
// In C90 mode, arrays only promote to pointers if the array expression is
532
// an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
533
// type 'array of type' is converted to an expression that has type 'pointer
534
// to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
535
// that has type 'array of type' ...". The relevant change is "an lvalue"
536
// (C90) to "an expression" (C99).
537
//
538
// C++ 4.2p1:
539
// An lvalue or rvalue of type "array of N T" or "array of unknown bound of
540
// T" can be converted to an rvalue of type "pointer to T".
541
//
542
if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
543
ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
544
CK_ArrayToPointerDecay);
545
if (Res.isInvalid())
546
return ExprError();
547
E = Res.get();
548
}
549
}
550
return E;
551
}
552
553
static void CheckForNullPointerDereference(Sema &S, Expr *E) {
554
// Check to see if we are dereferencing a null pointer. If so,
555
// and if not volatile-qualified, this is undefined behavior that the
556
// optimizer will delete, so warn about it. People sometimes try to use this
557
// to get a deterministic trap and are surprised by clang's behavior. This
558
// only handles the pattern "*null", which is a very syntactic check.
559
const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
560
if (UO && UO->getOpcode() == UO_Deref &&
561
UO->getSubExpr()->getType()->isPointerType()) {
562
const LangAS AS =
563
UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
564
if ((!isTargetAddressSpace(AS) ||
565
(isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
566
UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
567
S.Context, Expr::NPC_ValueDependentIsNotNull) &&
568
!UO->getType().isVolatileQualified()) {
569
S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
570
S.PDiag(diag::warn_indirection_through_null)
571
<< UO->getSubExpr()->getSourceRange());
572
S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
573
S.PDiag(diag::note_indirection_through_null));
574
}
575
}
576
}
577
578
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
579
SourceLocation AssignLoc,
580
const Expr* RHS) {
581
const ObjCIvarDecl *IV = OIRE->getDecl();
582
if (!IV)
583
return;
584
585
DeclarationName MemberName = IV->getDeclName();
586
IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
587
if (!Member || !Member->isStr("isa"))
588
return;
589
590
const Expr *Base = OIRE->getBase();
591
QualType BaseType = Base->getType();
592
if (OIRE->isArrow())
593
BaseType = BaseType->getPointeeType();
594
if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
595
if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
596
ObjCInterfaceDecl *ClassDeclared = nullptr;
597
ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
598
if (!ClassDeclared->getSuperClass()
599
&& (*ClassDeclared->ivar_begin()) == IV) {
600
if (RHS) {
601
NamedDecl *ObjectSetClass =
602
S.LookupSingleName(S.TUScope,
603
&S.Context.Idents.get("object_setClass"),
604
SourceLocation(), S.LookupOrdinaryName);
605
if (ObjectSetClass) {
606
SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
607
S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
608
<< FixItHint::CreateInsertion(OIRE->getBeginLoc(),
609
"object_setClass(")
610
<< FixItHint::CreateReplacement(
611
SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
612
<< FixItHint::CreateInsertion(RHSLocEnd, ")");
613
}
614
else
615
S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
616
} else {
617
NamedDecl *ObjectGetClass =
618
S.LookupSingleName(S.TUScope,
619
&S.Context.Idents.get("object_getClass"),
620
SourceLocation(), S.LookupOrdinaryName);
621
if (ObjectGetClass)
622
S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
623
<< FixItHint::CreateInsertion(OIRE->getBeginLoc(),
624
"object_getClass(")
625
<< FixItHint::CreateReplacement(
626
SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
627
else
628
S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
629
}
630
S.Diag(IV->getLocation(), diag::note_ivar_decl);
631
}
632
}
633
}
634
635
ExprResult Sema::DefaultLvalueConversion(Expr *E) {
636
// Handle any placeholder expressions which made it here.
637
if (E->hasPlaceholderType()) {
638
ExprResult result = CheckPlaceholderExpr(E);
639
if (result.isInvalid()) return ExprError();
640
E = result.get();
641
}
642
643
// C++ [conv.lval]p1:
644
// A glvalue of a non-function, non-array type T can be
645
// converted to a prvalue.
646
if (!E->isGLValue()) return E;
647
648
QualType T = E->getType();
649
assert(!T.isNull() && "r-value conversion on typeless expression?");
650
651
// lvalue-to-rvalue conversion cannot be applied to types that decay to
652
// pointers (i.e. function or array types).
653
if (T->canDecayToPointerType())
654
return E;
655
656
// We don't want to throw lvalue-to-rvalue casts on top of
657
// expressions of certain types in C++.
658
if (getLangOpts().CPlusPlus) {
659
if (T == Context.OverloadTy || T->isRecordType() ||
660
(T->isDependentType() && !T->isAnyPointerType() &&
661
!T->isMemberPointerType()))
662
return E;
663
}
664
665
// The C standard is actually really unclear on this point, and
666
// DR106 tells us what the result should be but not why. It's
667
// generally best to say that void types just doesn't undergo
668
// lvalue-to-rvalue at all. Note that expressions of unqualified
669
// 'void' type are never l-values, but qualified void can be.
670
if (T->isVoidType())
671
return E;
672
673
// OpenCL usually rejects direct accesses to values of 'half' type.
674
if (getLangOpts().OpenCL &&
675
!getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
676
T->isHalfType()) {
677
Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
678
<< 0 << T;
679
return ExprError();
680
}
681
682
CheckForNullPointerDereference(*this, E);
683
if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
684
NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
685
&Context.Idents.get("object_getClass"),
686
SourceLocation(), LookupOrdinaryName);
687
if (ObjectGetClass)
688
Diag(E->getExprLoc(), diag::warn_objc_isa_use)
689
<< FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
690
<< FixItHint::CreateReplacement(
691
SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
692
else
693
Diag(E->getExprLoc(), diag::warn_objc_isa_use);
694
}
695
else if (const ObjCIvarRefExpr *OIRE =
696
dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
697
DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
698
699
// C++ [conv.lval]p1:
700
// [...] If T is a non-class type, the type of the prvalue is the
701
// cv-unqualified version of T. Otherwise, the type of the
702
// rvalue is T.
703
//
704
// C99 6.3.2.1p2:
705
// If the lvalue has qualified type, the value has the unqualified
706
// version of the type of the lvalue; otherwise, the value has the
707
// type of the lvalue.
708
if (T.hasQualifiers())
709
T = T.getUnqualifiedType();
710
711
// Under the MS ABI, lock down the inheritance model now.
712
if (T->isMemberPointerType() &&
713
Context.getTargetInfo().getCXXABI().isMicrosoft())
714
(void)isCompleteType(E->getExprLoc(), T);
715
716
ExprResult Res = CheckLValueToRValueConversionOperand(E);
717
if (Res.isInvalid())
718
return Res;
719
E = Res.get();
720
721
// Loading a __weak object implicitly retains the value, so we need a cleanup to
722
// balance that.
723
if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
724
Cleanup.setExprNeedsCleanups(true);
725
726
if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
727
Cleanup.setExprNeedsCleanups(true);
728
729
// C++ [conv.lval]p3:
730
// If T is cv std::nullptr_t, the result is a null pointer constant.
731
CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
732
Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
733
CurFPFeatureOverrides());
734
735
// C11 6.3.2.1p2:
736
// ... if the lvalue has atomic type, the value has the non-atomic version
737
// of the type of the lvalue ...
738
if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
739
T = Atomic->getValueType().getUnqualifiedType();
740
Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
741
nullptr, VK_PRValue, FPOptionsOverride());
742
}
743
744
return Res;
745
}
746
747
ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
748
ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
749
if (Res.isInvalid())
750
return ExprError();
751
Res = DefaultLvalueConversion(Res.get());
752
if (Res.isInvalid())
753
return ExprError();
754
return Res;
755
}
756
757
ExprResult Sema::CallExprUnaryConversions(Expr *E) {
758
QualType Ty = E->getType();
759
ExprResult Res = E;
760
// Only do implicit cast for a function type, but not for a pointer
761
// to function type.
762
if (Ty->isFunctionType()) {
763
Res = ImpCastExprToType(E, Context.getPointerType(Ty),
764
CK_FunctionToPointerDecay);
765
if (Res.isInvalid())
766
return ExprError();
767
}
768
Res = DefaultLvalueConversion(Res.get());
769
if (Res.isInvalid())
770
return ExprError();
771
return Res.get();
772
}
773
774
/// UsualUnaryConversions - Performs various conversions that are common to most
775
/// operators (C99 6.3). The conversions of array and function types are
776
/// sometimes suppressed. For example, the array->pointer conversion doesn't
777
/// apply if the array is an argument to the sizeof or address (&) operators.
778
/// In these instances, this routine should *not* be called.
779
ExprResult Sema::UsualUnaryConversions(Expr *E) {
780
// First, convert to an r-value.
781
ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
782
if (Res.isInvalid())
783
return ExprError();
784
E = Res.get();
785
786
QualType Ty = E->getType();
787
assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
788
789
LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
790
if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
791
(getLangOpts().getFPEvalMethod() !=
792
LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
793
PP.getLastFPEvalPragmaLocation().isValid())) {
794
switch (EvalMethod) {
795
default:
796
llvm_unreachable("Unrecognized float evaluation method");
797
break;
798
case LangOptions::FEM_UnsetOnCommandLine:
799
llvm_unreachable("Float evaluation method should be set by now");
800
break;
801
case LangOptions::FEM_Double:
802
if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
803
// Widen the expression to double.
804
return Ty->isComplexType()
805
? ImpCastExprToType(E,
806
Context.getComplexType(Context.DoubleTy),
807
CK_FloatingComplexCast)
808
: ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
809
break;
810
case LangOptions::FEM_Extended:
811
if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
812
// Widen the expression to long double.
813
return Ty->isComplexType()
814
? ImpCastExprToType(
815
E, Context.getComplexType(Context.LongDoubleTy),
816
CK_FloatingComplexCast)
817
: ImpCastExprToType(E, Context.LongDoubleTy,
818
CK_FloatingCast);
819
break;
820
}
821
}
822
823
// Half FP have to be promoted to float unless it is natively supported
824
if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
825
return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
826
827
// Try to perform integral promotions if the object has a theoretically
828
// promotable type.
829
if (Ty->isIntegralOrUnscopedEnumerationType()) {
830
// C99 6.3.1.1p2:
831
//
832
// The following may be used in an expression wherever an int or
833
// unsigned int may be used:
834
// - an object or expression with an integer type whose integer
835
// conversion rank is less than or equal to the rank of int
836
// and unsigned int.
837
// - A bit-field of type _Bool, int, signed int, or unsigned int.
838
//
839
// If an int can represent all values of the original type, the
840
// value is converted to an int; otherwise, it is converted to an
841
// unsigned int. These are called the integer promotions. All
842
// other types are unchanged by the integer promotions.
843
844
QualType PTy = Context.isPromotableBitField(E);
845
if (!PTy.isNull()) {
846
E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
847
return E;
848
}
849
if (Context.isPromotableIntegerType(Ty)) {
850
QualType PT = Context.getPromotedIntegerType(Ty);
851
E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
852
return E;
853
}
854
}
855
return E;
856
}
857
858
/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
859
/// do not have a prototype. Arguments that have type float or __fp16
860
/// are promoted to double. All other argument types are converted by
861
/// UsualUnaryConversions().
862
ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
863
QualType Ty = E->getType();
864
assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
865
866
ExprResult Res = UsualUnaryConversions(E);
867
if (Res.isInvalid())
868
return ExprError();
869
E = Res.get();
870
871
// If this is a 'float' or '__fp16' (CVR qualified or typedef)
872
// promote to double.
873
// Note that default argument promotion applies only to float (and
874
// half/fp16); it does not apply to _Float16.
875
const BuiltinType *BTy = Ty->getAs<BuiltinType>();
876
if (BTy && (BTy->getKind() == BuiltinType::Half ||
877
BTy->getKind() == BuiltinType::Float)) {
878
if (getLangOpts().OpenCL &&
879
!getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
880
if (BTy->getKind() == BuiltinType::Half) {
881
E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
882
}
883
} else {
884
E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
885
}
886
}
887
if (BTy &&
888
getLangOpts().getExtendIntArgs() ==
889
LangOptions::ExtendArgsKind::ExtendTo64 &&
890
Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
891
Context.getTypeSizeInChars(BTy) <
892
Context.getTypeSizeInChars(Context.LongLongTy)) {
893
E = (Ty->isUnsignedIntegerType())
894
? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
895
.get()
896
: ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
897
assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
898
"Unexpected typesize for LongLongTy");
899
}
900
901
// C++ performs lvalue-to-rvalue conversion as a default argument
902
// promotion, even on class types, but note:
903
// C++11 [conv.lval]p2:
904
// When an lvalue-to-rvalue conversion occurs in an unevaluated
905
// operand or a subexpression thereof the value contained in the
906
// referenced object is not accessed. Otherwise, if the glvalue
907
// has a class type, the conversion copy-initializes a temporary
908
// of type T from the glvalue and the result of the conversion
909
// is a prvalue for the temporary.
910
// FIXME: add some way to gate this entire thing for correctness in
911
// potentially potentially evaluated contexts.
912
if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
913
ExprResult Temp = PerformCopyInitialization(
914
InitializedEntity::InitializeTemporary(E->getType()),
915
E->getExprLoc(), E);
916
if (Temp.isInvalid())
917
return ExprError();
918
E = Temp.get();
919
}
920
921
return E;
922
}
923
924
Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
925
if (Ty->isIncompleteType()) {
926
// C++11 [expr.call]p7:
927
// After these conversions, if the argument does not have arithmetic,
928
// enumeration, pointer, pointer to member, or class type, the program
929
// is ill-formed.
930
//
931
// Since we've already performed array-to-pointer and function-to-pointer
932
// decay, the only such type in C++ is cv void. This also handles
933
// initializer lists as variadic arguments.
934
if (Ty->isVoidType())
935
return VAK_Invalid;
936
937
if (Ty->isObjCObjectType())
938
return VAK_Invalid;
939
return VAK_Valid;
940
}
941
942
if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
943
return VAK_Invalid;
944
945
if (Context.getTargetInfo().getTriple().isWasm() &&
946
Ty.isWebAssemblyReferenceType()) {
947
return VAK_Invalid;
948
}
949
950
if (Ty.isCXX98PODType(Context))
951
return VAK_Valid;
952
953
// C++11 [expr.call]p7:
954
// Passing a potentially-evaluated argument of class type (Clause 9)
955
// having a non-trivial copy constructor, a non-trivial move constructor,
956
// or a non-trivial destructor, with no corresponding parameter,
957
// is conditionally-supported with implementation-defined semantics.
958
if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
959
if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
960
if (!Record->hasNonTrivialCopyConstructor() &&
961
!Record->hasNonTrivialMoveConstructor() &&
962
!Record->hasNonTrivialDestructor())
963
return VAK_ValidInCXX11;
964
965
if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
966
return VAK_Valid;
967
968
if (Ty->isObjCObjectType())
969
return VAK_Invalid;
970
971
if (getLangOpts().MSVCCompat)
972
return VAK_MSVCUndefined;
973
974
// FIXME: In C++11, these cases are conditionally-supported, meaning we're
975
// permitted to reject them. We should consider doing so.
976
return VAK_Undefined;
977
}
978
979
void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
980
// Don't allow one to pass an Objective-C interface to a vararg.
981
const QualType &Ty = E->getType();
982
VarArgKind VAK = isValidVarArgType(Ty);
983
984
// Complain about passing non-POD types through varargs.
985
switch (VAK) {
986
case VAK_ValidInCXX11:
987
DiagRuntimeBehavior(
988
E->getBeginLoc(), nullptr,
989
PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
990
[[fallthrough]];
991
case VAK_Valid:
992
if (Ty->isRecordType()) {
993
// This is unlikely to be what the user intended. If the class has a
994
// 'c_str' member function, the user probably meant to call that.
995
DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
996
PDiag(diag::warn_pass_class_arg_to_vararg)
997
<< Ty << CT << hasCStrMethod(E) << ".c_str()");
998
}
999
break;
1000
1001
case VAK_Undefined:
1002
case VAK_MSVCUndefined:
1003
DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004
PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1005
<< getLangOpts().CPlusPlus11 << Ty << CT);
1006
break;
1007
1008
case VAK_Invalid:
1009
if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1010
Diag(E->getBeginLoc(),
1011
diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1012
<< Ty << CT;
1013
else if (Ty->isObjCObjectType())
1014
DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1015
PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1016
<< Ty << CT);
1017
else
1018
Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1019
<< isa<InitListExpr>(E) << Ty << CT;
1020
break;
1021
}
1022
}
1023
1024
ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1025
FunctionDecl *FDecl) {
1026
if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1027
// Strip the unbridged-cast placeholder expression off, if applicable.
1028
if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1029
(CT == VariadicMethod ||
1030
(FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1031
E = ObjC().stripARCUnbridgedCast(E);
1032
1033
// Otherwise, do normal placeholder checking.
1034
} else {
1035
ExprResult ExprRes = CheckPlaceholderExpr(E);
1036
if (ExprRes.isInvalid())
1037
return ExprError();
1038
E = ExprRes.get();
1039
}
1040
}
1041
1042
ExprResult ExprRes = DefaultArgumentPromotion(E);
1043
if (ExprRes.isInvalid())
1044
return ExprError();
1045
1046
// Copy blocks to the heap.
1047
if (ExprRes.get()->getType()->isBlockPointerType())
1048
maybeExtendBlockObject(ExprRes);
1049
1050
E = ExprRes.get();
1051
1052
// Diagnostics regarding non-POD argument types are
1053
// emitted along with format string checking in Sema::CheckFunctionCall().
1054
if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1055
// Turn this into a trap.
1056
CXXScopeSpec SS;
1057
SourceLocation TemplateKWLoc;
1058
UnqualifiedId Name;
1059
Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1060
E->getBeginLoc());
1061
ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1062
/*HasTrailingLParen=*/true,
1063
/*IsAddressOfOperand=*/false);
1064
if (TrapFn.isInvalid())
1065
return ExprError();
1066
1067
ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1068
std::nullopt, E->getEndLoc());
1069
if (Call.isInvalid())
1070
return ExprError();
1071
1072
ExprResult Comma =
1073
ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1074
if (Comma.isInvalid())
1075
return ExprError();
1076
return Comma.get();
1077
}
1078
1079
if (!getLangOpts().CPlusPlus &&
1080
RequireCompleteType(E->getExprLoc(), E->getType(),
1081
diag::err_call_incomplete_argument))
1082
return ExprError();
1083
1084
return E;
1085
}
1086
1087
/// Convert complex integers to complex floats and real integers to
1088
/// real floats as required for complex arithmetic. Helper function of
1089
/// UsualArithmeticConversions()
1090
///
1091
/// \return false if the integer expression is an integer type and is
1092
/// successfully converted to the (complex) float type.
1093
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
1094
ExprResult &ComplexExpr,
1095
QualType IntTy,
1096
QualType ComplexTy,
1097
bool SkipCast) {
1098
if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1099
if (SkipCast) return false;
1100
if (IntTy->isIntegerType()) {
1101
QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1102
IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1103
} else {
1104
assert(IntTy->isComplexIntegerType());
1105
IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1106
CK_IntegralComplexToFloatingComplex);
1107
}
1108
return false;
1109
}
1110
1111
// This handles complex/complex, complex/float, or float/complex.
1112
// When both operands are complex, the shorter operand is converted to the
1113
// type of the longer, and that is the type of the result. This corresponds
1114
// to what is done when combining two real floating-point operands.
1115
// The fun begins when size promotion occur across type domains.
1116
// From H&S 6.3.4: When one operand is complex and the other is a real
1117
// floating-point type, the less precise type is converted, within it's
1118
// real or complex domain, to the precision of the other type. For example,
1119
// when combining a "long double" with a "double _Complex", the
1120
// "double _Complex" is promoted to "long double _Complex".
1121
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1122
QualType ShorterType,
1123
QualType LongerType,
1124
bool PromotePrecision) {
1125
bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1126
QualType Result =
1127
LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1128
1129
if (PromotePrecision) {
1130
if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1131
Shorter =
1132
S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1133
} else {
1134
if (LongerIsComplex)
1135
LongerType = LongerType->castAs<ComplexType>()->getElementType();
1136
Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1137
}
1138
}
1139
return Result;
1140
}
1141
1142
/// Handle arithmetic conversion with complex types. Helper function of
1143
/// UsualArithmeticConversions()
1144
static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1145
ExprResult &RHS, QualType LHSType,
1146
QualType RHSType, bool IsCompAssign) {
1147
// Handle (complex) integer types.
1148
if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1149
/*SkipCast=*/false))
1150
return LHSType;
1151
if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1152
/*SkipCast=*/IsCompAssign))
1153
return RHSType;
1154
1155
// Compute the rank of the two types, regardless of whether they are complex.
1156
int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1157
if (Order < 0)
1158
// Promote the precision of the LHS if not an assignment.
1159
return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1160
/*PromotePrecision=*/!IsCompAssign);
1161
// Promote the precision of the RHS unless it is already the same as the LHS.
1162
return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1163
/*PromotePrecision=*/Order > 0);
1164
}
1165
1166
/// Handle arithmetic conversion from integer to float. Helper function
1167
/// of UsualArithmeticConversions()
1168
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1169
ExprResult &IntExpr,
1170
QualType FloatTy, QualType IntTy,
1171
bool ConvertFloat, bool ConvertInt) {
1172
if (IntTy->isIntegerType()) {
1173
if (ConvertInt)
1174
// Convert intExpr to the lhs floating point type.
1175
IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1176
CK_IntegralToFloating);
1177
return FloatTy;
1178
}
1179
1180
// Convert both sides to the appropriate complex float.
1181
assert(IntTy->isComplexIntegerType());
1182
QualType result = S.Context.getComplexType(FloatTy);
1183
1184
// _Complex int -> _Complex float
1185
if (ConvertInt)
1186
IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1187
CK_IntegralComplexToFloatingComplex);
1188
1189
// float -> _Complex float
1190
if (ConvertFloat)
1191
FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1192
CK_FloatingRealToComplex);
1193
1194
return result;
1195
}
1196
1197
/// Handle arithmethic conversion with floating point types. Helper
1198
/// function of UsualArithmeticConversions()
1199
static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1200
ExprResult &RHS, QualType LHSType,
1201
QualType RHSType, bool IsCompAssign) {
1202
bool LHSFloat = LHSType->isRealFloatingType();
1203
bool RHSFloat = RHSType->isRealFloatingType();
1204
1205
// N1169 4.1.4: If one of the operands has a floating type and the other
1206
// operand has a fixed-point type, the fixed-point operand
1207
// is converted to the floating type [...]
1208
if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1209
if (LHSFloat)
1210
RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1211
else if (!IsCompAssign)
1212
LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1213
return LHSFloat ? LHSType : RHSType;
1214
}
1215
1216
// If we have two real floating types, convert the smaller operand
1217
// to the bigger result.
1218
if (LHSFloat && RHSFloat) {
1219
int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1220
if (order > 0) {
1221
RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1222
return LHSType;
1223
}
1224
1225
assert(order < 0 && "illegal float comparison");
1226
if (!IsCompAssign)
1227
LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1228
return RHSType;
1229
}
1230
1231
if (LHSFloat) {
1232
// Half FP has to be promoted to float unless it is natively supported
1233
if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1234
LHSType = S.Context.FloatTy;
1235
1236
return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1237
/*ConvertFloat=*/!IsCompAssign,
1238
/*ConvertInt=*/ true);
1239
}
1240
assert(RHSFloat);
1241
return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1242
/*ConvertFloat=*/ true,
1243
/*ConvertInt=*/!IsCompAssign);
1244
}
1245
1246
/// Diagnose attempts to convert between __float128, __ibm128 and
1247
/// long double if there is no support for such conversion.
1248
/// Helper function of UsualArithmeticConversions().
1249
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1250
QualType RHSType) {
1251
// No issue if either is not a floating point type.
1252
if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1253
return false;
1254
1255
// No issue if both have the same 128-bit float semantics.
1256
auto *LHSComplex = LHSType->getAs<ComplexType>();
1257
auto *RHSComplex = RHSType->getAs<ComplexType>();
1258
1259
QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1260
QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1261
1262
const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1263
const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1264
1265
if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1266
&RHSSem != &llvm::APFloat::IEEEquad()) &&
1267
(&LHSSem != &llvm::APFloat::IEEEquad() ||
1268
&RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1269
return false;
1270
1271
return true;
1272
}
1273
1274
typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1275
1276
namespace {
1277
/// These helper callbacks are placed in an anonymous namespace to
1278
/// permit their use as function template parameters.
1279
ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1280
return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1281
}
1282
1283
ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1284
return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1285
CK_IntegralComplexCast);
1286
}
1287
}
1288
1289
/// Handle integer arithmetic conversions. Helper function of
1290
/// UsualArithmeticConversions()
1291
template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1292
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1293
ExprResult &RHS, QualType LHSType,
1294
QualType RHSType, bool IsCompAssign) {
1295
// The rules for this case are in C99 6.3.1.8
1296
int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1297
bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1298
bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1299
if (LHSSigned == RHSSigned) {
1300
// Same signedness; use the higher-ranked type
1301
if (order >= 0) {
1302
RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1303
return LHSType;
1304
} else if (!IsCompAssign)
1305
LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1306
return RHSType;
1307
} else if (order != (LHSSigned ? 1 : -1)) {
1308
// The unsigned type has greater than or equal rank to the
1309
// signed type, so use the unsigned type
1310
if (RHSSigned) {
1311
RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1312
return LHSType;
1313
} else if (!IsCompAssign)
1314
LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1315
return RHSType;
1316
} else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1317
// The two types are different widths; if we are here, that
1318
// means the signed type is larger than the unsigned type, so
1319
// use the signed type.
1320
if (LHSSigned) {
1321
RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1322
return LHSType;
1323
} else if (!IsCompAssign)
1324
LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1325
return RHSType;
1326
} else {
1327
// The signed type is higher-ranked than the unsigned type,
1328
// but isn't actually any bigger (like unsigned int and long
1329
// on most 32-bit systems). Use the unsigned type corresponding
1330
// to the signed type.
1331
QualType result =
1332
S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1333
RHS = (*doRHSCast)(S, RHS.get(), result);
1334
if (!IsCompAssign)
1335
LHS = (*doLHSCast)(S, LHS.get(), result);
1336
return result;
1337
}
1338
}
1339
1340
/// Handle conversions with GCC complex int extension. Helper function
1341
/// of UsualArithmeticConversions()
1342
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1343
ExprResult &RHS, QualType LHSType,
1344
QualType RHSType,
1345
bool IsCompAssign) {
1346
const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1347
const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1348
1349
if (LHSComplexInt && RHSComplexInt) {
1350
QualType LHSEltType = LHSComplexInt->getElementType();
1351
QualType RHSEltType = RHSComplexInt->getElementType();
1352
QualType ScalarType =
1353
handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1354
(S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1355
1356
return S.Context.getComplexType(ScalarType);
1357
}
1358
1359
if (LHSComplexInt) {
1360
QualType LHSEltType = LHSComplexInt->getElementType();
1361
QualType ScalarType =
1362
handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1363
(S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1364
QualType ComplexType = S.Context.getComplexType(ScalarType);
1365
RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1366
CK_IntegralRealToComplex);
1367
1368
return ComplexType;
1369
}
1370
1371
assert(RHSComplexInt);
1372
1373
QualType RHSEltType = RHSComplexInt->getElementType();
1374
QualType ScalarType =
1375
handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1376
(S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1377
QualType ComplexType = S.Context.getComplexType(ScalarType);
1378
1379
if (!IsCompAssign)
1380
LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1381
CK_IntegralRealToComplex);
1382
return ComplexType;
1383
}
1384
1385
/// Return the rank of a given fixed point or integer type. The value itself
1386
/// doesn't matter, but the values must be increasing with proper increasing
1387
/// rank as described in N1169 4.1.1.
1388
static unsigned GetFixedPointRank(QualType Ty) {
1389
const auto *BTy = Ty->getAs<BuiltinType>();
1390
assert(BTy && "Expected a builtin type.");
1391
1392
switch (BTy->getKind()) {
1393
case BuiltinType::ShortFract:
1394
case BuiltinType::UShortFract:
1395
case BuiltinType::SatShortFract:
1396
case BuiltinType::SatUShortFract:
1397
return 1;
1398
case BuiltinType::Fract:
1399
case BuiltinType::UFract:
1400
case BuiltinType::SatFract:
1401
case BuiltinType::SatUFract:
1402
return 2;
1403
case BuiltinType::LongFract:
1404
case BuiltinType::ULongFract:
1405
case BuiltinType::SatLongFract:
1406
case BuiltinType::SatULongFract:
1407
return 3;
1408
case BuiltinType::ShortAccum:
1409
case BuiltinType::UShortAccum:
1410
case BuiltinType::SatShortAccum:
1411
case BuiltinType::SatUShortAccum:
1412
return 4;
1413
case BuiltinType::Accum:
1414
case BuiltinType::UAccum:
1415
case BuiltinType::SatAccum:
1416
case BuiltinType::SatUAccum:
1417
return 5;
1418
case BuiltinType::LongAccum:
1419
case BuiltinType::ULongAccum:
1420
case BuiltinType::SatLongAccum:
1421
case BuiltinType::SatULongAccum:
1422
return 6;
1423
default:
1424
if (BTy->isInteger())
1425
return 0;
1426
llvm_unreachable("Unexpected fixed point or integer type");
1427
}
1428
}
1429
1430
/// handleFixedPointConversion - Fixed point operations between fixed
1431
/// point types and integers or other fixed point types do not fall under
1432
/// usual arithmetic conversion since these conversions could result in loss
1433
/// of precsision (N1169 4.1.4). These operations should be calculated with
1434
/// the full precision of their result type (N1169 4.1.6.2.1).
1435
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1436
QualType RHSTy) {
1437
assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1438
"Expected at least one of the operands to be a fixed point type");
1439
assert((LHSTy->isFixedPointOrIntegerType() ||
1440
RHSTy->isFixedPointOrIntegerType()) &&
1441
"Special fixed point arithmetic operation conversions are only "
1442
"applied to ints or other fixed point types");
1443
1444
// If one operand has signed fixed-point type and the other operand has
1445
// unsigned fixed-point type, then the unsigned fixed-point operand is
1446
// converted to its corresponding signed fixed-point type and the resulting
1447
// type is the type of the converted operand.
1448
if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1449
LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1450
else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1451
RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1452
1453
// The result type is the type with the highest rank, whereby a fixed-point
1454
// conversion rank is always greater than an integer conversion rank; if the
1455
// type of either of the operands is a saturating fixedpoint type, the result
1456
// type shall be the saturating fixed-point type corresponding to the type
1457
// with the highest rank; the resulting value is converted (taking into
1458
// account rounding and overflow) to the precision of the resulting type.
1459
// Same ranks between signed and unsigned types are resolved earlier, so both
1460
// types are either signed or both unsigned at this point.
1461
unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1462
unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1463
1464
QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1465
1466
if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1467
ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1468
1469
return ResultTy;
1470
}
1471
1472
/// Check that the usual arithmetic conversions can be performed on this pair of
1473
/// expressions that might be of enumeration type.
1474
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1475
SourceLocation Loc,
1476
Sema::ArithConvKind ACK) {
1477
// C++2a [expr.arith.conv]p1:
1478
// If one operand is of enumeration type and the other operand is of a
1479
// different enumeration type or a floating-point type, this behavior is
1480
// deprecated ([depr.arith.conv.enum]).
1481
//
1482
// Warn on this in all language modes. Produce a deprecation warning in C++20.
1483
// Eventually we will presumably reject these cases (in C++23 onwards?).
1484
QualType L = LHS->getEnumCoercedType(S.Context),
1485
R = RHS->getEnumCoercedType(S.Context);
1486
bool LEnum = L->isUnscopedEnumerationType(),
1487
REnum = R->isUnscopedEnumerationType();
1488
bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1489
if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1490
(REnum && L->isFloatingType())) {
1491
S.Diag(Loc, S.getLangOpts().CPlusPlus26
1492
? diag::err_arith_conv_enum_float_cxx26
1493
: S.getLangOpts().CPlusPlus20
1494
? diag::warn_arith_conv_enum_float_cxx20
1495
: diag::warn_arith_conv_enum_float)
1496
<< LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1497
<< L << R;
1498
} else if (!IsCompAssign && LEnum && REnum &&
1499
!S.Context.hasSameUnqualifiedType(L, R)) {
1500
unsigned DiagID;
1501
// In C++ 26, usual arithmetic conversions between 2 different enum types
1502
// are ill-formed.
1503
if (S.getLangOpts().CPlusPlus26)
1504
DiagID = diag::err_conv_mixed_enum_types_cxx26;
1505
else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1506
!R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1507
// If either enumeration type is unnamed, it's less likely that the
1508
// user cares about this, but this situation is still deprecated in
1509
// C++2a. Use a different warning group.
1510
DiagID = S.getLangOpts().CPlusPlus20
1511
? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1512
: diag::warn_arith_conv_mixed_anon_enum_types;
1513
} else if (ACK == Sema::ACK_Conditional) {
1514
// Conditional expressions are separated out because they have
1515
// historically had a different warning flag.
1516
DiagID = S.getLangOpts().CPlusPlus20
1517
? diag::warn_conditional_mixed_enum_types_cxx20
1518
: diag::warn_conditional_mixed_enum_types;
1519
} else if (ACK == Sema::ACK_Comparison) {
1520
// Comparison expressions are separated out because they have
1521
// historically had a different warning flag.
1522
DiagID = S.getLangOpts().CPlusPlus20
1523
? diag::warn_comparison_mixed_enum_types_cxx20
1524
: diag::warn_comparison_mixed_enum_types;
1525
} else {
1526
DiagID = S.getLangOpts().CPlusPlus20
1527
? diag::warn_arith_conv_mixed_enum_types_cxx20
1528
: diag::warn_arith_conv_mixed_enum_types;
1529
}
1530
S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1531
<< (int)ACK << L << R;
1532
}
1533
}
1534
1535
/// UsualArithmeticConversions - Performs various conversions that are common to
1536
/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1537
/// routine returns the first non-arithmetic type found. The client is
1538
/// responsible for emitting appropriate error diagnostics.
1539
QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1540
SourceLocation Loc,
1541
ArithConvKind ACK) {
1542
checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1543
1544
if (ACK != ACK_CompAssign) {
1545
LHS = UsualUnaryConversions(LHS.get());
1546
if (LHS.isInvalid())
1547
return QualType();
1548
}
1549
1550
RHS = UsualUnaryConversions(RHS.get());
1551
if (RHS.isInvalid())
1552
return QualType();
1553
1554
// For conversion purposes, we ignore any qualifiers.
1555
// For example, "const float" and "float" are equivalent.
1556
QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1557
QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1558
1559
// For conversion purposes, we ignore any atomic qualifier on the LHS.
1560
if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1561
LHSType = AtomicLHS->getValueType();
1562
1563
// If both types are identical, no conversion is needed.
1564
if (Context.hasSameType(LHSType, RHSType))
1565
return Context.getCommonSugaredType(LHSType, RHSType);
1566
1567
// If either side is a non-arithmetic type (e.g. a pointer), we are done.
1568
// The caller can deal with this (e.g. pointer + int).
1569
if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1570
return QualType();
1571
1572
// Apply unary and bitfield promotions to the LHS's type.
1573
QualType LHSUnpromotedType = LHSType;
1574
if (Context.isPromotableIntegerType(LHSType))
1575
LHSType = Context.getPromotedIntegerType(LHSType);
1576
QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1577
if (!LHSBitfieldPromoteTy.isNull())
1578
LHSType = LHSBitfieldPromoteTy;
1579
if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1580
LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1581
1582
// If both types are identical, no conversion is needed.
1583
if (Context.hasSameType(LHSType, RHSType))
1584
return Context.getCommonSugaredType(LHSType, RHSType);
1585
1586
// At this point, we have two different arithmetic types.
1587
1588
// Diagnose attempts to convert between __ibm128, __float128 and long double
1589
// where such conversions currently can't be handled.
1590
if (unsupportedTypeConversion(*this, LHSType, RHSType))
1591
return QualType();
1592
1593
// Handle complex types first (C99 6.3.1.8p1).
1594
if (LHSType->isComplexType() || RHSType->isComplexType())
1595
return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1596
ACK == ACK_CompAssign);
1597
1598
// Now handle "real" floating types (i.e. float, double, long double).
1599
if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1600
return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1601
ACK == ACK_CompAssign);
1602
1603
// Handle GCC complex int extension.
1604
if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1605
return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1606
ACK == ACK_CompAssign);
1607
1608
if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1609
return handleFixedPointConversion(*this, LHSType, RHSType);
1610
1611
// Finally, we have two differing integer types.
1612
return handleIntegerConversion<doIntegralCast, doIntegralCast>
1613
(*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1614
}
1615
1616
//===----------------------------------------------------------------------===//
1617
// Semantic Analysis for various Expression Types
1618
//===----------------------------------------------------------------------===//
1619
1620
1621
ExprResult Sema::ActOnGenericSelectionExpr(
1622
SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1623
bool PredicateIsExpr, void *ControllingExprOrType,
1624
ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1625
unsigned NumAssocs = ArgTypes.size();
1626
assert(NumAssocs == ArgExprs.size());
1627
1628
TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1629
for (unsigned i = 0; i < NumAssocs; ++i) {
1630
if (ArgTypes[i])
1631
(void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1632
else
1633
Types[i] = nullptr;
1634
}
1635
1636
// If we have a controlling type, we need to convert it from a parsed type
1637
// into a semantic type and then pass that along.
1638
if (!PredicateIsExpr) {
1639
TypeSourceInfo *ControllingType;
1640
(void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1641
&ControllingType);
1642
assert(ControllingType && "couldn't get the type out of the parser");
1643
ControllingExprOrType = ControllingType;
1644
}
1645
1646
ExprResult ER = CreateGenericSelectionExpr(
1647
KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1648
llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1649
delete [] Types;
1650
return ER;
1651
}
1652
1653
ExprResult Sema::CreateGenericSelectionExpr(
1654
SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1655
bool PredicateIsExpr, void *ControllingExprOrType,
1656
ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1657
unsigned NumAssocs = Types.size();
1658
assert(NumAssocs == Exprs.size());
1659
assert(ControllingExprOrType &&
1660
"Must have either a controlling expression or a controlling type");
1661
1662
Expr *ControllingExpr = nullptr;
1663
TypeSourceInfo *ControllingType = nullptr;
1664
if (PredicateIsExpr) {
1665
// Decay and strip qualifiers for the controlling expression type, and
1666
// handle placeholder type replacement. See committee discussion from WG14
1667
// DR423.
1668
EnterExpressionEvaluationContext Unevaluated(
1669
*this, Sema::ExpressionEvaluationContext::Unevaluated);
1670
ExprResult R = DefaultFunctionArrayLvalueConversion(
1671
reinterpret_cast<Expr *>(ControllingExprOrType));
1672
if (R.isInvalid())
1673
return ExprError();
1674
ControllingExpr = R.get();
1675
} else {
1676
// The extension form uses the type directly rather than converting it.
1677
ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1678
if (!ControllingType)
1679
return ExprError();
1680
}
1681
1682
bool TypeErrorFound = false,
1683
IsResultDependent = ControllingExpr
1684
? ControllingExpr->isTypeDependent()
1685
: ControllingType->getType()->isDependentType(),
1686
ContainsUnexpandedParameterPack =
1687
ControllingExpr
1688
? ControllingExpr->containsUnexpandedParameterPack()
1689
: ControllingType->getType()->containsUnexpandedParameterPack();
1690
1691
// The controlling expression is an unevaluated operand, so side effects are
1692
// likely unintended.
1693
if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1694
ControllingExpr->HasSideEffects(Context, false))
1695
Diag(ControllingExpr->getExprLoc(),
1696
diag::warn_side_effects_unevaluated_context);
1697
1698
for (unsigned i = 0; i < NumAssocs; ++i) {
1699
if (Exprs[i]->containsUnexpandedParameterPack())
1700
ContainsUnexpandedParameterPack = true;
1701
1702
if (Types[i]) {
1703
if (Types[i]->getType()->containsUnexpandedParameterPack())
1704
ContainsUnexpandedParameterPack = true;
1705
1706
if (Types[i]->getType()->isDependentType()) {
1707
IsResultDependent = true;
1708
} else {
1709
// We relax the restriction on use of incomplete types and non-object
1710
// types with the type-based extension of _Generic. Allowing incomplete
1711
// objects means those can be used as "tags" for a type-safe way to map
1712
// to a value. Similarly, matching on function types rather than
1713
// function pointer types can be useful. However, the restriction on VM
1714
// types makes sense to retain as there are open questions about how
1715
// the selection can be made at compile time.
1716
//
1717
// C11 6.5.1.1p2 "The type name in a generic association shall specify a
1718
// complete object type other than a variably modified type."
1719
unsigned D = 0;
1720
if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1721
D = diag::err_assoc_type_incomplete;
1722
else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1723
D = diag::err_assoc_type_nonobject;
1724
else if (Types[i]->getType()->isVariablyModifiedType())
1725
D = diag::err_assoc_type_variably_modified;
1726
else if (ControllingExpr) {
1727
// Because the controlling expression undergoes lvalue conversion,
1728
// array conversion, and function conversion, an association which is
1729
// of array type, function type, or is qualified can never be
1730
// reached. We will warn about this so users are less surprised by
1731
// the unreachable association. However, we don't have to handle
1732
// function types; that's not an object type, so it's handled above.
1733
//
1734
// The logic is somewhat different for C++ because C++ has different
1735
// lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1736
// If T is a non-class type, the type of the prvalue is the cv-
1737
// unqualified version of T. Otherwise, the type of the prvalue is T.
1738
// The result of these rules is that all qualified types in an
1739
// association in C are unreachable, and in C++, only qualified non-
1740
// class types are unreachable.
1741
//
1742
// NB: this does not apply when the first operand is a type rather
1743
// than an expression, because the type form does not undergo
1744
// conversion.
1745
unsigned Reason = 0;
1746
QualType QT = Types[i]->getType();
1747
if (QT->isArrayType())
1748
Reason = 1;
1749
else if (QT.hasQualifiers() &&
1750
(!LangOpts.CPlusPlus || !QT->isRecordType()))
1751
Reason = 2;
1752
1753
if (Reason)
1754
Diag(Types[i]->getTypeLoc().getBeginLoc(),
1755
diag::warn_unreachable_association)
1756
<< QT << (Reason - 1);
1757
}
1758
1759
if (D != 0) {
1760
Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1761
<< Types[i]->getTypeLoc().getSourceRange()
1762
<< Types[i]->getType();
1763
TypeErrorFound = true;
1764
}
1765
1766
// C11 6.5.1.1p2 "No two generic associations in the same generic
1767
// selection shall specify compatible types."
1768
for (unsigned j = i+1; j < NumAssocs; ++j)
1769
if (Types[j] && !Types[j]->getType()->isDependentType() &&
1770
Context.typesAreCompatible(Types[i]->getType(),
1771
Types[j]->getType())) {
1772
Diag(Types[j]->getTypeLoc().getBeginLoc(),
1773
diag::err_assoc_compatible_types)
1774
<< Types[j]->getTypeLoc().getSourceRange()
1775
<< Types[j]->getType()
1776
<< Types[i]->getType();
1777
Diag(Types[i]->getTypeLoc().getBeginLoc(),
1778
diag::note_compat_assoc)
1779
<< Types[i]->getTypeLoc().getSourceRange()
1780
<< Types[i]->getType();
1781
TypeErrorFound = true;
1782
}
1783
}
1784
}
1785
}
1786
if (TypeErrorFound)
1787
return ExprError();
1788
1789
// If we determined that the generic selection is result-dependent, don't
1790
// try to compute the result expression.
1791
if (IsResultDependent) {
1792
if (ControllingExpr)
1793
return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1794
Types, Exprs, DefaultLoc, RParenLoc,
1795
ContainsUnexpandedParameterPack);
1796
return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1797
Exprs, DefaultLoc, RParenLoc,
1798
ContainsUnexpandedParameterPack);
1799
}
1800
1801
SmallVector<unsigned, 1> CompatIndices;
1802
unsigned DefaultIndex = -1U;
1803
// Look at the canonical type of the controlling expression in case it was a
1804
// deduced type like __auto_type. However, when issuing diagnostics, use the
1805
// type the user wrote in source rather than the canonical one.
1806
for (unsigned i = 0; i < NumAssocs; ++i) {
1807
if (!Types[i])
1808
DefaultIndex = i;
1809
else if (ControllingExpr &&
1810
Context.typesAreCompatible(
1811
ControllingExpr->getType().getCanonicalType(),
1812
Types[i]->getType()))
1813
CompatIndices.push_back(i);
1814
else if (ControllingType &&
1815
Context.typesAreCompatible(
1816
ControllingType->getType().getCanonicalType(),
1817
Types[i]->getType()))
1818
CompatIndices.push_back(i);
1819
}
1820
1821
auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1822
TypeSourceInfo *ControllingType) {
1823
// We strip parens here because the controlling expression is typically
1824
// parenthesized in macro definitions.
1825
if (ControllingExpr)
1826
ControllingExpr = ControllingExpr->IgnoreParens();
1827
1828
SourceRange SR = ControllingExpr
1829
? ControllingExpr->getSourceRange()
1830
: ControllingType->getTypeLoc().getSourceRange();
1831
QualType QT = ControllingExpr ? ControllingExpr->getType()
1832
: ControllingType->getType();
1833
1834
return std::make_pair(SR, QT);
1835
};
1836
1837
// C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1838
// type compatible with at most one of the types named in its generic
1839
// association list."
1840
if (CompatIndices.size() > 1) {
1841
auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1842
SourceRange SR = P.first;
1843
Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1844
<< SR << P.second << (unsigned)CompatIndices.size();
1845
for (unsigned I : CompatIndices) {
1846
Diag(Types[I]->getTypeLoc().getBeginLoc(),
1847
diag::note_compat_assoc)
1848
<< Types[I]->getTypeLoc().getSourceRange()
1849
<< Types[I]->getType();
1850
}
1851
return ExprError();
1852
}
1853
1854
// C11 6.5.1.1p2 "If a generic selection has no default generic association,
1855
// its controlling expression shall have type compatible with exactly one of
1856
// the types named in its generic association list."
1857
if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1858
auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1859
SourceRange SR = P.first;
1860
Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1861
return ExprError();
1862
}
1863
1864
// C11 6.5.1.1p3 "If a generic selection has a generic association with a
1865
// type name that is compatible with the type of the controlling expression,
1866
// then the result expression of the generic selection is the expression
1867
// in that generic association. Otherwise, the result expression of the
1868
// generic selection is the expression in the default generic association."
1869
unsigned ResultIndex =
1870
CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1871
1872
if (ControllingExpr) {
1873
return GenericSelectionExpr::Create(
1874
Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1875
ContainsUnexpandedParameterPack, ResultIndex);
1876
}
1877
return GenericSelectionExpr::Create(
1878
Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1879
ContainsUnexpandedParameterPack, ResultIndex);
1880
}
1881
1882
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
1883
switch (Kind) {
1884
default:
1885
llvm_unreachable("unexpected TokenKind");
1886
case tok::kw___func__:
1887
return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1888
case tok::kw___FUNCTION__:
1889
return PredefinedIdentKind::Function;
1890
case tok::kw___FUNCDNAME__:
1891
return PredefinedIdentKind::FuncDName; // [MS]
1892
case tok::kw___FUNCSIG__:
1893
return PredefinedIdentKind::FuncSig; // [MS]
1894
case tok::kw_L__FUNCTION__:
1895
return PredefinedIdentKind::LFunction; // [MS]
1896
case tok::kw_L__FUNCSIG__:
1897
return PredefinedIdentKind::LFuncSig; // [MS]
1898
case tok::kw___PRETTY_FUNCTION__:
1899
return PredefinedIdentKind::PrettyFunction; // [GNU]
1900
}
1901
}
1902
1903
/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1904
/// to determine the value of a PredefinedExpr. This can be either a
1905
/// block, lambda, captured statement, function, otherwise a nullptr.
1906
static Decl *getPredefinedExprDecl(DeclContext *DC) {
1907
while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1908
DC = DC->getParent();
1909
return cast_or_null<Decl>(DC);
1910
}
1911
1912
/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1913
/// location of the token and the offset of the ud-suffix within it.
1914
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1915
unsigned Offset) {
1916
return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1917
S.getLangOpts());
1918
}
1919
1920
/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1921
/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1922
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1923
IdentifierInfo *UDSuffix,
1924
SourceLocation UDSuffixLoc,
1925
ArrayRef<Expr*> Args,
1926
SourceLocation LitEndLoc) {
1927
assert(Args.size() <= 2 && "too many arguments for literal operator");
1928
1929
QualType ArgTy[2];
1930
for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1931
ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1932
if (ArgTy[ArgIdx]->isArrayType())
1933
ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1934
}
1935
1936
DeclarationName OpName =
1937
S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1938
DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1939
OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1940
1941
LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1942
if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1943
/*AllowRaw*/ false, /*AllowTemplate*/ false,
1944
/*AllowStringTemplatePack*/ false,
1945
/*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1946
return ExprError();
1947
1948
return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1949
}
1950
1951
ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
1952
// StringToks needs backing storage as it doesn't hold array elements itself
1953
std::vector<Token> ExpandedToks;
1954
if (getLangOpts().MicrosoftExt)
1955
StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1956
1957
StringLiteralParser Literal(StringToks, PP,
1958
StringLiteralEvalMethod::Unevaluated);
1959
if (Literal.hadError)
1960
return ExprError();
1961
1962
SmallVector<SourceLocation, 4> StringTokLocs;
1963
for (const Token &Tok : StringToks)
1964
StringTokLocs.push_back(Tok.getLocation());
1965
1966
StringLiteral *Lit = StringLiteral::Create(
1967
Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1968
&StringTokLocs[0], StringTokLocs.size());
1969
1970
if (!Literal.getUDSuffix().empty()) {
1971
SourceLocation UDSuffixLoc =
1972
getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1973
Literal.getUDSuffixOffset());
1974
return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1975
}
1976
1977
return Lit;
1978
}
1979
1980
std::vector<Token>
1981
Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
1982
// MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
1983
// local macros that expand to string literals that may be concatenated.
1984
// These macros are expanded here (in Sema), because StringLiteralParser
1985
// (in Lex) doesn't know the enclosing function (because it hasn't been
1986
// parsed yet).
1987
assert(getLangOpts().MicrosoftExt);
1988
1989
// Note: Although function local macros are defined only inside functions,
1990
// we ensure a valid `CurrentDecl` even outside of a function. This allows
1991
// expansion of macros into empty string literals without additional checks.
1992
Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
1993
if (!CurrentDecl)
1994
CurrentDecl = Context.getTranslationUnitDecl();
1995
1996
std::vector<Token> ExpandedToks;
1997
ExpandedToks.reserve(Toks.size());
1998
for (const Token &Tok : Toks) {
1999
if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2000
assert(tok::isStringLiteral(Tok.getKind()));
2001
ExpandedToks.emplace_back(Tok);
2002
continue;
2003
}
2004
if (isa<TranslationUnitDecl>(CurrentDecl))
2005
Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2006
// Stringify predefined expression
2007
Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2008
<< Tok.getKind();
2009
SmallString<64> Str;
2010
llvm::raw_svector_ostream OS(Str);
2011
Token &Exp = ExpandedToks.emplace_back();
2012
Exp.startToken();
2013
if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2014
Tok.getKind() == tok::kw_L__FUNCSIG__) {
2015
OS << 'L';
2016
Exp.setKind(tok::wide_string_literal);
2017
} else {
2018
Exp.setKind(tok::string_literal);
2019
}
2020
OS << '"'
2021
<< Lexer::Stringify(PredefinedExpr::ComputeName(
2022
getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2023
<< '"';
2024
PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2025
}
2026
return ExpandedToks;
2027
}
2028
2029
ExprResult
2030
Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2031
assert(!StringToks.empty() && "Must have at least one string!");
2032
2033
// StringToks needs backing storage as it doesn't hold array elements itself
2034
std::vector<Token> ExpandedToks;
2035
if (getLangOpts().MicrosoftExt)
2036
StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2037
2038
StringLiteralParser Literal(StringToks, PP);
2039
if (Literal.hadError)
2040
return ExprError();
2041
2042
SmallVector<SourceLocation, 4> StringTokLocs;
2043
for (const Token &Tok : StringToks)
2044
StringTokLocs.push_back(Tok.getLocation());
2045
2046
QualType CharTy = Context.CharTy;
2047
StringLiteralKind Kind = StringLiteralKind::Ordinary;
2048
if (Literal.isWide()) {
2049
CharTy = Context.getWideCharType();
2050
Kind = StringLiteralKind::Wide;
2051
} else if (Literal.isUTF8()) {
2052
if (getLangOpts().Char8)
2053
CharTy = Context.Char8Ty;
2054
else if (getLangOpts().C23)
2055
CharTy = Context.UnsignedCharTy;
2056
Kind = StringLiteralKind::UTF8;
2057
} else if (Literal.isUTF16()) {
2058
CharTy = Context.Char16Ty;
2059
Kind = StringLiteralKind::UTF16;
2060
} else if (Literal.isUTF32()) {
2061
CharTy = Context.Char32Ty;
2062
Kind = StringLiteralKind::UTF32;
2063
} else if (Literal.isPascal()) {
2064
CharTy = Context.UnsignedCharTy;
2065
}
2066
2067
// Warn on u8 string literals before C++20 and C23, whose type
2068
// was an array of char before but becomes an array of char8_t.
2069
// In C++20, it cannot be used where a pointer to char is expected.
2070
// In C23, it might have an unexpected value if char was signed.
2071
if (Kind == StringLiteralKind::UTF8 &&
2072
(getLangOpts().CPlusPlus
2073
? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2074
: !getLangOpts().C23)) {
2075
Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2076
? diag::warn_cxx20_compat_utf8_string
2077
: diag::warn_c23_compat_utf8_string);
2078
2079
// Create removals for all 'u8' prefixes in the string literal(s). This
2080
// ensures C++20/C23 compatibility (but may change the program behavior when
2081
// built by non-Clang compilers for which the execution character set is
2082
// not always UTF-8).
2083
auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2084
SourceLocation RemovalDiagLoc;
2085
for (const Token &Tok : StringToks) {
2086
if (Tok.getKind() == tok::utf8_string_literal) {
2087
if (RemovalDiagLoc.isInvalid())
2088
RemovalDiagLoc = Tok.getLocation();
2089
RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
2090
Tok.getLocation(),
2091
Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2092
getSourceManager(), getLangOpts())));
2093
}
2094
}
2095
Diag(RemovalDiagLoc, RemovalDiag);
2096
}
2097
2098
QualType StrTy =
2099
Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2100
2101
// Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2102
StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2103
Kind, Literal.Pascal, StrTy,
2104
&StringTokLocs[0],
2105
StringTokLocs.size());
2106
if (Literal.getUDSuffix().empty())
2107
return Lit;
2108
2109
// We're building a user-defined literal.
2110
IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2111
SourceLocation UDSuffixLoc =
2112
getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2113
Literal.getUDSuffixOffset());
2114
2115
// Make sure we're allowed user-defined literals here.
2116
if (!UDLScope)
2117
return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2118
2119
// C++11 [lex.ext]p5: The literal L is treated as a call of the form
2120
// operator "" X (str, len)
2121
QualType SizeType = Context.getSizeType();
2122
2123
DeclarationName OpName =
2124
Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2125
DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2126
OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2127
2128
QualType ArgTy[] = {
2129
Context.getArrayDecayedType(StrTy), SizeType
2130
};
2131
2132
LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2133
switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2134
/*AllowRaw*/ false, /*AllowTemplate*/ true,
2135
/*AllowStringTemplatePack*/ true,
2136
/*DiagnoseMissing*/ true, Lit)) {
2137
2138
case LOLR_Cooked: {
2139
llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2140
IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2141
StringTokLocs[0]);
2142
Expr *Args[] = { Lit, LenArg };
2143
2144
return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2145
}
2146
2147
case LOLR_Template: {
2148
TemplateArgumentListInfo ExplicitArgs;
2149
TemplateArgument Arg(Lit);
2150
TemplateArgumentLocInfo ArgInfo(Lit);
2151
ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2152
return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2153
StringTokLocs.back(), &ExplicitArgs);
2154
}
2155
2156
case LOLR_StringTemplatePack: {
2157
TemplateArgumentListInfo ExplicitArgs;
2158
2159
unsigned CharBits = Context.getIntWidth(CharTy);
2160
bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2161
llvm::APSInt Value(CharBits, CharIsUnsigned);
2162
2163
TemplateArgument TypeArg(CharTy);
2164
TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2165
ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2166
2167
for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2168
Value = Lit->getCodeUnit(I);
2169
TemplateArgument Arg(Context, Value, CharTy);
2170
TemplateArgumentLocInfo ArgInfo;
2171
ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2172
}
2173
return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2174
StringTokLocs.back(), &ExplicitArgs);
2175
}
2176
case LOLR_Raw:
2177
case LOLR_ErrorNoDiagnostic:
2178
llvm_unreachable("unexpected literal operator lookup result");
2179
case LOLR_Error:
2180
return ExprError();
2181
}
2182
llvm_unreachable("unexpected literal operator lookup result");
2183
}
2184
2185
DeclRefExpr *
2186
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2187
SourceLocation Loc,
2188
const CXXScopeSpec *SS) {
2189
DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2190
return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2191
}
2192
2193
DeclRefExpr *
2194
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2195
const DeclarationNameInfo &NameInfo,
2196
const CXXScopeSpec *SS, NamedDecl *FoundD,
2197
SourceLocation TemplateKWLoc,
2198
const TemplateArgumentListInfo *TemplateArgs) {
2199
NestedNameSpecifierLoc NNS =
2200
SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2201
return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2202
TemplateArgs);
2203
}
2204
2205
// CUDA/HIP: Check whether a captured reference variable is referencing a
2206
// host variable in a device or host device lambda.
2207
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2208
VarDecl *VD) {
2209
if (!S.getLangOpts().CUDA || !VD->hasInit())
2210
return false;
2211
assert(VD->getType()->isReferenceType());
2212
2213
// Check whether the reference variable is referencing a host variable.
2214
auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2215
if (!DRE)
2216
return false;
2217
auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2218
if (!Referee || !Referee->hasGlobalStorage() ||
2219
Referee->hasAttr<CUDADeviceAttr>())
2220
return false;
2221
2222
// Check whether the current function is a device or host device lambda.
2223
// Check whether the reference variable is a capture by getDeclContext()
2224
// since refersToEnclosingVariableOrCapture() is not ready at this point.
2225
auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2226
if (MD && MD->getParent()->isLambda() &&
2227
MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2228
VD->getDeclContext() != MD)
2229
return true;
2230
2231
return false;
2232
}
2233
2234
NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2235
// A declaration named in an unevaluated operand never constitutes an odr-use.
2236
if (isUnevaluatedContext())
2237
return NOUR_Unevaluated;
2238
2239
// C++2a [basic.def.odr]p4:
2240
// A variable x whose name appears as a potentially-evaluated expression e
2241
// is odr-used by e unless [...] x is a reference that is usable in
2242
// constant expressions.
2243
// CUDA/HIP:
2244
// If a reference variable referencing a host variable is captured in a
2245
// device or host device lambda, the value of the referee must be copied
2246
// to the capture and the reference variable must be treated as odr-use
2247
// since the value of the referee is not known at compile time and must
2248
// be loaded from the captured.
2249
if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2250
if (VD->getType()->isReferenceType() &&
2251
!(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2252
!isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2253
VD->isUsableInConstantExpressions(Context))
2254
return NOUR_Constant;
2255
}
2256
2257
// All remaining non-variable cases constitute an odr-use. For variables, we
2258
// need to wait and see how the expression is used.
2259
return NOUR_None;
2260
}
2261
2262
DeclRefExpr *
2263
Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2264
const DeclarationNameInfo &NameInfo,
2265
NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2266
SourceLocation TemplateKWLoc,
2267
const TemplateArgumentListInfo *TemplateArgs) {
2268
bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2269
NeedToCaptureVariable(D, NameInfo.getLoc());
2270
2271
DeclRefExpr *E = DeclRefExpr::Create(
2272
Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2273
VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2274
MarkDeclRefReferenced(E);
2275
2276
// C++ [except.spec]p17:
2277
// An exception-specification is considered to be needed when:
2278
// - in an expression, the function is the unique lookup result or
2279
// the selected member of a set of overloaded functions.
2280
//
2281
// We delay doing this until after we've built the function reference and
2282
// marked it as used so that:
2283
// a) if the function is defaulted, we get errors from defining it before /
2284
// instead of errors from computing its exception specification, and
2285
// b) if the function is a defaulted comparison, we can use the body we
2286
// build when defining it as input to the exception specification
2287
// computation rather than computing a new body.
2288
if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2289
if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2290
if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2291
E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2292
}
2293
}
2294
2295
if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2296
Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2297
!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2298
getCurFunction()->recordUseOfWeak(E);
2299
2300
const auto *FD = dyn_cast<FieldDecl>(D);
2301
if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2302
FD = IFD->getAnonField();
2303
if (FD) {
2304
UnusedPrivateFields.remove(FD);
2305
// Just in case we're building an illegal pointer-to-member.
2306
if (FD->isBitField())
2307
E->setObjectKind(OK_BitField);
2308
}
2309
2310
// C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2311
// designates a bit-field.
2312
if (const auto *BD = dyn_cast<BindingDecl>(D))
2313
if (const auto *BE = BD->getBinding())
2314
E->setObjectKind(BE->getObjectKind());
2315
2316
return E;
2317
}
2318
2319
void
2320
Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2321
TemplateArgumentListInfo &Buffer,
2322
DeclarationNameInfo &NameInfo,
2323
const TemplateArgumentListInfo *&TemplateArgs) {
2324
if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2325
Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2326
Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2327
2328
ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2329
Id.TemplateId->NumArgs);
2330
translateTemplateArguments(TemplateArgsPtr, Buffer);
2331
2332
TemplateName TName = Id.TemplateId->Template.get();
2333
SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2334
NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2335
TemplateArgs = &Buffer;
2336
} else {
2337
NameInfo = GetNameFromUnqualifiedId(Id);
2338
TemplateArgs = nullptr;
2339
}
2340
}
2341
2342
static void emitEmptyLookupTypoDiagnostic(
2343
const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2344
DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2345
unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2346
DeclContext *Ctx =
2347
SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2348
if (!TC) {
2349
// Emit a special diagnostic for failed member lookups.
2350
// FIXME: computing the declaration context might fail here (?)
2351
if (Ctx)
2352
SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2353
<< SS.getRange();
2354
else
2355
SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2356
return;
2357
}
2358
2359
std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2360
bool DroppedSpecifier =
2361
TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2362
unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2363
? diag::note_implicit_param_decl
2364
: diag::note_previous_decl;
2365
if (!Ctx)
2366
SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2367
SemaRef.PDiag(NoteID));
2368
else
2369
SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2370
<< Typo << Ctx << DroppedSpecifier
2371
<< SS.getRange(),
2372
SemaRef.PDiag(NoteID));
2373
}
2374
2375
bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2376
// During a default argument instantiation the CurContext points
2377
// to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2378
// function parameter list, hence add an explicit check.
2379
bool isDefaultArgument =
2380
!CodeSynthesisContexts.empty() &&
2381
CodeSynthesisContexts.back().Kind ==
2382
CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2383
const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2384
bool isInstance = CurMethod && CurMethod->isInstance() &&
2385
R.getNamingClass() == CurMethod->getParent() &&
2386
!isDefaultArgument;
2387
2388
// There are two ways we can find a class-scope declaration during template
2389
// instantiation that we did not find in the template definition: if it is a
2390
// member of a dependent base class, or if it is declared after the point of
2391
// use in the same class. Distinguish these by comparing the class in which
2392
// the member was found to the naming class of the lookup.
2393
unsigned DiagID = diag::err_found_in_dependent_base;
2394
unsigned NoteID = diag::note_member_declared_at;
2395
if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2396
DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2397
: diag::err_found_later_in_class;
2398
} else if (getLangOpts().MSVCCompat) {
2399
DiagID = diag::ext_found_in_dependent_base;
2400
NoteID = diag::note_dependent_member_use;
2401
}
2402
2403
if (isInstance) {
2404
// Give a code modification hint to insert 'this->'.
2405
Diag(R.getNameLoc(), DiagID)
2406
<< R.getLookupName()
2407
<< FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2408
CheckCXXThisCapture(R.getNameLoc());
2409
} else {
2410
// FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2411
// they're not shadowed).
2412
Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2413
}
2414
2415
for (const NamedDecl *D : R)
2416
Diag(D->getLocation(), NoteID);
2417
2418
// Return true if we are inside a default argument instantiation
2419
// and the found name refers to an instance member function, otherwise
2420
// the caller will try to create an implicit member call and this is wrong
2421
// for default arguments.
2422
//
2423
// FIXME: Is this special case necessary? We could allow the caller to
2424
// diagnose this.
2425
if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2426
Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2427
return true;
2428
}
2429
2430
// Tell the callee to try to recover.
2431
return false;
2432
}
2433
2434
bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2435
CorrectionCandidateCallback &CCC,
2436
TemplateArgumentListInfo *ExplicitTemplateArgs,
2437
ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2438
TypoExpr **Out) {
2439
DeclarationName Name = R.getLookupName();
2440
2441
unsigned diagnostic = diag::err_undeclared_var_use;
2442
unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2443
if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2444
Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2445
Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2446
diagnostic = diag::err_undeclared_use;
2447
diagnostic_suggest = diag::err_undeclared_use_suggest;
2448
}
2449
2450
// If the original lookup was an unqualified lookup, fake an
2451
// unqualified lookup. This is useful when (for example) the
2452
// original lookup would not have found something because it was a
2453
// dependent name.
2454
DeclContext *DC =
2455
LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2456
while (DC) {
2457
if (isa<CXXRecordDecl>(DC)) {
2458
LookupQualifiedName(R, DC);
2459
2460
if (!R.empty()) {
2461
// Don't give errors about ambiguities in this lookup.
2462
R.suppressDiagnostics();
2463
2464
// If there's a best viable function among the results, only mention
2465
// that one in the notes.
2466
OverloadCandidateSet Candidates(R.getNameLoc(),
2467
OverloadCandidateSet::CSK_Normal);
2468
AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2469
OverloadCandidateSet::iterator Best;
2470
if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2471
OR_Success) {
2472
R.clear();
2473
R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2474
R.resolveKind();
2475
}
2476
2477
return DiagnoseDependentMemberLookup(R);
2478
}
2479
2480
R.clear();
2481
}
2482
2483
DC = DC->getLookupParent();
2484
}
2485
2486
// We didn't find anything, so try to correct for a typo.
2487
TypoCorrection Corrected;
2488
if (S && Out) {
2489
SourceLocation TypoLoc = R.getNameLoc();
2490
assert(!ExplicitTemplateArgs &&
2491
"Diagnosing an empty lookup with explicit template args!");
2492
*Out = CorrectTypoDelayed(
2493
R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2494
[=](const TypoCorrection &TC) {
2495
emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2496
diagnostic, diagnostic_suggest);
2497
},
2498
nullptr, CTK_ErrorRecovery, LookupCtx);
2499
if (*Out)
2500
return true;
2501
} else if (S && (Corrected =
2502
CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
2503
&SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2504
std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2505
bool DroppedSpecifier =
2506
Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2507
R.setLookupName(Corrected.getCorrection());
2508
2509
bool AcceptableWithRecovery = false;
2510
bool AcceptableWithoutRecovery = false;
2511
NamedDecl *ND = Corrected.getFoundDecl();
2512
if (ND) {
2513
if (Corrected.isOverloaded()) {
2514
OverloadCandidateSet OCS(R.getNameLoc(),
2515
OverloadCandidateSet::CSK_Normal);
2516
OverloadCandidateSet::iterator Best;
2517
for (NamedDecl *CD : Corrected) {
2518
if (FunctionTemplateDecl *FTD =
2519
dyn_cast<FunctionTemplateDecl>(CD))
2520
AddTemplateOverloadCandidate(
2521
FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2522
Args, OCS);
2523
else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2524
if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2525
AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2526
Args, OCS);
2527
}
2528
switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2529
case OR_Success:
2530
ND = Best->FoundDecl;
2531
Corrected.setCorrectionDecl(ND);
2532
break;
2533
default:
2534
// FIXME: Arbitrarily pick the first declaration for the note.
2535
Corrected.setCorrectionDecl(ND);
2536
break;
2537
}
2538
}
2539
R.addDecl(ND);
2540
if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2541
CXXRecordDecl *Record = nullptr;
2542
if (Corrected.getCorrectionSpecifier()) {
2543
const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2544
Record = Ty->getAsCXXRecordDecl();
2545
}
2546
if (!Record)
2547
Record = cast<CXXRecordDecl>(
2548
ND->getDeclContext()->getRedeclContext());
2549
R.setNamingClass(Record);
2550
}
2551
2552
auto *UnderlyingND = ND->getUnderlyingDecl();
2553
AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2554
isa<FunctionTemplateDecl>(UnderlyingND);
2555
// FIXME: If we ended up with a typo for a type name or
2556
// Objective-C class name, we're in trouble because the parser
2557
// is in the wrong place to recover. Suggest the typo
2558
// correction, but don't make it a fix-it since we're not going
2559
// to recover well anyway.
2560
AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2561
getAsTypeTemplateDecl(UnderlyingND) ||
2562
isa<ObjCInterfaceDecl>(UnderlyingND);
2563
} else {
2564
// FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2565
// because we aren't able to recover.
2566
AcceptableWithoutRecovery = true;
2567
}
2568
2569
if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2570
unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2571
? diag::note_implicit_param_decl
2572
: diag::note_previous_decl;
2573
if (SS.isEmpty())
2574
diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2575
PDiag(NoteID), AcceptableWithRecovery);
2576
else
2577
diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2578
<< Name << computeDeclContext(SS, false)
2579
<< DroppedSpecifier << SS.getRange(),
2580
PDiag(NoteID), AcceptableWithRecovery);
2581
2582
// Tell the callee whether to try to recover.
2583
return !AcceptableWithRecovery;
2584
}
2585
}
2586
R.clear();
2587
2588
// Emit a special diagnostic for failed member lookups.
2589
// FIXME: computing the declaration context might fail here (?)
2590
if (!SS.isEmpty()) {
2591
Diag(R.getNameLoc(), diag::err_no_member)
2592
<< Name << computeDeclContext(SS, false)
2593
<< SS.getRange();
2594
return true;
2595
}
2596
2597
// Give up, we can't recover.
2598
Diag(R.getNameLoc(), diagnostic) << Name;
2599
return true;
2600
}
2601
2602
/// In Microsoft mode, if we are inside a template class whose parent class has
2603
/// dependent base classes, and we can't resolve an unqualified identifier, then
2604
/// assume the identifier is a member of a dependent base class. We can only
2605
/// recover successfully in static methods, instance methods, and other contexts
2606
/// where 'this' is available. This doesn't precisely match MSVC's
2607
/// instantiation model, but it's close enough.
2608
static Expr *
2609
recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2610
DeclarationNameInfo &NameInfo,
2611
SourceLocation TemplateKWLoc,
2612
const TemplateArgumentListInfo *TemplateArgs) {
2613
// Only try to recover from lookup into dependent bases in static methods or
2614
// contexts where 'this' is available.
2615
QualType ThisType = S.getCurrentThisType();
2616
const CXXRecordDecl *RD = nullptr;
2617
if (!ThisType.isNull())
2618
RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2619
else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2620
RD = MD->getParent();
2621
if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2622
return nullptr;
2623
2624
// Diagnose this as unqualified lookup into a dependent base class. If 'this'
2625
// is available, suggest inserting 'this->' as a fixit.
2626
SourceLocation Loc = NameInfo.getLoc();
2627
auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2628
DB << NameInfo.getName() << RD;
2629
2630
if (!ThisType.isNull()) {
2631
DB << FixItHint::CreateInsertion(Loc, "this->");
2632
return CXXDependentScopeMemberExpr::Create(
2633
Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2634
/*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2635
/*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2636
}
2637
2638
// Synthesize a fake NNS that points to the derived class. This will
2639
// perform name lookup during template instantiation.
2640
CXXScopeSpec SS;
2641
auto *NNS =
2642
NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2643
SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2644
return DependentScopeDeclRefExpr::Create(
2645
Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2646
TemplateArgs);
2647
}
2648
2649
ExprResult
2650
Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2651
SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2652
bool HasTrailingLParen, bool IsAddressOfOperand,
2653
CorrectionCandidateCallback *CCC,
2654
bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2655
assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2656
"cannot be direct & operand and have a trailing lparen");
2657
if (SS.isInvalid())
2658
return ExprError();
2659
2660
TemplateArgumentListInfo TemplateArgsBuffer;
2661
2662
// Decompose the UnqualifiedId into the following data.
2663
DeclarationNameInfo NameInfo;
2664
const TemplateArgumentListInfo *TemplateArgs;
2665
DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2666
2667
DeclarationName Name = NameInfo.getName();
2668
IdentifierInfo *II = Name.getAsIdentifierInfo();
2669
SourceLocation NameLoc = NameInfo.getLoc();
2670
2671
if (II && II->isEditorPlaceholder()) {
2672
// FIXME: When typed placeholders are supported we can create a typed
2673
// placeholder expression node.
2674
return ExprError();
2675
}
2676
2677
// This specially handles arguments of attributes appertains to a type of C
2678
// struct field such that the name lookup within a struct finds the member
2679
// name, which is not the case for other contexts in C.
2680
if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2681
// See if this is reference to a field of struct.
2682
LookupResult R(*this, NameInfo, LookupMemberName);
2683
// LookupName handles a name lookup from within anonymous struct.
2684
if (LookupName(R, S)) {
2685
if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2686
QualType type = VD->getType().getNonReferenceType();
2687
// This will eventually be translated into MemberExpr upon
2688
// the use of instantiated struct fields.
2689
return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2690
}
2691
}
2692
}
2693
2694
// Perform the required lookup.
2695
LookupResult R(*this, NameInfo,
2696
(Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2697
? LookupObjCImplicitSelfParam
2698
: LookupOrdinaryName);
2699
if (TemplateKWLoc.isValid() || TemplateArgs) {
2700
// Lookup the template name again to correctly establish the context in
2701
// which it was found. This is really unfortunate as we already did the
2702
// lookup to determine that it was a template name in the first place. If
2703
// this becomes a performance hit, we can work harder to preserve those
2704
// results until we get here but it's likely not worth it.
2705
AssumedTemplateKind AssumedTemplate;
2706
if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2707
/*EnteringContext=*/false, TemplateKWLoc,
2708
&AssumedTemplate))
2709
return ExprError();
2710
2711
if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2712
return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2713
IsAddressOfOperand, TemplateArgs);
2714
} else {
2715
bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2716
LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2717
/*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2718
2719
// If the result might be in a dependent base class, this is a dependent
2720
// id-expression.
2721
if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2722
return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2723
IsAddressOfOperand, TemplateArgs);
2724
2725
// If this reference is in an Objective-C method, then we need to do
2726
// some special Objective-C lookup, too.
2727
if (IvarLookupFollowUp) {
2728
ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2729
if (E.isInvalid())
2730
return ExprError();
2731
2732
if (Expr *Ex = E.getAs<Expr>())
2733
return Ex;
2734
}
2735
}
2736
2737
if (R.isAmbiguous())
2738
return ExprError();
2739
2740
// This could be an implicitly declared function reference if the language
2741
// mode allows it as a feature.
2742
if (R.empty() && HasTrailingLParen && II &&
2743
getLangOpts().implicitFunctionsAllowed()) {
2744
NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2745
if (D) R.addDecl(D);
2746
}
2747
2748
// Determine whether this name might be a candidate for
2749
// argument-dependent lookup.
2750
bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2751
2752
if (R.empty() && !ADL) {
2753
if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2754
if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2755
TemplateKWLoc, TemplateArgs))
2756
return E;
2757
}
2758
2759
// Don't diagnose an empty lookup for inline assembly.
2760
if (IsInlineAsmIdentifier)
2761
return ExprError();
2762
2763
// If this name wasn't predeclared and if this is not a function
2764
// call, diagnose the problem.
2765
TypoExpr *TE = nullptr;
2766
DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2767
: nullptr);
2768
DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2769
assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2770
"Typo correction callback misconfigured");
2771
if (CCC) {
2772
// Make sure the callback knows what the typo being diagnosed is.
2773
CCC->setTypoName(II);
2774
if (SS.isValid())
2775
CCC->setTypoNNS(SS.getScopeRep());
2776
}
2777
// FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2778
// a template name, but we happen to have always already looked up the name
2779
// before we get here if it must be a template name.
2780
if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2781
std::nullopt, nullptr, &TE)) {
2782
if (TE && KeywordReplacement) {
2783
auto &State = getTypoExprState(TE);
2784
auto BestTC = State.Consumer->getNextCorrection();
2785
if (BestTC.isKeyword()) {
2786
auto *II = BestTC.getCorrectionAsIdentifierInfo();
2787
if (State.DiagHandler)
2788
State.DiagHandler(BestTC);
2789
KeywordReplacement->startToken();
2790
KeywordReplacement->setKind(II->getTokenID());
2791
KeywordReplacement->setIdentifierInfo(II);
2792
KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2793
// Clean up the state associated with the TypoExpr, since it has
2794
// now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2795
clearDelayedTypo(TE);
2796
// Signal that a correction to a keyword was performed by returning a
2797
// valid-but-null ExprResult.
2798
return (Expr*)nullptr;
2799
}
2800
State.Consumer->resetCorrectionStream();
2801
}
2802
return TE ? TE : ExprError();
2803
}
2804
2805
assert(!R.empty() &&
2806
"DiagnoseEmptyLookup returned false but added no results");
2807
2808
// If we found an Objective-C instance variable, let
2809
// LookupInObjCMethod build the appropriate expression to
2810
// reference the ivar.
2811
if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2812
R.clear();
2813
ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2814
// In a hopelessly buggy code, Objective-C instance variable
2815
// lookup fails and no expression will be built to reference it.
2816
if (!E.isInvalid() && !E.get())
2817
return ExprError();
2818
return E;
2819
}
2820
}
2821
2822
// This is guaranteed from this point on.
2823
assert(!R.empty() || ADL);
2824
2825
// Check whether this might be a C++ implicit instance member access.
2826
// C++ [class.mfct.non-static]p3:
2827
// When an id-expression that is not part of a class member access
2828
// syntax and not used to form a pointer to member is used in the
2829
// body of a non-static member function of class X, if name lookup
2830
// resolves the name in the id-expression to a non-static non-type
2831
// member of some class C, the id-expression is transformed into a
2832
// class member access expression using (*this) as the
2833
// postfix-expression to the left of the . operator.
2834
//
2835
// But we don't actually need to do this for '&' operands if R
2836
// resolved to a function or overloaded function set, because the
2837
// expression is ill-formed if it actually works out to be a
2838
// non-static member function:
2839
//
2840
// C++ [expr.ref]p4:
2841
// Otherwise, if E1.E2 refers to a non-static member function. . .
2842
// [t]he expression can be used only as the left-hand operand of a
2843
// member function call.
2844
//
2845
// There are other safeguards against such uses, but it's important
2846
// to get this right here so that we don't end up making a
2847
// spuriously dependent expression if we're inside a dependent
2848
// instance method.
2849
if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2850
return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2851
S);
2852
2853
if (TemplateArgs || TemplateKWLoc.isValid()) {
2854
2855
// In C++1y, if this is a variable template id, then check it
2856
// in BuildTemplateIdExpr().
2857
// The single lookup result must be a variable template declaration.
2858
if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2859
Id.TemplateId->Kind == TNK_Var_template) {
2860
assert(R.getAsSingle<VarTemplateDecl>() &&
2861
"There should only be one declaration found.");
2862
}
2863
2864
return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2865
}
2866
2867
return BuildDeclarationNameExpr(SS, R, ADL);
2868
}
2869
2870
ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2871
CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2872
bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2873
LookupResult R(*this, NameInfo, LookupOrdinaryName);
2874
LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2875
2876
if (R.isAmbiguous())
2877
return ExprError();
2878
2879
if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2880
return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2881
NameInfo, /*TemplateArgs=*/nullptr);
2882
2883
if (R.empty()) {
2884
// Don't diagnose problems with invalid record decl, the secondary no_member
2885
// diagnostic during template instantiation is likely bogus, e.g. if a class
2886
// is invalid because it's derived from an invalid base class, then missing
2887
// members were likely supposed to be inherited.
2888
DeclContext *DC = computeDeclContext(SS);
2889
if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2890
if (CD->isInvalidDecl())
2891
return ExprError();
2892
Diag(NameInfo.getLoc(), diag::err_no_member)
2893
<< NameInfo.getName() << DC << SS.getRange();
2894
return ExprError();
2895
}
2896
2897
if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2898
// Diagnose a missing typename if this resolved unambiguously to a type in
2899
// a dependent context. If we can recover with a type, downgrade this to
2900
// a warning in Microsoft compatibility mode.
2901
unsigned DiagID = diag::err_typename_missing;
2902
if (RecoveryTSI && getLangOpts().MSVCCompat)
2903
DiagID = diag::ext_typename_missing;
2904
SourceLocation Loc = SS.getBeginLoc();
2905
auto D = Diag(Loc, DiagID);
2906
D << SS.getScopeRep() << NameInfo.getName().getAsString()
2907
<< SourceRange(Loc, NameInfo.getEndLoc());
2908
2909
// Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2910
// context.
2911
if (!RecoveryTSI)
2912
return ExprError();
2913
2914
// Only issue the fixit if we're prepared to recover.
2915
D << FixItHint::CreateInsertion(Loc, "typename ");
2916
2917
// Recover by pretending this was an elaborated type.
2918
QualType Ty = Context.getTypeDeclType(TD);
2919
TypeLocBuilder TLB;
2920
TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2921
2922
QualType ET = getElaboratedType(ElaboratedTypeKeyword::None, SS, Ty);
2923
ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2924
QTL.setElaboratedKeywordLoc(SourceLocation());
2925
QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2926
2927
*RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2928
2929
return ExprEmpty();
2930
}
2931
2932
// If necessary, build an implicit class member access.
2933
if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2934
return BuildPossibleImplicitMemberExpr(SS,
2935
/*TemplateKWLoc=*/SourceLocation(),
2936
R, /*TemplateArgs=*/nullptr,
2937
/*S=*/nullptr);
2938
2939
return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
2940
}
2941
2942
ExprResult
2943
Sema::PerformObjectMemberConversion(Expr *From,
2944
NestedNameSpecifier *Qualifier,
2945
NamedDecl *FoundDecl,
2946
NamedDecl *Member) {
2947
const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2948
if (!RD)
2949
return From;
2950
2951
QualType DestRecordType;
2952
QualType DestType;
2953
QualType FromRecordType;
2954
QualType FromType = From->getType();
2955
bool PointerConversions = false;
2956
if (isa<FieldDecl>(Member)) {
2957
DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2958
auto FromPtrType = FromType->getAs<PointerType>();
2959
DestRecordType = Context.getAddrSpaceQualType(
2960
DestRecordType, FromPtrType
2961
? FromType->getPointeeType().getAddressSpace()
2962
: FromType.getAddressSpace());
2963
2964
if (FromPtrType) {
2965
DestType = Context.getPointerType(DestRecordType);
2966
FromRecordType = FromPtrType->getPointeeType();
2967
PointerConversions = true;
2968
} else {
2969
DestType = DestRecordType;
2970
FromRecordType = FromType;
2971
}
2972
} else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
2973
if (!Method->isImplicitObjectMemberFunction())
2974
return From;
2975
2976
DestType = Method->getThisType().getNonReferenceType();
2977
DestRecordType = Method->getFunctionObjectParameterType();
2978
2979
if (FromType->getAs<PointerType>()) {
2980
FromRecordType = FromType->getPointeeType();
2981
PointerConversions = true;
2982
} else {
2983
FromRecordType = FromType;
2984
DestType = DestRecordType;
2985
}
2986
2987
LangAS FromAS = FromRecordType.getAddressSpace();
2988
LangAS DestAS = DestRecordType.getAddressSpace();
2989
if (FromAS != DestAS) {
2990
QualType FromRecordTypeWithoutAS =
2991
Context.removeAddrSpaceQualType(FromRecordType);
2992
QualType FromTypeWithDestAS =
2993
Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2994
if (PointerConversions)
2995
FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2996
From = ImpCastExprToType(From, FromTypeWithDestAS,
2997
CK_AddressSpaceConversion, From->getValueKind())
2998
.get();
2999
}
3000
} else {
3001
// No conversion necessary.
3002
return From;
3003
}
3004
3005
if (DestType->isDependentType() || FromType->isDependentType())
3006
return From;
3007
3008
// If the unqualified types are the same, no conversion is necessary.
3009
if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3010
return From;
3011
3012
SourceRange FromRange = From->getSourceRange();
3013
SourceLocation FromLoc = FromRange.getBegin();
3014
3015
ExprValueKind VK = From->getValueKind();
3016
3017
// C++ [class.member.lookup]p8:
3018
// [...] Ambiguities can often be resolved by qualifying a name with its
3019
// class name.
3020
//
3021
// If the member was a qualified name and the qualified referred to a
3022
// specific base subobject type, we'll cast to that intermediate type
3023
// first and then to the object in which the member is declared. That allows
3024
// one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3025
//
3026
// class Base { public: int x; };
3027
// class Derived1 : public Base { };
3028
// class Derived2 : public Base { };
3029
// class VeryDerived : public Derived1, public Derived2 { void f(); };
3030
//
3031
// void VeryDerived::f() {
3032
// x = 17; // error: ambiguous base subobjects
3033
// Derived1::x = 17; // okay, pick the Base subobject of Derived1
3034
// }
3035
if (Qualifier && Qualifier->getAsType()) {
3036
QualType QType = QualType(Qualifier->getAsType(), 0);
3037
assert(QType->isRecordType() && "lookup done with non-record type");
3038
3039
QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3040
3041
// In C++98, the qualifier type doesn't actually have to be a base
3042
// type of the object type, in which case we just ignore it.
3043
// Otherwise build the appropriate casts.
3044
if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3045
CXXCastPath BasePath;
3046
if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3047
FromLoc, FromRange, &BasePath))
3048
return ExprError();
3049
3050
if (PointerConversions)
3051
QType = Context.getPointerType(QType);
3052
From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3053
VK, &BasePath).get();
3054
3055
FromType = QType;
3056
FromRecordType = QRecordType;
3057
3058
// If the qualifier type was the same as the destination type,
3059
// we're done.
3060
if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3061
return From;
3062
}
3063
}
3064
3065
CXXCastPath BasePath;
3066
if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3067
FromLoc, FromRange, &BasePath,
3068
/*IgnoreAccess=*/true))
3069
return ExprError();
3070
3071
return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3072
VK, &BasePath);
3073
}
3074
3075
bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3076
const LookupResult &R,
3077
bool HasTrailingLParen) {
3078
// Only when used directly as the postfix-expression of a call.
3079
if (!HasTrailingLParen)
3080
return false;
3081
3082
// Never if a scope specifier was provided.
3083
if (SS.isNotEmpty())
3084
return false;
3085
3086
// Only in C++ or ObjC++.
3087
if (!getLangOpts().CPlusPlus)
3088
return false;
3089
3090
// Turn off ADL when we find certain kinds of declarations during
3091
// normal lookup:
3092
for (const NamedDecl *D : R) {
3093
// C++0x [basic.lookup.argdep]p3:
3094
// -- a declaration of a class member
3095
// Since using decls preserve this property, we check this on the
3096
// original decl.
3097
if (D->isCXXClassMember())
3098
return false;
3099
3100
// C++0x [basic.lookup.argdep]p3:
3101
// -- a block-scope function declaration that is not a
3102
// using-declaration
3103
// NOTE: we also trigger this for function templates (in fact, we
3104
// don't check the decl type at all, since all other decl types
3105
// turn off ADL anyway).
3106
if (isa<UsingShadowDecl>(D))
3107
D = cast<UsingShadowDecl>(D)->getTargetDecl();
3108
else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3109
return false;
3110
3111
// C++0x [basic.lookup.argdep]p3:
3112
// -- a declaration that is neither a function or a function
3113
// template
3114
// And also for builtin functions.
3115
if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3116
// But also builtin functions.
3117
if (FDecl->getBuiltinID() && FDecl->isImplicit())
3118
return false;
3119
} else if (!isa<FunctionTemplateDecl>(D))
3120
return false;
3121
}
3122
3123
return true;
3124
}
3125
3126
3127
/// Diagnoses obvious problems with the use of the given declaration
3128
/// as an expression. This is only actually called for lookups that
3129
/// were not overloaded, and it doesn't promise that the declaration
3130
/// will in fact be used.
3131
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3132
bool AcceptInvalid) {
3133
if (D->isInvalidDecl() && !AcceptInvalid)
3134
return true;
3135
3136
if (isa<TypedefNameDecl>(D)) {
3137
S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3138
return true;
3139
}
3140
3141
if (isa<ObjCInterfaceDecl>(D)) {
3142
S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3143
return true;
3144
}
3145
3146
if (isa<NamespaceDecl>(D)) {
3147
S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3148
return true;
3149
}
3150
3151
return false;
3152
}
3153
3154
// Certain multiversion types should be treated as overloaded even when there is
3155
// only one result.
3156
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3157
assert(R.isSingleResult() && "Expected only a single result");
3158
const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3159
return FD &&
3160
(FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3161
}
3162
3163
ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3164
LookupResult &R, bool NeedsADL,
3165
bool AcceptInvalidDecl) {
3166
// If this is a single, fully-resolved result and we don't need ADL,
3167
// just build an ordinary singleton decl ref.
3168
if (!NeedsADL && R.isSingleResult() &&
3169
!R.getAsSingle<FunctionTemplateDecl>() &&
3170
!ShouldLookupResultBeMultiVersionOverload(R))
3171
return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3172
R.getRepresentativeDecl(), nullptr,
3173
AcceptInvalidDecl);
3174
3175
// We only need to check the declaration if there's exactly one
3176
// result, because in the overloaded case the results can only be
3177
// functions and function templates.
3178
if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3179
CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3180
AcceptInvalidDecl))
3181
return ExprError();
3182
3183
// Otherwise, just build an unresolved lookup expression. Suppress
3184
// any lookup-related diagnostics; we'll hash these out later, when
3185
// we've picked a target.
3186
R.suppressDiagnostics();
3187
3188
UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3189
Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3190
R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3191
/*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3192
3193
return ULE;
3194
}
3195
3196
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3197
SourceLocation loc,
3198
ValueDecl *var);
3199
3200
ExprResult Sema::BuildDeclarationNameExpr(
3201
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3202
NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3203
bool AcceptInvalidDecl) {
3204
assert(D && "Cannot refer to a NULL declaration");
3205
assert(!isa<FunctionTemplateDecl>(D) &&
3206
"Cannot refer unambiguously to a function template");
3207
3208
SourceLocation Loc = NameInfo.getLoc();
3209
if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3210
// Recovery from invalid cases (e.g. D is an invalid Decl).
3211
// We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3212
// diagnostics, as invalid decls use int as a fallback type.
3213
return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3214
}
3215
3216
if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3217
// Specifically diagnose references to class templates that are missing
3218
// a template argument list.
3219
diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3220
return ExprError();
3221
}
3222
3223
// Make sure that we're referring to a value.
3224
if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3225
Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3226
Diag(D->getLocation(), diag::note_declared_at);
3227
return ExprError();
3228
}
3229
3230
// Check whether this declaration can be used. Note that we suppress
3231
// this check when we're going to perform argument-dependent lookup
3232
// on this function name, because this might not be the function
3233
// that overload resolution actually selects.
3234
if (DiagnoseUseOfDecl(D, Loc))
3235
return ExprError();
3236
3237
auto *VD = cast<ValueDecl>(D);
3238
3239
// Only create DeclRefExpr's for valid Decl's.
3240
if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3241
return ExprError();
3242
3243
// Handle members of anonymous structs and unions. If we got here,
3244
// and the reference is to a class member indirect field, then this
3245
// must be the subject of a pointer-to-member expression.
3246
if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3247
IndirectField && !IndirectField->isCXXClassMember())
3248
return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3249
IndirectField);
3250
3251
QualType type = VD->getType();
3252
if (type.isNull())
3253
return ExprError();
3254
ExprValueKind valueKind = VK_PRValue;
3255
3256
// In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3257
// a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3258
// is expanded by some outer '...' in the context of the use.
3259
type = type.getNonPackExpansionType();
3260
3261
switch (D->getKind()) {
3262
// Ignore all the non-ValueDecl kinds.
3263
#define ABSTRACT_DECL(kind)
3264
#define VALUE(type, base)
3265
#define DECL(type, base) case Decl::type:
3266
#include "clang/AST/DeclNodes.inc"
3267
llvm_unreachable("invalid value decl kind");
3268
3269
// These shouldn't make it here.
3270
case Decl::ObjCAtDefsField:
3271
llvm_unreachable("forming non-member reference to ivar?");
3272
3273
// Enum constants are always r-values and never references.
3274
// Unresolved using declarations are dependent.
3275
case Decl::EnumConstant:
3276
case Decl::UnresolvedUsingValue:
3277
case Decl::OMPDeclareReduction:
3278
case Decl::OMPDeclareMapper:
3279
valueKind = VK_PRValue;
3280
break;
3281
3282
// Fields and indirect fields that got here must be for
3283
// pointer-to-member expressions; we just call them l-values for
3284
// internal consistency, because this subexpression doesn't really
3285
// exist in the high-level semantics.
3286
case Decl::Field:
3287
case Decl::IndirectField:
3288
case Decl::ObjCIvar:
3289
assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3290
"building reference to field in C?");
3291
3292
// These can't have reference type in well-formed programs, but
3293
// for internal consistency we do this anyway.
3294
type = type.getNonReferenceType();
3295
valueKind = VK_LValue;
3296
break;
3297
3298
// Non-type template parameters are either l-values or r-values
3299
// depending on the type.
3300
case Decl::NonTypeTemplateParm: {
3301
if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3302
type = reftype->getPointeeType();
3303
valueKind = VK_LValue; // even if the parameter is an r-value reference
3304
break;
3305
}
3306
3307
// [expr.prim.id.unqual]p2:
3308
// If the entity is a template parameter object for a template
3309
// parameter of type T, the type of the expression is const T.
3310
// [...] The expression is an lvalue if the entity is a [...] template
3311
// parameter object.
3312
if (type->isRecordType()) {
3313
type = type.getUnqualifiedType().withConst();
3314
valueKind = VK_LValue;
3315
break;
3316
}
3317
3318
// For non-references, we need to strip qualifiers just in case
3319
// the template parameter was declared as 'const int' or whatever.
3320
valueKind = VK_PRValue;
3321
type = type.getUnqualifiedType();
3322
break;
3323
}
3324
3325
case Decl::Var:
3326
case Decl::VarTemplateSpecialization:
3327
case Decl::VarTemplatePartialSpecialization:
3328
case Decl::Decomposition:
3329
case Decl::OMPCapturedExpr:
3330
// In C, "extern void blah;" is valid and is an r-value.
3331
if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3332
type->isVoidType()) {
3333
valueKind = VK_PRValue;
3334
break;
3335
}
3336
[[fallthrough]];
3337
3338
case Decl::ImplicitParam:
3339
case Decl::ParmVar: {
3340
// These are always l-values.
3341
valueKind = VK_LValue;
3342
type = type.getNonReferenceType();
3343
3344
// FIXME: Does the addition of const really only apply in
3345
// potentially-evaluated contexts? Since the variable isn't actually
3346
// captured in an unevaluated context, it seems that the answer is no.
3347
if (!isUnevaluatedContext()) {
3348
QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3349
if (!CapturedType.isNull())
3350
type = CapturedType;
3351
}
3352
3353
break;
3354
}
3355
3356
case Decl::Binding:
3357
// These are always lvalues.
3358
valueKind = VK_LValue;
3359
type = type.getNonReferenceType();
3360
break;
3361
3362
case Decl::Function: {
3363
if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3364
if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3365
type = Context.BuiltinFnTy;
3366
valueKind = VK_PRValue;
3367
break;
3368
}
3369
}
3370
3371
const FunctionType *fty = type->castAs<FunctionType>();
3372
3373
// If we're referring to a function with an __unknown_anytype
3374
// result type, make the entire expression __unknown_anytype.
3375
if (fty->getReturnType() == Context.UnknownAnyTy) {
3376
type = Context.UnknownAnyTy;
3377
valueKind = VK_PRValue;
3378
break;
3379
}
3380
3381
// Functions are l-values in C++.
3382
if (getLangOpts().CPlusPlus) {
3383
valueKind = VK_LValue;
3384
break;
3385
}
3386
3387
// C99 DR 316 says that, if a function type comes from a
3388
// function definition (without a prototype), that type is only
3389
// used for checking compatibility. Therefore, when referencing
3390
// the function, we pretend that we don't have the full function
3391
// type.
3392
if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3393
type = Context.getFunctionNoProtoType(fty->getReturnType(),
3394
fty->getExtInfo());
3395
3396
// Functions are r-values in C.
3397
valueKind = VK_PRValue;
3398
break;
3399
}
3400
3401
case Decl::CXXDeductionGuide:
3402
llvm_unreachable("building reference to deduction guide");
3403
3404
case Decl::MSProperty:
3405
case Decl::MSGuid:
3406
case Decl::TemplateParamObject:
3407
// FIXME: Should MSGuidDecl and template parameter objects be subject to
3408
// capture in OpenMP, or duplicated between host and device?
3409
valueKind = VK_LValue;
3410
break;
3411
3412
case Decl::UnnamedGlobalConstant:
3413
valueKind = VK_LValue;
3414
break;
3415
3416
case Decl::CXXMethod:
3417
// If we're referring to a method with an __unknown_anytype
3418
// result type, make the entire expression __unknown_anytype.
3419
// This should only be possible with a type written directly.
3420
if (const FunctionProtoType *proto =
3421
dyn_cast<FunctionProtoType>(VD->getType()))
3422
if (proto->getReturnType() == Context.UnknownAnyTy) {
3423
type = Context.UnknownAnyTy;
3424
valueKind = VK_PRValue;
3425
break;
3426
}
3427
3428
// C++ methods are l-values if static, r-values if non-static.
3429
if (cast<CXXMethodDecl>(VD)->isStatic()) {
3430
valueKind = VK_LValue;
3431
break;
3432
}
3433
[[fallthrough]];
3434
3435
case Decl::CXXConversion:
3436
case Decl::CXXDestructor:
3437
case Decl::CXXConstructor:
3438
valueKind = VK_PRValue;
3439
break;
3440
}
3441
3442
auto *E =
3443
BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3444
/*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3445
// Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3446
// wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3447
// RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3448
// diagnostics).
3449
if (VD->isInvalidDecl() && E)
3450
return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3451
return E;
3452
}
3453
3454
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3455
SmallString<32> &Target) {
3456
Target.resize(CharByteWidth * (Source.size() + 1));
3457
char *ResultPtr = &Target[0];
3458
const llvm::UTF8 *ErrorPtr;
3459
bool success =
3460
llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3461
(void)success;
3462
assert(success);
3463
Target.resize(ResultPtr - &Target[0]);
3464
}
3465
3466
ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3467
PredefinedIdentKind IK) {
3468
Decl *currentDecl = getPredefinedExprDecl(CurContext);
3469
if (!currentDecl) {
3470
Diag(Loc, diag::ext_predef_outside_function);
3471
currentDecl = Context.getTranslationUnitDecl();
3472
}
3473
3474
QualType ResTy;
3475
StringLiteral *SL = nullptr;
3476
if (cast<DeclContext>(currentDecl)->isDependentContext())
3477
ResTy = Context.DependentTy;
3478
else {
3479
// Pre-defined identifiers are of type char[x], where x is the length of
3480
// the string.
3481
bool ForceElaboratedPrinting =
3482
IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3483
auto Str =
3484
PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3485
unsigned Length = Str.length();
3486
3487
llvm::APInt LengthI(32, Length + 1);
3488
if (IK == PredefinedIdentKind::LFunction ||
3489
IK == PredefinedIdentKind::LFuncSig) {
3490
ResTy =
3491
Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3492
SmallString<32> RawChars;
3493
ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3494
Str, RawChars);
3495
ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3496
ArraySizeModifier::Normal,
3497
/*IndexTypeQuals*/ 0);
3498
SL = StringLiteral::Create(Context, RawChars, StringLiteralKind::Wide,
3499
/*Pascal*/ false, ResTy, Loc);
3500
} else {
3501
ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3502
ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3503
ArraySizeModifier::Normal,
3504
/*IndexTypeQuals*/ 0);
3505
SL = StringLiteral::Create(Context, Str, StringLiteralKind::Ordinary,
3506
/*Pascal*/ false, ResTy, Loc);
3507
}
3508
}
3509
3510
return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3511
SL);
3512
}
3513
3514
ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3515
return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3516
}
3517
3518
ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3519
SmallString<16> CharBuffer;
3520
bool Invalid = false;
3521
StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3522
if (Invalid)
3523
return ExprError();
3524
3525
CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3526
PP, Tok.getKind());
3527
if (Literal.hadError())
3528
return ExprError();
3529
3530
QualType Ty;
3531
if (Literal.isWide())
3532
Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3533
else if (Literal.isUTF8() && getLangOpts().C23)
3534
Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3535
else if (Literal.isUTF8() && getLangOpts().Char8)
3536
Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3537
else if (Literal.isUTF16())
3538
Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3539
else if (Literal.isUTF32())
3540
Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3541
else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3542
Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3543
else
3544
Ty = Context.CharTy; // 'x' -> char in C++;
3545
// u8'x' -> char in C11-C17 and in C++ without char8_t.
3546
3547
CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3548
if (Literal.isWide())
3549
Kind = CharacterLiteralKind::Wide;
3550
else if (Literal.isUTF16())
3551
Kind = CharacterLiteralKind::UTF16;
3552
else if (Literal.isUTF32())
3553
Kind = CharacterLiteralKind::UTF32;
3554
else if (Literal.isUTF8())
3555
Kind = CharacterLiteralKind::UTF8;
3556
3557
Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3558
Tok.getLocation());
3559
3560
if (Literal.getUDSuffix().empty())
3561
return Lit;
3562
3563
// We're building a user-defined literal.
3564
IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3565
SourceLocation UDSuffixLoc =
3566
getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3567
3568
// Make sure we're allowed user-defined literals here.
3569
if (!UDLScope)
3570
return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3571
3572
// C++11 [lex.ext]p6: The literal L is treated as a call of the form
3573
// operator "" X (ch)
3574
return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3575
Lit, Tok.getLocation());
3576
}
3577
3578
ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3579
unsigned IntSize = Context.getTargetInfo().getIntWidth();
3580
return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3581
Context.IntTy, Loc);
3582
}
3583
3584
static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3585
QualType Ty, SourceLocation Loc) {
3586
const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3587
3588
using llvm::APFloat;
3589
APFloat Val(Format);
3590
3591
llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3592
if (RM == llvm::RoundingMode::Dynamic)
3593
RM = llvm::RoundingMode::NearestTiesToEven;
3594
APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3595
3596
// Overflow is always an error, but underflow is only an error if
3597
// we underflowed to zero (APFloat reports denormals as underflow).
3598
if ((result & APFloat::opOverflow) ||
3599
((result & APFloat::opUnderflow) && Val.isZero())) {
3600
unsigned diagnostic;
3601
SmallString<20> buffer;
3602
if (result & APFloat::opOverflow) {
3603
diagnostic = diag::warn_float_overflow;
3604
APFloat::getLargest(Format).toString(buffer);
3605
} else {
3606
diagnostic = diag::warn_float_underflow;
3607
APFloat::getSmallest(Format).toString(buffer);
3608
}
3609
3610
S.Diag(Loc, diagnostic) << Ty << buffer.str();
3611
}
3612
3613
bool isExact = (result == APFloat::opOK);
3614
return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3615
}
3616
3617
bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3618
assert(E && "Invalid expression");
3619
3620
if (E->isValueDependent())
3621
return false;
3622
3623
QualType QT = E->getType();
3624
if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3625
Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3626
return true;
3627
}
3628
3629
llvm::APSInt ValueAPS;
3630
ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3631
3632
if (R.isInvalid())
3633
return true;
3634
3635
// GCC allows the value of unroll count to be 0.
3636
// https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3637
// "The values of 0 and 1 block any unrolling of the loop."
3638
// The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3639
// '#pragma unroll' cases.
3640
bool ValueIsPositive =
3641
AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3642
if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3643
Diag(E->getExprLoc(), diag::err_requires_positive_value)
3644
<< toString(ValueAPS, 10) << ValueIsPositive;
3645
return true;
3646
}
3647
3648
return false;
3649
}
3650
3651
ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3652
// Fast path for a single digit (which is quite common). A single digit
3653
// cannot have a trigraph, escaped newline, radix prefix, or suffix.
3654
if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3655
const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3656
return ActOnIntegerConstant(Tok.getLocation(), Val);
3657
}
3658
3659
SmallString<128> SpellingBuffer;
3660
// NumericLiteralParser wants to overread by one character. Add padding to
3661
// the buffer in case the token is copied to the buffer. If getSpelling()
3662
// returns a StringRef to the memory buffer, it should have a null char at
3663
// the EOF, so it is also safe.
3664
SpellingBuffer.resize(Tok.getLength() + 1);
3665
3666
// Get the spelling of the token, which eliminates trigraphs, etc.
3667
bool Invalid = false;
3668
StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3669
if (Invalid)
3670
return ExprError();
3671
3672
NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3673
PP.getSourceManager(), PP.getLangOpts(),
3674
PP.getTargetInfo(), PP.getDiagnostics());
3675
if (Literal.hadError)
3676
return ExprError();
3677
3678
if (Literal.hasUDSuffix()) {
3679
// We're building a user-defined literal.
3680
const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3681
SourceLocation UDSuffixLoc =
3682
getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3683
3684
// Make sure we're allowed user-defined literals here.
3685
if (!UDLScope)
3686
return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3687
3688
QualType CookedTy;
3689
if (Literal.isFloatingLiteral()) {
3690
// C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3691
// long double, the literal is treated as a call of the form
3692
// operator "" X (f L)
3693
CookedTy = Context.LongDoubleTy;
3694
} else {
3695
// C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3696
// unsigned long long, the literal is treated as a call of the form
3697
// operator "" X (n ULL)
3698
CookedTy = Context.UnsignedLongLongTy;
3699
}
3700
3701
DeclarationName OpName =
3702
Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3703
DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3704
OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3705
3706
SourceLocation TokLoc = Tok.getLocation();
3707
3708
// Perform literal operator lookup to determine if we're building a raw
3709
// literal or a cooked one.
3710
LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3711
switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3712
/*AllowRaw*/ true, /*AllowTemplate*/ true,
3713
/*AllowStringTemplatePack*/ false,
3714
/*DiagnoseMissing*/ !Literal.isImaginary)) {
3715
case LOLR_ErrorNoDiagnostic:
3716
// Lookup failure for imaginary constants isn't fatal, there's still the
3717
// GNU extension producing _Complex types.
3718
break;
3719
case LOLR_Error:
3720
return ExprError();
3721
case LOLR_Cooked: {
3722
Expr *Lit;
3723
if (Literal.isFloatingLiteral()) {
3724
Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3725
} else {
3726
llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3727
if (Literal.GetIntegerValue(ResultVal))
3728
Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3729
<< /* Unsigned */ 1;
3730
Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3731
Tok.getLocation());
3732
}
3733
return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3734
}
3735
3736
case LOLR_Raw: {
3737
// C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3738
// literal is treated as a call of the form
3739
// operator "" X ("n")
3740
unsigned Length = Literal.getUDSuffixOffset();
3741
QualType StrTy = Context.getConstantArrayType(
3742
Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3743
llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3744
Expr *Lit =
3745
StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3746
StringLiteralKind::Ordinary,
3747
/*Pascal*/ false, StrTy, &TokLoc, 1);
3748
return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3749
}
3750
3751
case LOLR_Template: {
3752
// C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3753
// template), L is treated as a call fo the form
3754
// operator "" X <'c1', 'c2', ... 'ck'>()
3755
// where n is the source character sequence c1 c2 ... ck.
3756
TemplateArgumentListInfo ExplicitArgs;
3757
unsigned CharBits = Context.getIntWidth(Context.CharTy);
3758
bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3759
llvm::APSInt Value(CharBits, CharIsUnsigned);
3760
for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3761
Value = TokSpelling[I];
3762
TemplateArgument Arg(Context, Value, Context.CharTy);
3763
TemplateArgumentLocInfo ArgInfo;
3764
ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3765
}
3766
return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3767
&ExplicitArgs);
3768
}
3769
case LOLR_StringTemplatePack:
3770
llvm_unreachable("unexpected literal operator lookup result");
3771
}
3772
}
3773
3774
Expr *Res;
3775
3776
if (Literal.isFixedPointLiteral()) {
3777
QualType Ty;
3778
3779
if (Literal.isAccum) {
3780
if (Literal.isHalf) {
3781
Ty = Context.ShortAccumTy;
3782
} else if (Literal.isLong) {
3783
Ty = Context.LongAccumTy;
3784
} else {
3785
Ty = Context.AccumTy;
3786
}
3787
} else if (Literal.isFract) {
3788
if (Literal.isHalf) {
3789
Ty = Context.ShortFractTy;
3790
} else if (Literal.isLong) {
3791
Ty = Context.LongFractTy;
3792
} else {
3793
Ty = Context.FractTy;
3794
}
3795
}
3796
3797
if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3798
3799
bool isSigned = !Literal.isUnsigned;
3800
unsigned scale = Context.getFixedPointScale(Ty);
3801
unsigned bit_width = Context.getTypeInfo(Ty).Width;
3802
3803
llvm::APInt Val(bit_width, 0, isSigned);
3804
bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3805
bool ValIsZero = Val.isZero() && !Overflowed;
3806
3807
auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3808
if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3809
// Clause 6.4.4 - The value of a constant shall be in the range of
3810
// representable values for its type, with exception for constants of a
3811
// fract type with a value of exactly 1; such a constant shall denote
3812
// the maximal value for the type.
3813
--Val;
3814
else if (Val.ugt(MaxVal) || Overflowed)
3815
Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3816
3817
Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3818
Tok.getLocation(), scale);
3819
} else if (Literal.isFloatingLiteral()) {
3820
QualType Ty;
3821
if (Literal.isHalf){
3822
if (getLangOpts().HLSL ||
3823
getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3824
Ty = Context.HalfTy;
3825
else {
3826
Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3827
return ExprError();
3828
}
3829
} else if (Literal.isFloat)
3830
Ty = Context.FloatTy;
3831
else if (Literal.isLong)
3832
Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3833
else if (Literal.isFloat16)
3834
Ty = Context.Float16Ty;
3835
else if (Literal.isFloat128)
3836
Ty = Context.Float128Ty;
3837
else if (getLangOpts().HLSL)
3838
Ty = Context.FloatTy;
3839
else
3840
Ty = Context.DoubleTy;
3841
3842
Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3843
3844
if (Ty == Context.DoubleTy) {
3845
if (getLangOpts().SinglePrecisionConstants) {
3846
if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3847
Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3848
}
3849
} else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3850
"cl_khr_fp64", getLangOpts())) {
3851
// Impose single-precision float type when cl_khr_fp64 is not enabled.
3852
Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3853
<< (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3854
Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3855
}
3856
}
3857
} else if (!Literal.isIntegerLiteral()) {
3858
return ExprError();
3859
} else {
3860
QualType Ty;
3861
3862
// 'z/uz' literals are a C++23 feature.
3863
if (Literal.isSizeT)
3864
Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3865
? getLangOpts().CPlusPlus23
3866
? diag::warn_cxx20_compat_size_t_suffix
3867
: diag::ext_cxx23_size_t_suffix
3868
: diag::err_cxx23_size_t_suffix);
3869
3870
// 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3871
// but we do not currently support the suffix in C++ mode because it's not
3872
// entirely clear whether WG21 will prefer this suffix to return a library
3873
// type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3874
// literals are a C++ extension.
3875
if (Literal.isBitInt)
3876
PP.Diag(Tok.getLocation(),
3877
getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3878
: getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3879
: diag::ext_c23_bitint_suffix);
3880
3881
// Get the value in the widest-possible width. What is "widest" depends on
3882
// whether the literal is a bit-precise integer or not. For a bit-precise
3883
// integer type, try to scan the source to determine how many bits are
3884
// needed to represent the value. This may seem a bit expensive, but trying
3885
// to get the integer value from an overly-wide APInt is *extremely*
3886
// expensive, so the naive approach of assuming
3887
// llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3888
unsigned BitsNeeded =
3889
Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3890
Literal.getLiteralDigits(), Literal.getRadix())
3891
: Context.getTargetInfo().getIntMaxTWidth();
3892
llvm::APInt ResultVal(BitsNeeded, 0);
3893
3894
if (Literal.GetIntegerValue(ResultVal)) {
3895
// If this value didn't fit into uintmax_t, error and force to ull.
3896
Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3897
<< /* Unsigned */ 1;
3898
Ty = Context.UnsignedLongLongTy;
3899
assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3900
"long long is not intmax_t?");
3901
} else {
3902
// If this value fits into a ULL, try to figure out what else it fits into
3903
// according to the rules of C99 6.4.4.1p5.
3904
3905
// Octal, Hexadecimal, and integers with a U suffix are allowed to
3906
// be an unsigned int.
3907
bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3908
3909
// HLSL doesn't really have `long` or `long long`. We support the `ll`
3910
// suffix for portability of code with C++, but both `l` and `ll` are
3911
// 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3912
// same.
3913
if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3914
Literal.isLong = true;
3915
Literal.isLongLong = false;
3916
}
3917
3918
// Check from smallest to largest, picking the smallest type we can.
3919
unsigned Width = 0;
3920
3921
// Microsoft specific integer suffixes are explicitly sized.
3922
if (Literal.MicrosoftInteger) {
3923
if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3924
Width = 8;
3925
Ty = Context.CharTy;
3926
} else {
3927
Width = Literal.MicrosoftInteger;
3928
Ty = Context.getIntTypeForBitwidth(Width,
3929
/*Signed=*/!Literal.isUnsigned);
3930
}
3931
}
3932
3933
// Bit-precise integer literals are automagically-sized based on the
3934
// width required by the literal.
3935
if (Literal.isBitInt) {
3936
// The signed version has one more bit for the sign value. There are no
3937
// zero-width bit-precise integers, even if the literal value is 0.
3938
Width = std::max(ResultVal.getActiveBits(), 1u) +
3939
(Literal.isUnsigned ? 0u : 1u);
3940
3941
// Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3942
// and reset the type to the largest supported width.
3943
unsigned int MaxBitIntWidth =
3944
Context.getTargetInfo().getMaxBitIntWidth();
3945
if (Width > MaxBitIntWidth) {
3946
Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3947
<< Literal.isUnsigned;
3948
Width = MaxBitIntWidth;
3949
}
3950
3951
// Reset the result value to the smaller APInt and select the correct
3952
// type to be used. Note, we zext even for signed values because the
3953
// literal itself is always an unsigned value (a preceeding - is a
3954
// unary operator, not part of the literal).
3955
ResultVal = ResultVal.zextOrTrunc(Width);
3956
Ty = Context.getBitIntType(Literal.isUnsigned, Width);
3957
}
3958
3959
// Check C++23 size_t literals.
3960
if (Literal.isSizeT) {
3961
assert(!Literal.MicrosoftInteger &&
3962
"size_t literals can't be Microsoft literals");
3963
unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3964
Context.getTargetInfo().getSizeType());
3965
3966
// Does it fit in size_t?
3967
if (ResultVal.isIntN(SizeTSize)) {
3968
// Does it fit in ssize_t?
3969
if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3970
Ty = Context.getSignedSizeType();
3971
else if (AllowUnsigned)
3972
Ty = Context.getSizeType();
3973
Width = SizeTSize;
3974
}
3975
}
3976
3977
if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3978
!Literal.isSizeT) {
3979
// Are int/unsigned possibilities?
3980
unsigned IntSize = Context.getTargetInfo().getIntWidth();
3981
3982
// Does it fit in a unsigned int?
3983
if (ResultVal.isIntN(IntSize)) {
3984
// Does it fit in a signed int?
3985
if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3986
Ty = Context.IntTy;
3987
else if (AllowUnsigned)
3988
Ty = Context.UnsignedIntTy;
3989
Width = IntSize;
3990
}
3991
}
3992
3993
// Are long/unsigned long possibilities?
3994
if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3995
unsigned LongSize = Context.getTargetInfo().getLongWidth();
3996
3997
// Does it fit in a unsigned long?
3998
if (ResultVal.isIntN(LongSize)) {
3999
// Does it fit in a signed long?
4000
if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4001
Ty = Context.LongTy;
4002
else if (AllowUnsigned)
4003
Ty = Context.UnsignedLongTy;
4004
// Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4005
// is compatible.
4006
else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4007
const unsigned LongLongSize =
4008
Context.getTargetInfo().getLongLongWidth();
4009
Diag(Tok.getLocation(),
4010
getLangOpts().CPlusPlus
4011
? Literal.isLong
4012
? diag::warn_old_implicitly_unsigned_long_cxx
4013
: /*C++98 UB*/ diag::
4014
ext_old_implicitly_unsigned_long_cxx
4015
: diag::warn_old_implicitly_unsigned_long)
4016
<< (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4017
: /*will be ill-formed*/ 1);
4018
Ty = Context.UnsignedLongTy;
4019
}
4020
Width = LongSize;
4021
}
4022
}
4023
4024
// Check long long if needed.
4025
if (Ty.isNull() && !Literal.isSizeT) {
4026
unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4027
4028
// Does it fit in a unsigned long long?
4029
if (ResultVal.isIntN(LongLongSize)) {
4030
// Does it fit in a signed long long?
4031
// To be compatible with MSVC, hex integer literals ending with the
4032
// LL or i64 suffix are always signed in Microsoft mode.
4033
if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4034
(getLangOpts().MSVCCompat && Literal.isLongLong)))
4035
Ty = Context.LongLongTy;
4036
else if (AllowUnsigned)
4037
Ty = Context.UnsignedLongLongTy;
4038
Width = LongLongSize;
4039
4040
// 'long long' is a C99 or C++11 feature, whether the literal
4041
// explicitly specified 'long long' or we needed the extra width.
4042
if (getLangOpts().CPlusPlus)
4043
Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4044
? diag::warn_cxx98_compat_longlong
4045
: diag::ext_cxx11_longlong);
4046
else if (!getLangOpts().C99)
4047
Diag(Tok.getLocation(), diag::ext_c99_longlong);
4048
}
4049
}
4050
4051
// If we still couldn't decide a type, we either have 'size_t' literal
4052
// that is out of range, or a decimal literal that does not fit in a
4053
// signed long long and has no U suffix.
4054
if (Ty.isNull()) {
4055
if (Literal.isSizeT)
4056
Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4057
<< Literal.isUnsigned;
4058
else
4059
Diag(Tok.getLocation(),
4060
diag::ext_integer_literal_too_large_for_signed);
4061
Ty = Context.UnsignedLongLongTy;
4062
Width = Context.getTargetInfo().getLongLongWidth();
4063
}
4064
4065
if (ResultVal.getBitWidth() != Width)
4066
ResultVal = ResultVal.trunc(Width);
4067
}
4068
Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4069
}
4070
4071
// If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4072
if (Literal.isImaginary) {
4073
Res = new (Context) ImaginaryLiteral(Res,
4074
Context.getComplexType(Res->getType()));
4075
4076
Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4077
}
4078
return Res;
4079
}
4080
4081
ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4082
assert(E && "ActOnParenExpr() missing expr");
4083
QualType ExprTy = E->getType();
4084
if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4085
!E->isLValue() && ExprTy->hasFloatingRepresentation())
4086
return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4087
return new (Context) ParenExpr(L, R, E);
4088
}
4089
4090
static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4091
SourceLocation Loc,
4092
SourceRange ArgRange) {
4093
// [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4094
// scalar or vector data type argument..."
4095
// Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4096
// type (C99 6.2.5p18) or void.
4097
if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4098
S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4099
<< T << ArgRange;
4100
return true;
4101
}
4102
4103
assert((T->isVoidType() || !T->isIncompleteType()) &&
4104
"Scalar types should always be complete");
4105
return false;
4106
}
4107
4108
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4109
SourceLocation Loc,
4110
SourceRange ArgRange) {
4111
// builtin_vectorelements supports both fixed-sized and scalable vectors.
4112
if (!T->isVectorType() && !T->isSizelessVectorType())
4113
return S.Diag(Loc, diag::err_builtin_non_vector_type)
4114
<< ""
4115
<< "__builtin_vectorelements" << T << ArgRange;
4116
4117
return false;
4118
}
4119
4120
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,
4121
SourceLocation Loc,
4122
SourceRange ArgRange) {
4123
if (S.checkPointerAuthEnabled(Loc, ArgRange))
4124
return true;
4125
4126
if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4127
!T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4128
S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4129
return true;
4130
}
4131
4132
return false;
4133
}
4134
4135
static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4136
SourceLocation Loc,
4137
SourceRange ArgRange,
4138
UnaryExprOrTypeTrait TraitKind) {
4139
// Invalid types must be hard errors for SFINAE in C++.
4140
if (S.LangOpts.CPlusPlus)
4141
return true;
4142
4143
// C99 6.5.3.4p1:
4144
if (T->isFunctionType() &&
4145
(TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4146
TraitKind == UETT_PreferredAlignOf)) {
4147
// sizeof(function)/alignof(function) is allowed as an extension.
4148
S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4149
<< getTraitSpelling(TraitKind) << ArgRange;
4150
return false;
4151
}
4152
4153
// Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4154
// this is an error (OpenCL v1.1 s6.3.k)
4155
if (T->isVoidType()) {
4156
unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4157
: diag::ext_sizeof_alignof_void_type;
4158
S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4159
return false;
4160
}
4161
4162
return true;
4163
}
4164
4165
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4166
SourceLocation Loc,
4167
SourceRange ArgRange,
4168
UnaryExprOrTypeTrait TraitKind) {
4169
// Reject sizeof(interface) and sizeof(interface<proto>) if the
4170
// runtime doesn't allow it.
4171
if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4172
S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4173
<< T << (TraitKind == UETT_SizeOf)
4174
<< ArgRange;
4175
return true;
4176
}
4177
4178
return false;
4179
}
4180
4181
/// Check whether E is a pointer from a decayed array type (the decayed
4182
/// pointer type is equal to T) and emit a warning if it is.
4183
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4184
const Expr *E) {
4185
// Don't warn if the operation changed the type.
4186
if (T != E->getType())
4187
return;
4188
4189
// Now look for array decays.
4190
const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4191
if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4192
return;
4193
4194
S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4195
<< ICE->getType()
4196
<< ICE->getSubExpr()->getType();
4197
}
4198
4199
bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4200
UnaryExprOrTypeTrait ExprKind) {
4201
QualType ExprTy = E->getType();
4202
assert(!ExprTy->isReferenceType());
4203
4204
bool IsUnevaluatedOperand =
4205
(ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4206
ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4207
ExprKind == UETT_VecStep);
4208
if (IsUnevaluatedOperand) {
4209
ExprResult Result = CheckUnevaluatedOperand(E);
4210
if (Result.isInvalid())
4211
return true;
4212
E = Result.get();
4213
}
4214
4215
// The operand for sizeof and alignof is in an unevaluated expression context,
4216
// so side effects could result in unintended consequences.
4217
// Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4218
// used to build SFINAE gadgets.
4219
// FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4220
if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4221
!E->isInstantiationDependent() &&
4222
!E->getType()->isVariableArrayType() &&
4223
E->HasSideEffects(Context, false))
4224
Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4225
4226
if (ExprKind == UETT_VecStep)
4227
return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4228
E->getSourceRange());
4229
4230
if (ExprKind == UETT_VectorElements)
4231
return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4232
E->getSourceRange());
4233
4234
// Explicitly list some types as extensions.
4235
if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4236
E->getSourceRange(), ExprKind))
4237
return false;
4238
4239
// WebAssembly tables are always illegal operands to unary expressions and
4240
// type traits.
4241
if (Context.getTargetInfo().getTriple().isWasm() &&
4242
E->getType()->isWebAssemblyTableType()) {
4243
Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4244
<< getTraitSpelling(ExprKind);
4245
return true;
4246
}
4247
4248
// 'alignof' applied to an expression only requires the base element type of
4249
// the expression to be complete. 'sizeof' requires the expression's type to
4250
// be complete (and will attempt to complete it if it's an array of unknown
4251
// bound).
4252
if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4253
if (RequireCompleteSizedType(
4254
E->getExprLoc(), Context.getBaseElementType(E->getType()),
4255
diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4256
getTraitSpelling(ExprKind), E->getSourceRange()))
4257
return true;
4258
} else {
4259
if (RequireCompleteSizedExprType(
4260
E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4261
getTraitSpelling(ExprKind), E->getSourceRange()))
4262
return true;
4263
}
4264
4265
// Completing the expression's type may have changed it.
4266
ExprTy = E->getType();
4267
assert(!ExprTy->isReferenceType());
4268
4269
if (ExprTy->isFunctionType()) {
4270
Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4271
<< getTraitSpelling(ExprKind) << E->getSourceRange();
4272
return true;
4273
}
4274
4275
if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4276
E->getSourceRange(), ExprKind))
4277
return true;
4278
4279
if (ExprKind == UETT_SizeOf) {
4280
if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4281
if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4282
QualType OType = PVD->getOriginalType();
4283
QualType Type = PVD->getType();
4284
if (Type->isPointerType() && OType->isArrayType()) {
4285
Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4286
<< Type << OType;
4287
Diag(PVD->getLocation(), diag::note_declared_at);
4288
}
4289
}
4290
}
4291
4292
// Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4293
// decays into a pointer and returns an unintended result. This is most
4294
// likely a typo for "sizeof(array) op x".
4295
if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4296
warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4297
BO->getLHS());
4298
warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4299
BO->getRHS());
4300
}
4301
}
4302
4303
return false;
4304
}
4305
4306
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4307
// Cannot know anything else if the expression is dependent.
4308
if (E->isTypeDependent())
4309
return false;
4310
4311
if (E->getObjectKind() == OK_BitField) {
4312
S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4313
<< 1 << E->getSourceRange();
4314
return true;
4315
}
4316
4317
ValueDecl *D = nullptr;
4318
Expr *Inner = E->IgnoreParens();
4319
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4320
D = DRE->getDecl();
4321
} else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4322
D = ME->getMemberDecl();
4323
}
4324
4325
// If it's a field, require the containing struct to have a
4326
// complete definition so that we can compute the layout.
4327
//
4328
// This can happen in C++11 onwards, either by naming the member
4329
// in a way that is not transformed into a member access expression
4330
// (in an unevaluated operand, for instance), or by naming the member
4331
// in a trailing-return-type.
4332
//
4333
// For the record, since __alignof__ on expressions is a GCC
4334
// extension, GCC seems to permit this but always gives the
4335
// nonsensical answer 0.
4336
//
4337
// We don't really need the layout here --- we could instead just
4338
// directly check for all the appropriate alignment-lowing
4339
// attributes --- but that would require duplicating a lot of
4340
// logic that just isn't worth duplicating for such a marginal
4341
// use-case.
4342
if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4343
// Fast path this check, since we at least know the record has a
4344
// definition if we can find a member of it.
4345
if (!FD->getParent()->isCompleteDefinition()) {
4346
S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4347
<< E->getSourceRange();
4348
return true;
4349
}
4350
4351
// Otherwise, if it's a field, and the field doesn't have
4352
// reference type, then it must have a complete type (or be a
4353
// flexible array member, which we explicitly want to
4354
// white-list anyway), which makes the following checks trivial.
4355
if (!FD->getType()->isReferenceType())
4356
return false;
4357
}
4358
4359
return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4360
}
4361
4362
bool Sema::CheckVecStepExpr(Expr *E) {
4363
E = E->IgnoreParens();
4364
4365
// Cannot know anything else if the expression is dependent.
4366
if (E->isTypeDependent())
4367
return false;
4368
4369
return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4370
}
4371
4372
static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4373
CapturingScopeInfo *CSI) {
4374
assert(T->isVariablyModifiedType());
4375
assert(CSI != nullptr);
4376
4377
// We're going to walk down into the type and look for VLA expressions.
4378
do {
4379
const Type *Ty = T.getTypePtr();
4380
switch (Ty->getTypeClass()) {
4381
#define TYPE(Class, Base)
4382
#define ABSTRACT_TYPE(Class, Base)
4383
#define NON_CANONICAL_TYPE(Class, Base)
4384
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4385
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4386
#include "clang/AST/TypeNodes.inc"
4387
T = QualType();
4388
break;
4389
// These types are never variably-modified.
4390
case Type::Builtin:
4391
case Type::Complex:
4392
case Type::Vector:
4393
case Type::ExtVector:
4394
case Type::ConstantMatrix:
4395
case Type::Record:
4396
case Type::Enum:
4397
case Type::TemplateSpecialization:
4398
case Type::ObjCObject:
4399
case Type::ObjCInterface:
4400
case Type::ObjCObjectPointer:
4401
case Type::ObjCTypeParam:
4402
case Type::Pipe:
4403
case Type::BitInt:
4404
llvm_unreachable("type class is never variably-modified!");
4405
case Type::Elaborated:
4406
T = cast<ElaboratedType>(Ty)->getNamedType();
4407
break;
4408
case Type::Adjusted:
4409
T = cast<AdjustedType>(Ty)->getOriginalType();
4410
break;
4411
case Type::Decayed:
4412
T = cast<DecayedType>(Ty)->getPointeeType();
4413
break;
4414
case Type::ArrayParameter:
4415
T = cast<ArrayParameterType>(Ty)->getElementType();
4416
break;
4417
case Type::Pointer:
4418
T = cast<PointerType>(Ty)->getPointeeType();
4419
break;
4420
case Type::BlockPointer:
4421
T = cast<BlockPointerType>(Ty)->getPointeeType();
4422
break;
4423
case Type::LValueReference:
4424
case Type::RValueReference:
4425
T = cast<ReferenceType>(Ty)->getPointeeType();
4426
break;
4427
case Type::MemberPointer:
4428
T = cast<MemberPointerType>(Ty)->getPointeeType();
4429
break;
4430
case Type::ConstantArray:
4431
case Type::IncompleteArray:
4432
// Losing element qualification here is fine.
4433
T = cast<ArrayType>(Ty)->getElementType();
4434
break;
4435
case Type::VariableArray: {
4436
// Losing element qualification here is fine.
4437
const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4438
4439
// Unknown size indication requires no size computation.
4440
// Otherwise, evaluate and record it.
4441
auto Size = VAT->getSizeExpr();
4442
if (Size && !CSI->isVLATypeCaptured(VAT) &&
4443
(isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4444
CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4445
4446
T = VAT->getElementType();
4447
break;
4448
}
4449
case Type::FunctionProto:
4450
case Type::FunctionNoProto:
4451
T = cast<FunctionType>(Ty)->getReturnType();
4452
break;
4453
case Type::Paren:
4454
case Type::TypeOf:
4455
case Type::UnaryTransform:
4456
case Type::Attributed:
4457
case Type::BTFTagAttributed:
4458
case Type::SubstTemplateTypeParm:
4459
case Type::MacroQualified:
4460
case Type::CountAttributed:
4461
// Keep walking after single level desugaring.
4462
T = T.getSingleStepDesugaredType(Context);
4463
break;
4464
case Type::Typedef:
4465
T = cast<TypedefType>(Ty)->desugar();
4466
break;
4467
case Type::Decltype:
4468
T = cast<DecltypeType>(Ty)->desugar();
4469
break;
4470
case Type::PackIndexing:
4471
T = cast<PackIndexingType>(Ty)->desugar();
4472
break;
4473
case Type::Using:
4474
T = cast<UsingType>(Ty)->desugar();
4475
break;
4476
case Type::Auto:
4477
case Type::DeducedTemplateSpecialization:
4478
T = cast<DeducedType>(Ty)->getDeducedType();
4479
break;
4480
case Type::TypeOfExpr:
4481
T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4482
break;
4483
case Type::Atomic:
4484
T = cast<AtomicType>(Ty)->getValueType();
4485
break;
4486
}
4487
} while (!T.isNull() && T->isVariablyModifiedType());
4488
}
4489
4490
bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4491
SourceLocation OpLoc,
4492
SourceRange ExprRange,
4493
UnaryExprOrTypeTrait ExprKind,
4494
StringRef KWName) {
4495
if (ExprType->isDependentType())
4496
return false;
4497
4498
// C++ [expr.sizeof]p2:
4499
// When applied to a reference or a reference type, the result
4500
// is the size of the referenced type.
4501
// C++11 [expr.alignof]p3:
4502
// When alignof is applied to a reference type, the result
4503
// shall be the alignment of the referenced type.
4504
if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4505
ExprType = Ref->getPointeeType();
4506
4507
// C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4508
// When alignof or _Alignof is applied to an array type, the result
4509
// is the alignment of the element type.
4510
if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4511
ExprKind == UETT_OpenMPRequiredSimdAlign) {
4512
// If the trait is 'alignof' in C before C2y, the ability to apply the
4513
// trait to an incomplete array is an extension.
4514
if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4515
ExprType->isIncompleteArrayType())
4516
Diag(OpLoc, getLangOpts().C2y
4517
? diag::warn_c2y_compat_alignof_incomplete_array
4518
: diag::ext_c2y_alignof_incomplete_array);
4519
ExprType = Context.getBaseElementType(ExprType);
4520
}
4521
4522
if (ExprKind == UETT_VecStep)
4523
return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4524
4525
if (ExprKind == UETT_VectorElements)
4526
return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4527
ExprRange);
4528
4529
if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4530
return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4531
ExprRange);
4532
4533
// Explicitly list some types as extensions.
4534
if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4535
ExprKind))
4536
return false;
4537
4538
if (RequireCompleteSizedType(
4539
OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4540
KWName, ExprRange))
4541
return true;
4542
4543
if (ExprType->isFunctionType()) {
4544
Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4545
return true;
4546
}
4547
4548
// WebAssembly tables are always illegal operands to unary expressions and
4549
// type traits.
4550
if (Context.getTargetInfo().getTriple().isWasm() &&
4551
ExprType->isWebAssemblyTableType()) {
4552
Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4553
<< getTraitSpelling(ExprKind);
4554
return true;
4555
}
4556
4557
if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4558
ExprKind))
4559
return true;
4560
4561
if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4562
if (auto *TT = ExprType->getAs<TypedefType>()) {
4563
for (auto I = FunctionScopes.rbegin(),
4564
E = std::prev(FunctionScopes.rend());
4565
I != E; ++I) {
4566
auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4567
if (CSI == nullptr)
4568
break;
4569
DeclContext *DC = nullptr;
4570
if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4571
DC = LSI->CallOperator;
4572
else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4573
DC = CRSI->TheCapturedDecl;
4574
else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4575
DC = BSI->TheDecl;
4576
if (DC) {
4577
if (DC->containsDecl(TT->getDecl()))
4578
break;
4579
captureVariablyModifiedType(Context, ExprType, CSI);
4580
}
4581
}
4582
}
4583
}
4584
4585
return false;
4586
}
4587
4588
ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4589
SourceLocation OpLoc,
4590
UnaryExprOrTypeTrait ExprKind,
4591
SourceRange R) {
4592
if (!TInfo)
4593
return ExprError();
4594
4595
QualType T = TInfo->getType();
4596
4597
if (!T->isDependentType() &&
4598
CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4599
getTraitSpelling(ExprKind)))
4600
return ExprError();
4601
4602
// Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4603
// properly deal with VLAs in nested calls of sizeof and typeof.
4604
if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4605
TInfo->getType()->isVariablyModifiedType())
4606
TInfo = TransformToPotentiallyEvaluated(TInfo);
4607
4608
// C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4609
return new (Context) UnaryExprOrTypeTraitExpr(
4610
ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4611
}
4612
4613
ExprResult
4614
Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4615
UnaryExprOrTypeTrait ExprKind) {
4616
ExprResult PE = CheckPlaceholderExpr(E);
4617
if (PE.isInvalid())
4618
return ExprError();
4619
4620
E = PE.get();
4621
4622
// Verify that the operand is valid.
4623
bool isInvalid = false;
4624
if (E->isTypeDependent()) {
4625
// Delay type-checking for type-dependent expressions.
4626
} else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4627
isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4628
} else if (ExprKind == UETT_VecStep) {
4629
isInvalid = CheckVecStepExpr(E);
4630
} else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4631
Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4632
isInvalid = true;
4633
} else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4634
Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4635
isInvalid = true;
4636
} else if (ExprKind == UETT_VectorElements) {
4637
isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4638
} else {
4639
isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4640
}
4641
4642
if (isInvalid)
4643
return ExprError();
4644
4645
if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4646
PE = TransformToPotentiallyEvaluated(E);
4647
if (PE.isInvalid()) return ExprError();
4648
E = PE.get();
4649
}
4650
4651
// C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4652
return new (Context) UnaryExprOrTypeTraitExpr(
4653
ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4654
}
4655
4656
ExprResult
4657
Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4658
UnaryExprOrTypeTrait ExprKind, bool IsType,
4659
void *TyOrEx, SourceRange ArgRange) {
4660
// If error parsing type, ignore.
4661
if (!TyOrEx) return ExprError();
4662
4663
if (IsType) {
4664
TypeSourceInfo *TInfo;
4665
(void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4666
return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4667
}
4668
4669
Expr *ArgEx = (Expr *)TyOrEx;
4670
ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4671
return Result;
4672
}
4673
4674
bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4675
SourceLocation OpLoc, SourceRange R) {
4676
if (!TInfo)
4677
return true;
4678
return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4679
UETT_AlignOf, KWName);
4680
}
4681
4682
bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4683
SourceLocation OpLoc, SourceRange R) {
4684
TypeSourceInfo *TInfo;
4685
(void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()),
4686
&TInfo);
4687
return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4688
}
4689
4690
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4691
bool IsReal) {
4692
if (V.get()->isTypeDependent())
4693
return S.Context.DependentTy;
4694
4695
// _Real and _Imag are only l-values for normal l-values.
4696
if (V.get()->getObjectKind() != OK_Ordinary) {
4697
V = S.DefaultLvalueConversion(V.get());
4698
if (V.isInvalid())
4699
return QualType();
4700
}
4701
4702
// These operators return the element type of a complex type.
4703
if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4704
return CT->getElementType();
4705
4706
// Otherwise they pass through real integer and floating point types here.
4707
if (V.get()->getType()->isArithmeticType())
4708
return V.get()->getType();
4709
4710
// Test for placeholders.
4711
ExprResult PR = S.CheckPlaceholderExpr(V.get());
4712
if (PR.isInvalid()) return QualType();
4713
if (PR.get() != V.get()) {
4714
V = PR;
4715
return CheckRealImagOperand(S, V, Loc, IsReal);
4716
}
4717
4718
// Reject anything else.
4719
S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4720
<< (IsReal ? "__real" : "__imag");
4721
return QualType();
4722
}
4723
4724
4725
4726
ExprResult
4727
Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4728
tok::TokenKind Kind, Expr *Input) {
4729
UnaryOperatorKind Opc;
4730
switch (Kind) {
4731
default: llvm_unreachable("Unknown unary op!");
4732
case tok::plusplus: Opc = UO_PostInc; break;
4733
case tok::minusminus: Opc = UO_PostDec; break;
4734
}
4735
4736
// Since this might is a postfix expression, get rid of ParenListExprs.
4737
ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4738
if (Result.isInvalid()) return ExprError();
4739
Input = Result.get();
4740
4741
return BuildUnaryOp(S, OpLoc, Opc, Input);
4742
}
4743
4744
/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4745
///
4746
/// \return true on error
4747
static bool checkArithmeticOnObjCPointer(Sema &S,
4748
SourceLocation opLoc,
4749
Expr *op) {
4750
assert(op->getType()->isObjCObjectPointerType());
4751
if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4752
!S.LangOpts.ObjCSubscriptingLegacyRuntime)
4753
return false;
4754
4755
S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4756
<< op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4757
<< op->getSourceRange();
4758
return true;
4759
}
4760
4761
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4762
auto *BaseNoParens = Base->IgnoreParens();
4763
if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4764
return MSProp->getPropertyDecl()->getType()->isArrayType();
4765
return isa<MSPropertySubscriptExpr>(BaseNoParens);
4766
}
4767
4768
// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4769
// Typically this is DependentTy, but can sometimes be more precise.
4770
//
4771
// There are cases when we could determine a non-dependent type:
4772
// - LHS and RHS may have non-dependent types despite being type-dependent
4773
// (e.g. unbounded array static members of the current instantiation)
4774
// - one may be a dependent-sized array with known element type
4775
// - one may be a dependent-typed valid index (enum in current instantiation)
4776
//
4777
// We *always* return a dependent type, in such cases it is DependentTy.
4778
// This avoids creating type-dependent expressions with non-dependent types.
4779
// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4780
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4781
const ASTContext &Ctx) {
4782
assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4783
QualType LTy = LHS->getType(), RTy = RHS->getType();
4784
QualType Result = Ctx.DependentTy;
4785
if (RTy->isIntegralOrUnscopedEnumerationType()) {
4786
if (const PointerType *PT = LTy->getAs<PointerType>())
4787
Result = PT->getPointeeType();
4788
else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4789
Result = AT->getElementType();
4790
} else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4791
if (const PointerType *PT = RTy->getAs<PointerType>())
4792
Result = PT->getPointeeType();
4793
else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4794
Result = AT->getElementType();
4795
}
4796
// Ensure we return a dependent type.
4797
return Result->isDependentType() ? Result : Ctx.DependentTy;
4798
}
4799
4800
ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4801
SourceLocation lbLoc,
4802
MultiExprArg ArgExprs,
4803
SourceLocation rbLoc) {
4804
4805
if (base && !base->getType().isNull() &&
4806
base->hasPlaceholderType(BuiltinType::ArraySection)) {
4807
auto *AS = cast<ArraySectionExpr>(base);
4808
if (AS->isOMPArraySection())
4809
return OpenMP().ActOnOMPArraySectionExpr(
4810
base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4811
/*Length*/ nullptr,
4812
/*Stride=*/nullptr, rbLoc);
4813
4814
return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4815
SourceLocation(), /*Length*/ nullptr,
4816
rbLoc);
4817
}
4818
4819
// Since this might be a postfix expression, get rid of ParenListExprs.
4820
if (isa<ParenListExpr>(base)) {
4821
ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4822
if (result.isInvalid())
4823
return ExprError();
4824
base = result.get();
4825
}
4826
4827
// Check if base and idx form a MatrixSubscriptExpr.
4828
//
4829
// Helper to check for comma expressions, which are not allowed as indices for
4830
// matrix subscript expressions.
4831
auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4832
if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4833
Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4834
<< SourceRange(base->getBeginLoc(), rbLoc);
4835
return true;
4836
}
4837
return false;
4838
};
4839
// The matrix subscript operator ([][])is considered a single operator.
4840
// Separating the index expressions by parenthesis is not allowed.
4841
if (base && !base->getType().isNull() &&
4842
base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4843
!isa<MatrixSubscriptExpr>(base)) {
4844
Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4845
<< SourceRange(base->getBeginLoc(), rbLoc);
4846
return ExprError();
4847
}
4848
// If the base is a MatrixSubscriptExpr, try to create a new
4849
// MatrixSubscriptExpr.
4850
auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4851
if (matSubscriptE) {
4852
assert(ArgExprs.size() == 1);
4853
if (CheckAndReportCommaError(ArgExprs.front()))
4854
return ExprError();
4855
4856
assert(matSubscriptE->isIncomplete() &&
4857
"base has to be an incomplete matrix subscript");
4858
return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4859
matSubscriptE->getRowIdx(),
4860
ArgExprs.front(), rbLoc);
4861
}
4862
if (base->getType()->isWebAssemblyTableType()) {
4863
Diag(base->getExprLoc(), diag::err_wasm_table_art)
4864
<< SourceRange(base->getBeginLoc(), rbLoc) << 3;
4865
return ExprError();
4866
}
4867
4868
// Handle any non-overload placeholder types in the base and index
4869
// expressions. We can't handle overloads here because the other
4870
// operand might be an overloadable type, in which case the overload
4871
// resolution for the operator overload should get the first crack
4872
// at the overload.
4873
bool IsMSPropertySubscript = false;
4874
if (base->getType()->isNonOverloadPlaceholderType()) {
4875
IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4876
if (!IsMSPropertySubscript) {
4877
ExprResult result = CheckPlaceholderExpr(base);
4878
if (result.isInvalid())
4879
return ExprError();
4880
base = result.get();
4881
}
4882
}
4883
4884
// If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4885
if (base->getType()->isMatrixType()) {
4886
assert(ArgExprs.size() == 1);
4887
if (CheckAndReportCommaError(ArgExprs.front()))
4888
return ExprError();
4889
4890
return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4891
rbLoc);
4892
}
4893
4894
if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4895
Expr *idx = ArgExprs[0];
4896
if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4897
(isa<CXXOperatorCallExpr>(idx) &&
4898
cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4899
Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4900
<< SourceRange(base->getBeginLoc(), rbLoc);
4901
}
4902
}
4903
4904
if (ArgExprs.size() == 1 &&
4905
ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4906
ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4907
if (result.isInvalid())
4908
return ExprError();
4909
ArgExprs[0] = result.get();
4910
} else {
4911
if (CheckArgsForPlaceholders(ArgExprs))
4912
return ExprError();
4913
}
4914
4915
// Build an unanalyzed expression if either operand is type-dependent.
4916
if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4917
(base->isTypeDependent() ||
4918
Expr::hasAnyTypeDependentArguments(ArgExprs)) &&
4919
!isa<PackExpansionExpr>(ArgExprs[0])) {
4920
return new (Context) ArraySubscriptExpr(
4921
base, ArgExprs.front(),
4922
getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4923
VK_LValue, OK_Ordinary, rbLoc);
4924
}
4925
4926
// MSDN, property (C++)
4927
// https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4928
// This attribute can also be used in the declaration of an empty array in a
4929
// class or structure definition. For example:
4930
// __declspec(property(get=GetX, put=PutX)) int x[];
4931
// The above statement indicates that x[] can be used with one or more array
4932
// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4933
// and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4934
if (IsMSPropertySubscript) {
4935
assert(ArgExprs.size() == 1);
4936
// Build MS property subscript expression if base is MS property reference
4937
// or MS property subscript.
4938
return new (Context)
4939
MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4940
VK_LValue, OK_Ordinary, rbLoc);
4941
}
4942
4943
// Use C++ overloaded-operator rules if either operand has record
4944
// type. The spec says to do this if either type is *overloadable*,
4945
// but enum types can't declare subscript operators or conversion
4946
// operators, so there's nothing interesting for overload resolution
4947
// to do if there aren't any record types involved.
4948
//
4949
// ObjC pointers have their own subscripting logic that is not tied
4950
// to overload resolution and so should not take this path.
4951
if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4952
((base->getType()->isRecordType() ||
4953
(ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
4954
ArgExprs[0]->getType()->isRecordType())))) {
4955
return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4956
}
4957
4958
ExprResult Res =
4959
CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4960
4961
if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4962
CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4963
4964
return Res;
4965
}
4966
4967
ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4968
InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4969
InitializationKind Kind =
4970
InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4971
InitializationSequence InitSeq(*this, Entity, Kind, E);
4972
return InitSeq.Perform(*this, Entity, Kind, E);
4973
}
4974
4975
ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4976
Expr *ColumnIdx,
4977
SourceLocation RBLoc) {
4978
ExprResult BaseR = CheckPlaceholderExpr(Base);
4979
if (BaseR.isInvalid())
4980
return BaseR;
4981
Base = BaseR.get();
4982
4983
ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4984
if (RowR.isInvalid())
4985
return RowR;
4986
RowIdx = RowR.get();
4987
4988
if (!ColumnIdx)
4989
return new (Context) MatrixSubscriptExpr(
4990
Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4991
4992
// Build an unanalyzed expression if any of the operands is type-dependent.
4993
if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4994
ColumnIdx->isTypeDependent())
4995
return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4996
Context.DependentTy, RBLoc);
4997
4998
ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4999
if (ColumnR.isInvalid())
5000
return ColumnR;
5001
ColumnIdx = ColumnR.get();
5002
5003
// Check that IndexExpr is an integer expression. If it is a constant
5004
// expression, check that it is less than Dim (= the number of elements in the
5005
// corresponding dimension).
5006
auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5007
bool IsColumnIdx) -> Expr * {
5008
if (!IndexExpr->getType()->isIntegerType() &&
5009
!IndexExpr->isTypeDependent()) {
5010
Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5011
<< IsColumnIdx;
5012
return nullptr;
5013
}
5014
5015
if (std::optional<llvm::APSInt> Idx =
5016
IndexExpr->getIntegerConstantExpr(Context)) {
5017
if ((*Idx < 0 || *Idx >= Dim)) {
5018
Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5019
<< IsColumnIdx << Dim;
5020
return nullptr;
5021
}
5022
}
5023
5024
ExprResult ConvExpr =
5025
tryConvertExprToType(IndexExpr, Context.getSizeType());
5026
assert(!ConvExpr.isInvalid() &&
5027
"should be able to convert any integer type to size type");
5028
return ConvExpr.get();
5029
};
5030
5031
auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5032
RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5033
ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5034
if (!RowIdx || !ColumnIdx)
5035
return ExprError();
5036
5037
return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5038
MTy->getElementType(), RBLoc);
5039
}
5040
5041
void Sema::CheckAddressOfNoDeref(const Expr *E) {
5042
ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5043
const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5044
5045
// For expressions like `&(*s).b`, the base is recorded and what should be
5046
// checked.
5047
const MemberExpr *Member = nullptr;
5048
while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5049
StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5050
5051
LastRecord.PossibleDerefs.erase(StrippedExpr);
5052
}
5053
5054
void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5055
if (isUnevaluatedContext())
5056
return;
5057
5058
QualType ResultTy = E->getType();
5059
ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5060
5061
// Bail if the element is an array since it is not memory access.
5062
if (isa<ArrayType>(ResultTy))
5063
return;
5064
5065
if (ResultTy->hasAttr(attr::NoDeref)) {
5066
LastRecord.PossibleDerefs.insert(E);
5067
return;
5068
}
5069
5070
// Check if the base type is a pointer to a member access of a struct
5071
// marked with noderef.
5072
const Expr *Base = E->getBase();
5073
QualType BaseTy = Base->getType();
5074
if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5075
// Not a pointer access
5076
return;
5077
5078
const MemberExpr *Member = nullptr;
5079
while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5080
Member->isArrow())
5081
Base = Member->getBase();
5082
5083
if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5084
if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5085
LastRecord.PossibleDerefs.insert(E);
5086
}
5087
}
5088
5089
ExprResult
5090
Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5091
Expr *Idx, SourceLocation RLoc) {
5092
Expr *LHSExp = Base;
5093
Expr *RHSExp = Idx;
5094
5095
ExprValueKind VK = VK_LValue;
5096
ExprObjectKind OK = OK_Ordinary;
5097
5098
// Per C++ core issue 1213, the result is an xvalue if either operand is
5099
// a non-lvalue array, and an lvalue otherwise.
5100
if (getLangOpts().CPlusPlus11) {
5101
for (auto *Op : {LHSExp, RHSExp}) {
5102
Op = Op->IgnoreImplicit();
5103
if (Op->getType()->isArrayType() && !Op->isLValue())
5104
VK = VK_XValue;
5105
}
5106
}
5107
5108
// Perform default conversions.
5109
if (!LHSExp->getType()->isSubscriptableVectorType()) {
5110
ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5111
if (Result.isInvalid())
5112
return ExprError();
5113
LHSExp = Result.get();
5114
}
5115
ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5116
if (Result.isInvalid())
5117
return ExprError();
5118
RHSExp = Result.get();
5119
5120
QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5121
5122
// C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5123
// to the expression *((e1)+(e2)). This means the array "Base" may actually be
5124
// in the subscript position. As a result, we need to derive the array base
5125
// and index from the expression types.
5126
Expr *BaseExpr, *IndexExpr;
5127
QualType ResultType;
5128
if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5129
BaseExpr = LHSExp;
5130
IndexExpr = RHSExp;
5131
ResultType =
5132
getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5133
} else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5134
BaseExpr = LHSExp;
5135
IndexExpr = RHSExp;
5136
ResultType = PTy->getPointeeType();
5137
} else if (const ObjCObjectPointerType *PTy =
5138
LHSTy->getAs<ObjCObjectPointerType>()) {
5139
BaseExpr = LHSExp;
5140
IndexExpr = RHSExp;
5141
5142
// Use custom logic if this should be the pseudo-object subscript
5143
// expression.
5144
if (!LangOpts.isSubscriptPointerArithmetic())
5145
return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5146
nullptr, nullptr);
5147
5148
ResultType = PTy->getPointeeType();
5149
} else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5150
// Handle the uncommon case of "123[Ptr]".
5151
BaseExpr = RHSExp;
5152
IndexExpr = LHSExp;
5153
ResultType = PTy->getPointeeType();
5154
} else if (const ObjCObjectPointerType *PTy =
5155
RHSTy->getAs<ObjCObjectPointerType>()) {
5156
// Handle the uncommon case of "123[Ptr]".
5157
BaseExpr = RHSExp;
5158
IndexExpr = LHSExp;
5159
ResultType = PTy->getPointeeType();
5160
if (!LangOpts.isSubscriptPointerArithmetic()) {
5161
Diag(LLoc, diag::err_subscript_nonfragile_interface)
5162
<< ResultType << BaseExpr->getSourceRange();
5163
return ExprError();
5164
}
5165
} else if (LHSTy->isSubscriptableVectorType()) {
5166
if (LHSTy->isBuiltinType() &&
5167
LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5168
const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5169
if (BTy->isSVEBool())
5170
return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5171
<< LHSExp->getSourceRange()
5172
<< RHSExp->getSourceRange());
5173
ResultType = BTy->getSveEltType(Context);
5174
} else {
5175
const VectorType *VTy = LHSTy->getAs<VectorType>();
5176
ResultType = VTy->getElementType();
5177
}
5178
BaseExpr = LHSExp; // vectors: V[123]
5179
IndexExpr = RHSExp;
5180
// We apply C++ DR1213 to vector subscripting too.
5181
if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5182
ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5183
if (Materialized.isInvalid())
5184
return ExprError();
5185
LHSExp = Materialized.get();
5186
}
5187
VK = LHSExp->getValueKind();
5188
if (VK != VK_PRValue)
5189
OK = OK_VectorComponent;
5190
5191
QualType BaseType = BaseExpr->getType();
5192
Qualifiers BaseQuals = BaseType.getQualifiers();
5193
Qualifiers MemberQuals = ResultType.getQualifiers();
5194
Qualifiers Combined = BaseQuals + MemberQuals;
5195
if (Combined != MemberQuals)
5196
ResultType = Context.getQualifiedType(ResultType, Combined);
5197
} else if (LHSTy->isArrayType()) {
5198
// If we see an array that wasn't promoted by
5199
// DefaultFunctionArrayLvalueConversion, it must be an array that
5200
// wasn't promoted because of the C90 rule that doesn't
5201
// allow promoting non-lvalue arrays. Warn, then
5202
// force the promotion here.
5203
Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5204
<< LHSExp->getSourceRange();
5205
LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5206
CK_ArrayToPointerDecay).get();
5207
LHSTy = LHSExp->getType();
5208
5209
BaseExpr = LHSExp;
5210
IndexExpr = RHSExp;
5211
ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5212
} else if (RHSTy->isArrayType()) {
5213
// Same as previous, except for 123[f().a] case
5214
Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5215
<< RHSExp->getSourceRange();
5216
RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5217
CK_ArrayToPointerDecay).get();
5218
RHSTy = RHSExp->getType();
5219
5220
BaseExpr = RHSExp;
5221
IndexExpr = LHSExp;
5222
ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5223
} else {
5224
return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5225
<< LHSExp->getSourceRange() << RHSExp->getSourceRange());
5226
}
5227
// C99 6.5.2.1p1
5228
if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5229
return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5230
<< IndexExpr->getSourceRange());
5231
5232
if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5233
IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5234
!IndexExpr->isTypeDependent()) {
5235
std::optional<llvm::APSInt> IntegerContantExpr =
5236
IndexExpr->getIntegerConstantExpr(getASTContext());
5237
if (!IntegerContantExpr.has_value() ||
5238
IntegerContantExpr.value().isNegative())
5239
Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5240
}
5241
5242
// C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5243
// C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5244
// type. Note that Functions are not objects, and that (in C99 parlance)
5245
// incomplete types are not object types.
5246
if (ResultType->isFunctionType()) {
5247
Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5248
<< ResultType << BaseExpr->getSourceRange();
5249
return ExprError();
5250
}
5251
5252
if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5253
// GNU extension: subscripting on pointer to void
5254
Diag(LLoc, diag::ext_gnu_subscript_void_type)
5255
<< BaseExpr->getSourceRange();
5256
5257
// C forbids expressions of unqualified void type from being l-values.
5258
// See IsCForbiddenLValueType.
5259
if (!ResultType.hasQualifiers())
5260
VK = VK_PRValue;
5261
} else if (!ResultType->isDependentType() &&
5262
!ResultType.isWebAssemblyReferenceType() &&
5263
RequireCompleteSizedType(
5264
LLoc, ResultType,
5265
diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5266
return ExprError();
5267
5268
assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5269
!ResultType.isCForbiddenLValueType());
5270
5271
if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5272
FunctionScopes.size() > 1) {
5273
if (auto *TT =
5274
LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5275
for (auto I = FunctionScopes.rbegin(),
5276
E = std::prev(FunctionScopes.rend());
5277
I != E; ++I) {
5278
auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5279
if (CSI == nullptr)
5280
break;
5281
DeclContext *DC = nullptr;
5282
if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5283
DC = LSI->CallOperator;
5284
else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5285
DC = CRSI->TheCapturedDecl;
5286
else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5287
DC = BSI->TheDecl;
5288
if (DC) {
5289
if (DC->containsDecl(TT->getDecl()))
5290
break;
5291
captureVariablyModifiedType(
5292
Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5293
}
5294
}
5295
}
5296
}
5297
5298
return new (Context)
5299
ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5300
}
5301
5302
bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5303
ParmVarDecl *Param, Expr *RewrittenInit,
5304
bool SkipImmediateInvocations) {
5305
if (Param->hasUnparsedDefaultArg()) {
5306
assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5307
// If we've already cleared out the location for the default argument,
5308
// that means we're parsing it right now.
5309
if (!UnparsedDefaultArgLocs.count(Param)) {
5310
Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5311
Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5312
Param->setInvalidDecl();
5313
return true;
5314
}
5315
5316
Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5317
<< FD << cast<CXXRecordDecl>(FD->getDeclContext());
5318
Diag(UnparsedDefaultArgLocs[Param],
5319
diag::note_default_argument_declared_here);
5320
return true;
5321
}
5322
5323
if (Param->hasUninstantiatedDefaultArg()) {
5324
assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5325
if (InstantiateDefaultArgument(CallLoc, FD, Param))
5326
return true;
5327
}
5328
5329
Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5330
assert(Init && "default argument but no initializer?");
5331
5332
// If the default expression creates temporaries, we need to
5333
// push them to the current stack of expression temporaries so they'll
5334
// be properly destroyed.
5335
// FIXME: We should really be rebuilding the default argument with new
5336
// bound temporaries; see the comment in PR5810.
5337
// We don't need to do that with block decls, though, because
5338
// blocks in default argument expression can never capture anything.
5339
if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5340
// Set the "needs cleanups" bit regardless of whether there are
5341
// any explicit objects.
5342
Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5343
// Append all the objects to the cleanup list. Right now, this
5344
// should always be a no-op, because blocks in default argument
5345
// expressions should never be able to capture anything.
5346
assert(!InitWithCleanup->getNumObjects() &&
5347
"default argument expression has capturing blocks?");
5348
}
5349
// C++ [expr.const]p15.1:
5350
// An expression or conversion is in an immediate function context if it is
5351
// potentially evaluated and [...] its innermost enclosing non-block scope
5352
// is a function parameter scope of an immediate function.
5353
EnterExpressionEvaluationContext EvalContext(
5354
*this,
5355
FD->isImmediateFunction()
5356
? ExpressionEvaluationContext::ImmediateFunctionContext
5357
: ExpressionEvaluationContext::PotentiallyEvaluated,
5358
Param);
5359
ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5360
SkipImmediateInvocations;
5361
runWithSufficientStackSpace(CallLoc, [&] {
5362
MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5363
});
5364
return false;
5365
}
5366
5367
struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5368
const ASTContext &Context;
5369
ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
5370
5371
bool HasImmediateCalls = false;
5372
bool shouldVisitImplicitCode() const { return true; }
5373
5374
bool VisitCallExpr(CallExpr *E) {
5375
if (const FunctionDecl *FD = E->getDirectCallee())
5376
HasImmediateCalls |= FD->isImmediateFunction();
5377
return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5378
}
5379
5380
bool VisitCXXConstructExpr(CXXConstructExpr *E) {
5381
if (const FunctionDecl *FD = E->getConstructor())
5382
HasImmediateCalls |= FD->isImmediateFunction();
5383
return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5384
}
5385
5386
// SourceLocExpr are not immediate invocations
5387
// but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5388
// need to be rebuilt so that they refer to the correct SourceLocation and
5389
// DeclContext.
5390
bool VisitSourceLocExpr(SourceLocExpr *E) {
5391
HasImmediateCalls = true;
5392
return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5393
}
5394
5395
// A nested lambda might have parameters with immediate invocations
5396
// in their default arguments.
5397
// The compound statement is not visited (as it does not constitute a
5398
// subexpression).
5399
// FIXME: We should consider visiting and transforming captures
5400
// with init expressions.
5401
bool VisitLambdaExpr(LambdaExpr *E) {
5402
return VisitCXXMethodDecl(E->getCallOperator());
5403
}
5404
5405
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
5406
return TraverseStmt(E->getExpr());
5407
}
5408
5409
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
5410
return TraverseStmt(E->getExpr());
5411
}
5412
};
5413
5414
struct EnsureImmediateInvocationInDefaultArgs
5415
: TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5416
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
5417
: TreeTransform(SemaRef) {}
5418
5419
// Lambda can only have immediate invocations in the default
5420
// args of their parameters, which is transformed upon calling the closure.
5421
// The body is not a subexpression, so we have nothing to do.
5422
// FIXME: Immediate calls in capture initializers should be transformed.
5423
ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5424
ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
5425
5426
// Make sure we don't rebuild the this pointer as it would
5427
// cause it to incorrectly point it to the outermost class
5428
// in the case of nested struct initialization.
5429
ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5430
5431
// Rewrite to source location to refer to the context in which they are used.
5432
ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
5433
DeclContext *DC = E->getParentContext();
5434
if (DC == SemaRef.CurContext)
5435
return E;
5436
5437
// FIXME: During instantiation, because the rebuild of defaults arguments
5438
// is not always done in the context of the template instantiator,
5439
// we run the risk of producing a dependent source location
5440
// that would never be rebuilt.
5441
// This usually happens during overload resolution, or in contexts
5442
// where the value of the source location does not matter.
5443
// However, we should find a better way to deal with source location
5444
// of function templates.
5445
if (!SemaRef.CurrentInstantiationScope ||
5446
!SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5447
DC = SemaRef.CurContext;
5448
5449
return getDerived().RebuildSourceLocExpr(
5450
E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5451
}
5452
};
5453
5454
ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5455
FunctionDecl *FD, ParmVarDecl *Param,
5456
Expr *Init) {
5457
assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5458
5459
bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5460
bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
5461
std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5462
InitializationContext =
5463
OutermostDeclarationWithDelayedImmediateInvocations();
5464
if (!InitializationContext.has_value())
5465
InitializationContext.emplace(CallLoc, Param, CurContext);
5466
5467
if (!Init && !Param->hasUnparsedDefaultArg()) {
5468
// Mark that we are replacing a default argument first.
5469
// If we are instantiating a template we won't have to
5470
// retransform immediate calls.
5471
// C++ [expr.const]p15.1:
5472
// An expression or conversion is in an immediate function context if it
5473
// is potentially evaluated and [...] its innermost enclosing non-block
5474
// scope is a function parameter scope of an immediate function.
5475
EnterExpressionEvaluationContext EvalContext(
5476
*this,
5477
FD->isImmediateFunction()
5478
? ExpressionEvaluationContext::ImmediateFunctionContext
5479
: ExpressionEvaluationContext::PotentiallyEvaluated,
5480
Param);
5481
5482
if (Param->hasUninstantiatedDefaultArg()) {
5483
if (InstantiateDefaultArgument(CallLoc, FD, Param))
5484
return ExprError();
5485
}
5486
// CWG2631
5487
// An immediate invocation that is not evaluated where it appears is
5488
// evaluated and checked for whether it is a constant expression at the
5489
// point where the enclosing initializer is used in a function call.
5490
ImmediateCallVisitor V(getASTContext());
5491
if (!NestedDefaultChecking)
5492
V.TraverseDecl(Param);
5493
5494
// Rewrite the call argument that was created from the corresponding
5495
// parameter's default argument.
5496
if (V.HasImmediateCalls || InLifetimeExtendingContext) {
5497
if (V.HasImmediateCalls)
5498
ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5499
CallLoc, Param, CurContext};
5500
// Pass down lifetime extending flag, and collect temporaries in
5501
// CreateMaterializeTemporaryExpr when we rewrite the call argument.
5502
keepInLifetimeExtendingContext();
5503
EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5504
ExprResult Res;
5505
runWithSufficientStackSpace(CallLoc, [&] {
5506
Res = Immediate.TransformInitializer(Param->getInit(),
5507
/*NotCopy=*/false);
5508
});
5509
if (Res.isInvalid())
5510
return ExprError();
5511
Res = ConvertParamDefaultArgument(Param, Res.get(),
5512
Res.get()->getBeginLoc());
5513
if (Res.isInvalid())
5514
return ExprError();
5515
Init = Res.get();
5516
}
5517
}
5518
5519
if (CheckCXXDefaultArgExpr(
5520
CallLoc, FD, Param, Init,
5521
/*SkipImmediateInvocations=*/NestedDefaultChecking))
5522
return ExprError();
5523
5524
return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5525
Init, InitializationContext->Context);
5526
}
5527
5528
ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
5529
assert(Field->hasInClassInitializer());
5530
5531
// If we might have already tried and failed to instantiate, don't try again.
5532
if (Field->isInvalidDecl())
5533
return ExprError();
5534
5535
CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5536
5537
auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5538
5539
std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5540
InitializationContext =
5541
OutermostDeclarationWithDelayedImmediateInvocations();
5542
if (!InitializationContext.has_value())
5543
InitializationContext.emplace(Loc, Field, CurContext);
5544
5545
Expr *Init = nullptr;
5546
5547
bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5548
5549
EnterExpressionEvaluationContext EvalContext(
5550
*this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
5551
5552
if (!Field->getInClassInitializer()) {
5553
// Maybe we haven't instantiated the in-class initializer. Go check the
5554
// pattern FieldDecl to see if it has one.
5555
if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5556
CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5557
DeclContext::lookup_result Lookup =
5558
ClassPattern->lookup(Field->getDeclName());
5559
5560
FieldDecl *Pattern = nullptr;
5561
for (auto *L : Lookup) {
5562
if ((Pattern = dyn_cast<FieldDecl>(L)))
5563
break;
5564
}
5565
assert(Pattern && "We must have set the Pattern!");
5566
if (!Pattern->hasInClassInitializer() ||
5567
InstantiateInClassInitializer(Loc, Field, Pattern,
5568
getTemplateInstantiationArgs(Field))) {
5569
Field->setInvalidDecl();
5570
return ExprError();
5571
}
5572
}
5573
}
5574
5575
// CWG2631
5576
// An immediate invocation that is not evaluated where it appears is
5577
// evaluated and checked for whether it is a constant expression at the
5578
// point where the enclosing initializer is used in a [...] a constructor
5579
// definition, or an aggregate initialization.
5580
ImmediateCallVisitor V(getASTContext());
5581
if (!NestedDefaultChecking)
5582
V.TraverseDecl(Field);
5583
if (V.HasImmediateCalls) {
5584
ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5585
CurContext};
5586
ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5587
NestedDefaultChecking;
5588
5589
EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5590
ExprResult Res;
5591
runWithSufficientStackSpace(Loc, [&] {
5592
Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5593
/*CXXDirectInit=*/false);
5594
});
5595
if (!Res.isInvalid())
5596
Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5597
if (Res.isInvalid()) {
5598
Field->setInvalidDecl();
5599
return ExprError();
5600
}
5601
Init = Res.get();
5602
}
5603
5604
if (Field->getInClassInitializer()) {
5605
Expr *E = Init ? Init : Field->getInClassInitializer();
5606
if (!NestedDefaultChecking)
5607
runWithSufficientStackSpace(Loc, [&] {
5608
MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5609
});
5610
// C++11 [class.base.init]p7:
5611
// The initialization of each base and member constitutes a
5612
// full-expression.
5613
ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5614
if (Res.isInvalid()) {
5615
Field->setInvalidDecl();
5616
return ExprError();
5617
}
5618
Init = Res.get();
5619
5620
return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5621
Field, InitializationContext->Context,
5622
Init);
5623
}
5624
5625
// DR1351:
5626
// If the brace-or-equal-initializer of a non-static data member
5627
// invokes a defaulted default constructor of its class or of an
5628
// enclosing class in a potentially evaluated subexpression, the
5629
// program is ill-formed.
5630
//
5631
// This resolution is unworkable: the exception specification of the
5632
// default constructor can be needed in an unevaluated context, in
5633
// particular, in the operand of a noexcept-expression, and we can be
5634
// unable to compute an exception specification for an enclosed class.
5635
//
5636
// Any attempt to resolve the exception specification of a defaulted default
5637
// constructor before the initializer is lexically complete will ultimately
5638
// come here at which point we can diagnose it.
5639
RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5640
Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5641
<< OutermostClass << Field;
5642
Diag(Field->getEndLoc(),
5643
diag::note_default_member_initializer_not_yet_parsed);
5644
// Recover by marking the field invalid, unless we're in a SFINAE context.
5645
if (!isSFINAEContext())
5646
Field->setInvalidDecl();
5647
return ExprError();
5648
}
5649
5650
Sema::VariadicCallType
5651
Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5652
Expr *Fn) {
5653
if (Proto && Proto->isVariadic()) {
5654
if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5655
return VariadicConstructor;
5656
else if (Fn && Fn->getType()->isBlockPointerType())
5657
return VariadicBlock;
5658
else if (FDecl) {
5659
if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5660
if (Method->isInstance())
5661
return VariadicMethod;
5662
} else if (Fn && Fn->getType() == Context.BoundMemberTy)
5663
return VariadicMethod;
5664
return VariadicFunction;
5665
}
5666
return VariadicDoesNotApply;
5667
}
5668
5669
namespace {
5670
class FunctionCallCCC final : public FunctionCallFilterCCC {
5671
public:
5672
FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5673
unsigned NumArgs, MemberExpr *ME)
5674
: FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5675
FunctionName(FuncName) {}
5676
5677
bool ValidateCandidate(const TypoCorrection &candidate) override {
5678
if (!candidate.getCorrectionSpecifier() ||
5679
candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5680
return false;
5681
}
5682
5683
return FunctionCallFilterCCC::ValidateCandidate(candidate);
5684
}
5685
5686
std::unique_ptr<CorrectionCandidateCallback> clone() override {
5687
return std::make_unique<FunctionCallCCC>(*this);
5688
}
5689
5690
private:
5691
const IdentifierInfo *const FunctionName;
5692
};
5693
}
5694
5695
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5696
FunctionDecl *FDecl,
5697
ArrayRef<Expr *> Args) {
5698
MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5699
DeclarationName FuncName = FDecl->getDeclName();
5700
SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5701
5702
FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5703
if (TypoCorrection Corrected = S.CorrectTypo(
5704
DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5705
S.getScopeForContext(S.CurContext), nullptr, CCC,
5706
Sema::CTK_ErrorRecovery)) {
5707
if (NamedDecl *ND = Corrected.getFoundDecl()) {
5708
if (Corrected.isOverloaded()) {
5709
OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5710
OverloadCandidateSet::iterator Best;
5711
for (NamedDecl *CD : Corrected) {
5712
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5713
S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5714
OCS);
5715
}
5716
switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5717
case OR_Success:
5718
ND = Best->FoundDecl;
5719
Corrected.setCorrectionDecl(ND);
5720
break;
5721
default:
5722
break;
5723
}
5724
}
5725
ND = ND->getUnderlyingDecl();
5726
if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5727
return Corrected;
5728
}
5729
}
5730
return TypoCorrection();
5731
}
5732
5733
// [C++26][[expr.unary.op]/p4
5734
// A pointer to member is only formed when an explicit &
5735
// is used and its operand is a qualified-id not enclosed in parentheses.
5736
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
5737
if (!isa<ParenExpr>(Fn))
5738
return false;
5739
5740
Fn = Fn->IgnoreParens();
5741
5742
auto *UO = dyn_cast<UnaryOperator>(Fn);
5743
if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5744
return false;
5745
if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5746
return DRE->hasQualifier();
5747
}
5748
if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5749
return OVL->getQualifier();
5750
return false;
5751
}
5752
5753
bool
5754
Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5755
FunctionDecl *FDecl,
5756
const FunctionProtoType *Proto,
5757
ArrayRef<Expr *> Args,
5758
SourceLocation RParenLoc,
5759
bool IsExecConfig) {
5760
// Bail out early if calling a builtin with custom typechecking.
5761
if (FDecl)
5762
if (unsigned ID = FDecl->getBuiltinID())
5763
if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5764
return false;
5765
5766
// C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5767
// assignment, to the types of the corresponding parameter, ...
5768
5769
bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5770
bool HasExplicitObjectParameter =
5771
!AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5772
unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5773
unsigned NumParams = Proto->getNumParams();
5774
bool Invalid = false;
5775
unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5776
unsigned FnKind = Fn->getType()->isBlockPointerType()
5777
? 1 /* block */
5778
: (IsExecConfig ? 3 /* kernel function (exec config) */
5779
: 0 /* function */);
5780
5781
// If too few arguments are available (and we don't have default
5782
// arguments for the remaining parameters), don't make the call.
5783
if (Args.size() < NumParams) {
5784
if (Args.size() < MinArgs) {
5785
TypoCorrection TC;
5786
if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5787
unsigned diag_id =
5788
MinArgs == NumParams && !Proto->isVariadic()
5789
? diag::err_typecheck_call_too_few_args_suggest
5790
: diag::err_typecheck_call_too_few_args_at_least_suggest;
5791
diagnoseTypo(
5792
TC, PDiag(diag_id)
5793
<< FnKind << MinArgs - ExplicitObjectParameterOffset
5794
<< static_cast<unsigned>(Args.size()) -
5795
ExplicitObjectParameterOffset
5796
<< HasExplicitObjectParameter << TC.getCorrectionRange());
5797
} else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5798
FDecl->getParamDecl(ExplicitObjectParameterOffset)
5799
->getDeclName())
5800
Diag(RParenLoc,
5801
MinArgs == NumParams && !Proto->isVariadic()
5802
? diag::err_typecheck_call_too_few_args_one
5803
: diag::err_typecheck_call_too_few_args_at_least_one)
5804
<< FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5805
<< HasExplicitObjectParameter << Fn->getSourceRange();
5806
else
5807
Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5808
? diag::err_typecheck_call_too_few_args
5809
: diag::err_typecheck_call_too_few_args_at_least)
5810
<< FnKind << MinArgs - ExplicitObjectParameterOffset
5811
<< static_cast<unsigned>(Args.size()) -
5812
ExplicitObjectParameterOffset
5813
<< HasExplicitObjectParameter << Fn->getSourceRange();
5814
5815
// Emit the location of the prototype.
5816
if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5817
Diag(FDecl->getLocation(), diag::note_callee_decl)
5818
<< FDecl << FDecl->getParametersSourceRange();
5819
5820
return true;
5821
}
5822
// We reserve space for the default arguments when we create
5823
// the call expression, before calling ConvertArgumentsForCall.
5824
assert((Call->getNumArgs() == NumParams) &&
5825
"We should have reserved space for the default arguments before!");
5826
}
5827
5828
// If too many are passed and not variadic, error on the extras and drop
5829
// them.
5830
if (Args.size() > NumParams) {
5831
if (!Proto->isVariadic()) {
5832
TypoCorrection TC;
5833
if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5834
unsigned diag_id =
5835
MinArgs == NumParams && !Proto->isVariadic()
5836
? diag::err_typecheck_call_too_many_args_suggest
5837
: diag::err_typecheck_call_too_many_args_at_most_suggest;
5838
diagnoseTypo(
5839
TC, PDiag(diag_id)
5840
<< FnKind << NumParams - ExplicitObjectParameterOffset
5841
<< static_cast<unsigned>(Args.size()) -
5842
ExplicitObjectParameterOffset
5843
<< HasExplicitObjectParameter << TC.getCorrectionRange());
5844
} else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5845
FDecl->getParamDecl(ExplicitObjectParameterOffset)
5846
->getDeclName())
5847
Diag(Args[NumParams]->getBeginLoc(),
5848
MinArgs == NumParams
5849
? diag::err_typecheck_call_too_many_args_one
5850
: diag::err_typecheck_call_too_many_args_at_most_one)
5851
<< FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5852
<< static_cast<unsigned>(Args.size()) -
5853
ExplicitObjectParameterOffset
5854
<< HasExplicitObjectParameter << Fn->getSourceRange()
5855
<< SourceRange(Args[NumParams]->getBeginLoc(),
5856
Args.back()->getEndLoc());
5857
else
5858
Diag(Args[NumParams]->getBeginLoc(),
5859
MinArgs == NumParams
5860
? diag::err_typecheck_call_too_many_args
5861
: diag::err_typecheck_call_too_many_args_at_most)
5862
<< FnKind << NumParams - ExplicitObjectParameterOffset
5863
<< static_cast<unsigned>(Args.size()) -
5864
ExplicitObjectParameterOffset
5865
<< HasExplicitObjectParameter << Fn->getSourceRange()
5866
<< SourceRange(Args[NumParams]->getBeginLoc(),
5867
Args.back()->getEndLoc());
5868
5869
// Emit the location of the prototype.
5870
if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5871
Diag(FDecl->getLocation(), diag::note_callee_decl)
5872
<< FDecl << FDecl->getParametersSourceRange();
5873
5874
// This deletes the extra arguments.
5875
Call->shrinkNumArgs(NumParams);
5876
return true;
5877
}
5878
}
5879
SmallVector<Expr *, 8> AllArgs;
5880
VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5881
5882
Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5883
AllArgs, CallType);
5884
if (Invalid)
5885
return true;
5886
unsigned TotalNumArgs = AllArgs.size();
5887
for (unsigned i = 0; i < TotalNumArgs; ++i)
5888
Call->setArg(i, AllArgs[i]);
5889
5890
Call->computeDependence();
5891
return false;
5892
}
5893
5894
bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5895
const FunctionProtoType *Proto,
5896
unsigned FirstParam, ArrayRef<Expr *> Args,
5897
SmallVectorImpl<Expr *> &AllArgs,
5898
VariadicCallType CallType, bool AllowExplicit,
5899
bool IsListInitialization) {
5900
unsigned NumParams = Proto->getNumParams();
5901
bool Invalid = false;
5902
size_t ArgIx = 0;
5903
// Continue to check argument types (even if we have too few/many args).
5904
for (unsigned i = FirstParam; i < NumParams; i++) {
5905
QualType ProtoArgType = Proto->getParamType(i);
5906
5907
Expr *Arg;
5908
ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5909
if (ArgIx < Args.size()) {
5910
Arg = Args[ArgIx++];
5911
5912
if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5913
diag::err_call_incomplete_argument, Arg))
5914
return true;
5915
5916
// Strip the unbridged-cast placeholder expression off, if applicable.
5917
bool CFAudited = false;
5918
if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5919
FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5920
(!Param || !Param->hasAttr<CFConsumedAttr>()))
5921
Arg = ObjC().stripARCUnbridgedCast(Arg);
5922
else if (getLangOpts().ObjCAutoRefCount &&
5923
FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5924
(!Param || !Param->hasAttr<CFConsumedAttr>()))
5925
CFAudited = true;
5926
5927
if (Proto->getExtParameterInfo(i).isNoEscape() &&
5928
ProtoArgType->isBlockPointerType())
5929
if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5930
BE->getBlockDecl()->setDoesNotEscape();
5931
5932
InitializedEntity Entity =
5933
Param ? InitializedEntity::InitializeParameter(Context, Param,
5934
ProtoArgType)
5935
: InitializedEntity::InitializeParameter(
5936
Context, ProtoArgType, Proto->isParamConsumed(i));
5937
5938
// Remember that parameter belongs to a CF audited API.
5939
if (CFAudited)
5940
Entity.setParameterCFAudited();
5941
5942
ExprResult ArgE = PerformCopyInitialization(
5943
Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5944
if (ArgE.isInvalid())
5945
return true;
5946
5947
Arg = ArgE.getAs<Expr>();
5948
} else {
5949
assert(Param && "can't use default arguments without a known callee");
5950
5951
ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5952
if (ArgExpr.isInvalid())
5953
return true;
5954
5955
Arg = ArgExpr.getAs<Expr>();
5956
}
5957
5958
// Check for array bounds violations for each argument to the call. This
5959
// check only triggers warnings when the argument isn't a more complex Expr
5960
// with its own checking, such as a BinaryOperator.
5961
CheckArrayAccess(Arg);
5962
5963
// Check for violations of C99 static array rules (C99 6.7.5.3p7).
5964
CheckStaticArrayArgument(CallLoc, Param, Arg);
5965
5966
AllArgs.push_back(Arg);
5967
}
5968
5969
// If this is a variadic call, handle args passed through "...".
5970
if (CallType != VariadicDoesNotApply) {
5971
// Assume that extern "C" functions with variadic arguments that
5972
// return __unknown_anytype aren't *really* variadic.
5973
if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5974
FDecl->isExternC()) {
5975
for (Expr *A : Args.slice(ArgIx)) {
5976
QualType paramType; // ignored
5977
ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5978
Invalid |= arg.isInvalid();
5979
AllArgs.push_back(arg.get());
5980
}
5981
5982
// Otherwise do argument promotion, (C99 6.5.2.2p7).
5983
} else {
5984
for (Expr *A : Args.slice(ArgIx)) {
5985
ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5986
Invalid |= Arg.isInvalid();
5987
AllArgs.push_back(Arg.get());
5988
}
5989
}
5990
5991
// Check for array bounds violations.
5992
for (Expr *A : Args.slice(ArgIx))
5993
CheckArrayAccess(A);
5994
}
5995
return Invalid;
5996
}
5997
5998
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5999
TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6000
if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6001
TL = DTL.getOriginalLoc();
6002
if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6003
S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6004
<< ATL.getLocalSourceRange();
6005
}
6006
6007
void
6008
Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6009
ParmVarDecl *Param,
6010
const Expr *ArgExpr) {
6011
// Static array parameters are not supported in C++.
6012
if (!Param || getLangOpts().CPlusPlus)
6013
return;
6014
6015
QualType OrigTy = Param->getOriginalType();
6016
6017
const ArrayType *AT = Context.getAsArrayType(OrigTy);
6018
if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6019
return;
6020
6021
if (ArgExpr->isNullPointerConstant(Context,
6022
Expr::NPC_NeverValueDependent)) {
6023
Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6024
DiagnoseCalleeStaticArrayParam(*this, Param);
6025
return;
6026
}
6027
6028
const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6029
if (!CAT)
6030
return;
6031
6032
const ConstantArrayType *ArgCAT =
6033
Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6034
if (!ArgCAT)
6035
return;
6036
6037
if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6038
ArgCAT->getElementType())) {
6039
if (ArgCAT->getSize().ult(CAT->getSize())) {
6040
Diag(CallLoc, diag::warn_static_array_too_small)
6041
<< ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6042
<< (unsigned)CAT->getZExtSize() << 0;
6043
DiagnoseCalleeStaticArrayParam(*this, Param);
6044
}
6045
return;
6046
}
6047
6048
std::optional<CharUnits> ArgSize =
6049
getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6050
std::optional<CharUnits> ParmSize =
6051
getASTContext().getTypeSizeInCharsIfKnown(CAT);
6052
if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6053
Diag(CallLoc, diag::warn_static_array_too_small)
6054
<< ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6055
<< (unsigned)ParmSize->getQuantity() << 1;
6056
DiagnoseCalleeStaticArrayParam(*this, Param);
6057
}
6058
}
6059
6060
/// Given a function expression of unknown-any type, try to rebuild it
6061
/// to have a function type.
6062
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6063
6064
/// Is the given type a placeholder that we need to lower out
6065
/// immediately during argument processing?
6066
static bool isPlaceholderToRemoveAsArg(QualType type) {
6067
// Placeholders are never sugared.
6068
const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6069
if (!placeholder) return false;
6070
6071
switch (placeholder->getKind()) {
6072
// Ignore all the non-placeholder types.
6073
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6074
case BuiltinType::Id:
6075
#include "clang/Basic/OpenCLImageTypes.def"
6076
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6077
case BuiltinType::Id:
6078
#include "clang/Basic/OpenCLExtensionTypes.def"
6079
// In practice we'll never use this, since all SVE types are sugared
6080
// via TypedefTypes rather than exposed directly as BuiltinTypes.
6081
#define SVE_TYPE(Name, Id, SingletonId) \
6082
case BuiltinType::Id:
6083
#include "clang/Basic/AArch64SVEACLETypes.def"
6084
#define PPC_VECTOR_TYPE(Name, Id, Size) \
6085
case BuiltinType::Id:
6086
#include "clang/Basic/PPCTypes.def"
6087
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6088
#include "clang/Basic/RISCVVTypes.def"
6089
#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6090
#include "clang/Basic/WebAssemblyReferenceTypes.def"
6091
#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6092
#include "clang/Basic/AMDGPUTypes.def"
6093
#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6094
#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6095
#include "clang/AST/BuiltinTypes.def"
6096
return false;
6097
6098
case BuiltinType::UnresolvedTemplate:
6099
// We cannot lower out overload sets; they might validly be resolved
6100
// by the call machinery.
6101
case BuiltinType::Overload:
6102
return false;
6103
6104
// Unbridged casts in ARC can be handled in some call positions and
6105
// should be left in place.
6106
case BuiltinType::ARCUnbridgedCast:
6107
return false;
6108
6109
// Pseudo-objects should be converted as soon as possible.
6110
case BuiltinType::PseudoObject:
6111
return true;
6112
6113
// The debugger mode could theoretically but currently does not try
6114
// to resolve unknown-typed arguments based on known parameter types.
6115
case BuiltinType::UnknownAny:
6116
return true;
6117
6118
// These are always invalid as call arguments and should be reported.
6119
case BuiltinType::BoundMember:
6120
case BuiltinType::BuiltinFn:
6121
case BuiltinType::IncompleteMatrixIdx:
6122
case BuiltinType::ArraySection:
6123
case BuiltinType::OMPArrayShaping:
6124
case BuiltinType::OMPIterator:
6125
return true;
6126
6127
}
6128
llvm_unreachable("bad builtin type kind");
6129
}
6130
6131
bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
6132
// Apply this processing to all the arguments at once instead of
6133
// dying at the first failure.
6134
bool hasInvalid = false;
6135
for (size_t i = 0, e = args.size(); i != e; i++) {
6136
if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6137
ExprResult result = CheckPlaceholderExpr(args[i]);
6138
if (result.isInvalid()) hasInvalid = true;
6139
else args[i] = result.get();
6140
}
6141
}
6142
return hasInvalid;
6143
}
6144
6145
/// If a builtin function has a pointer argument with no explicit address
6146
/// space, then it should be able to accept a pointer to any address
6147
/// space as input. In order to do this, we need to replace the
6148
/// standard builtin declaration with one that uses the same address space
6149
/// as the call.
6150
///
6151
/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6152
/// it does not contain any pointer arguments without
6153
/// an address space qualifer. Otherwise the rewritten
6154
/// FunctionDecl is returned.
6155
/// TODO: Handle pointer return types.
6156
static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6157
FunctionDecl *FDecl,
6158
MultiExprArg ArgExprs) {
6159
6160
QualType DeclType = FDecl->getType();
6161
const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6162
6163
if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6164
ArgExprs.size() < FT->getNumParams())
6165
return nullptr;
6166
6167
bool NeedsNewDecl = false;
6168
unsigned i = 0;
6169
SmallVector<QualType, 8> OverloadParams;
6170
6171
for (QualType ParamType : FT->param_types()) {
6172
6173
// Convert array arguments to pointer to simplify type lookup.
6174
ExprResult ArgRes =
6175
Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6176
if (ArgRes.isInvalid())
6177
return nullptr;
6178
Expr *Arg = ArgRes.get();
6179
QualType ArgType = Arg->getType();
6180
if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6181
!ArgType->isPointerType() ||
6182
!ArgType->getPointeeType().hasAddressSpace() ||
6183
isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6184
OverloadParams.push_back(ParamType);
6185
continue;
6186
}
6187
6188
QualType PointeeType = ParamType->getPointeeType();
6189
if (PointeeType.hasAddressSpace())
6190
continue;
6191
6192
NeedsNewDecl = true;
6193
LangAS AS = ArgType->getPointeeType().getAddressSpace();
6194
6195
PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6196
OverloadParams.push_back(Context.getPointerType(PointeeType));
6197
}
6198
6199
if (!NeedsNewDecl)
6200
return nullptr;
6201
6202
FunctionProtoType::ExtProtoInfo EPI;
6203
EPI.Variadic = FT->isVariadic();
6204
QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6205
OverloadParams, EPI);
6206
DeclContext *Parent = FDecl->getParent();
6207
FunctionDecl *OverloadDecl = FunctionDecl::Create(
6208
Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6209
FDecl->getIdentifier(), OverloadTy,
6210
/*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6211
false,
6212
/*hasPrototype=*/true);
6213
SmallVector<ParmVarDecl*, 16> Params;
6214
FT = cast<FunctionProtoType>(OverloadTy);
6215
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6216
QualType ParamType = FT->getParamType(i);
6217
ParmVarDecl *Parm =
6218
ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6219
SourceLocation(), nullptr, ParamType,
6220
/*TInfo=*/nullptr, SC_None, nullptr);
6221
Parm->setScopeInfo(0, i);
6222
Params.push_back(Parm);
6223
}
6224
OverloadDecl->setParams(Params);
6225
Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6226
return OverloadDecl;
6227
}
6228
6229
static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6230
FunctionDecl *Callee,
6231
MultiExprArg ArgExprs) {
6232
// `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6233
// similar attributes) really don't like it when functions are called with an
6234
// invalid number of args.
6235
if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6236
/*PartialOverloading=*/false) &&
6237
!Callee->isVariadic())
6238
return;
6239
if (Callee->getMinRequiredArguments() > ArgExprs.size())
6240
return;
6241
6242
if (const EnableIfAttr *Attr =
6243
S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6244
S.Diag(Fn->getBeginLoc(),
6245
isa<CXXMethodDecl>(Callee)
6246
? diag::err_ovl_no_viable_member_function_in_call
6247
: diag::err_ovl_no_viable_function_in_call)
6248
<< Callee << Callee->getSourceRange();
6249
S.Diag(Callee->getLocation(),
6250
diag::note_ovl_candidate_disabled_by_function_cond_attr)
6251
<< Attr->getCond()->getSourceRange() << Attr->getMessage();
6252
return;
6253
}
6254
}
6255
6256
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6257
const UnresolvedMemberExpr *const UME, Sema &S) {
6258
6259
const auto GetFunctionLevelDCIfCXXClass =
6260
[](Sema &S) -> const CXXRecordDecl * {
6261
const DeclContext *const DC = S.getFunctionLevelDeclContext();
6262
if (!DC || !DC->getParent())
6263
return nullptr;
6264
6265
// If the call to some member function was made from within a member
6266
// function body 'M' return return 'M's parent.
6267
if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6268
return MD->getParent()->getCanonicalDecl();
6269
// else the call was made from within a default member initializer of a
6270
// class, so return the class.
6271
if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6272
return RD->getCanonicalDecl();
6273
return nullptr;
6274
};
6275
// If our DeclContext is neither a member function nor a class (in the
6276
// case of a lambda in a default member initializer), we can't have an
6277
// enclosing 'this'.
6278
6279
const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6280
if (!CurParentClass)
6281
return false;
6282
6283
// The naming class for implicit member functions call is the class in which
6284
// name lookup starts.
6285
const CXXRecordDecl *const NamingClass =
6286
UME->getNamingClass()->getCanonicalDecl();
6287
assert(NamingClass && "Must have naming class even for implicit access");
6288
6289
// If the unresolved member functions were found in a 'naming class' that is
6290
// related (either the same or derived from) to the class that contains the
6291
// member function that itself contained the implicit member access.
6292
6293
return CurParentClass == NamingClass ||
6294
CurParentClass->isDerivedFrom(NamingClass);
6295
}
6296
6297
static void
6298
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6299
Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6300
6301
if (!UME)
6302
return;
6303
6304
LambdaScopeInfo *const CurLSI = S.getCurLambda();
6305
// Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6306
// already been captured, or if this is an implicit member function call (if
6307
// it isn't, an attempt to capture 'this' should already have been made).
6308
if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6309
!UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6310
return;
6311
6312
// Check if the naming class in which the unresolved members were found is
6313
// related (same as or is a base of) to the enclosing class.
6314
6315
if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6316
return;
6317
6318
6319
DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6320
// If the enclosing function is not dependent, then this lambda is
6321
// capture ready, so if we can capture this, do so.
6322
if (!EnclosingFunctionCtx->isDependentContext()) {
6323
// If the current lambda and all enclosing lambdas can capture 'this' -
6324
// then go ahead and capture 'this' (since our unresolved overload set
6325
// contains at least one non-static member function).
6326
if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6327
S.CheckCXXThisCapture(CallLoc);
6328
} else if (S.CurContext->isDependentContext()) {
6329
// ... since this is an implicit member reference, that might potentially
6330
// involve a 'this' capture, mark 'this' for potential capture in
6331
// enclosing lambdas.
6332
if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6333
CurLSI->addPotentialThisCapture(CallLoc);
6334
}
6335
}
6336
6337
// Once a call is fully resolved, warn for unqualified calls to specific
6338
// C++ standard functions, like move and forward.
6339
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
6340
const CallExpr *Call) {
6341
// We are only checking unary move and forward so exit early here.
6342
if (Call->getNumArgs() != 1)
6343
return;
6344
6345
const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6346
if (!E || isa<UnresolvedLookupExpr>(E))
6347
return;
6348
const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6349
if (!DRE || !DRE->getLocation().isValid())
6350
return;
6351
6352
if (DRE->getQualifier())
6353
return;
6354
6355
const FunctionDecl *FD = Call->getDirectCallee();
6356
if (!FD)
6357
return;
6358
6359
// Only warn for some functions deemed more frequent or problematic.
6360
unsigned BuiltinID = FD->getBuiltinID();
6361
if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6362
return;
6363
6364
S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6365
<< FD->getQualifiedNameAsString()
6366
<< FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6367
}
6368
6369
ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6370
MultiExprArg ArgExprs, SourceLocation RParenLoc,
6371
Expr *ExecConfig) {
6372
ExprResult Call =
6373
BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6374
/*IsExecConfig=*/false, /*AllowRecovery=*/true);
6375
if (Call.isInvalid())
6376
return Call;
6377
6378
// Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6379
// language modes.
6380
if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6381
ULE && ULE->hasExplicitTemplateArgs() &&
6382
ULE->decls_begin() == ULE->decls_end()) {
6383
Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6384
? diag::warn_cxx17_compat_adl_only_template_id
6385
: diag::ext_adl_only_template_id)
6386
<< ULE->getName();
6387
}
6388
6389
if (LangOpts.OpenMP)
6390
Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6391
ExecConfig);
6392
if (LangOpts.CPlusPlus) {
6393
if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6394
DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6395
6396
// If we previously found that the id-expression of this call refers to a
6397
// consteval function but the call is dependent, we should not treat is an
6398
// an invalid immediate call.
6399
if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6400
DRE && Call.get()->isValueDependent()) {
6401
currentEvaluationContext().ReferenceToConsteval.erase(DRE);
6402
}
6403
}
6404
return Call;
6405
}
6406
6407
ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6408
MultiExprArg ArgExprs, SourceLocation RParenLoc,
6409
Expr *ExecConfig, bool IsExecConfig,
6410
bool AllowRecovery) {
6411
// Since this might be a postfix expression, get rid of ParenListExprs.
6412
ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6413
if (Result.isInvalid()) return ExprError();
6414
Fn = Result.get();
6415
6416
if (CheckArgsForPlaceholders(ArgExprs))
6417
return ExprError();
6418
6419
if (getLangOpts().CPlusPlus) {
6420
// If this is a pseudo-destructor expression, build the call immediately.
6421
if (isa<CXXPseudoDestructorExpr>(Fn)) {
6422
if (!ArgExprs.empty()) {
6423
// Pseudo-destructor calls should not have any arguments.
6424
Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6425
<< FixItHint::CreateRemoval(
6426
SourceRange(ArgExprs.front()->getBeginLoc(),
6427
ArgExprs.back()->getEndLoc()));
6428
}
6429
6430
return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6431
VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6432
}
6433
if (Fn->getType() == Context.PseudoObjectTy) {
6434
ExprResult result = CheckPlaceholderExpr(Fn);
6435
if (result.isInvalid()) return ExprError();
6436
Fn = result.get();
6437
}
6438
6439
// Determine whether this is a dependent call inside a C++ template,
6440
// in which case we won't do any semantic analysis now.
6441
if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6442
if (ExecConfig) {
6443
return CUDAKernelCallExpr::Create(Context, Fn,
6444
cast<CallExpr>(ExecConfig), ArgExprs,
6445
Context.DependentTy, VK_PRValue,
6446
RParenLoc, CurFPFeatureOverrides());
6447
} else {
6448
6449
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6450
*this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6451
Fn->getBeginLoc());
6452
6453
return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6454
VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6455
}
6456
}
6457
6458
// Determine whether this is a call to an object (C++ [over.call.object]).
6459
if (Fn->getType()->isRecordType())
6460
return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6461
RParenLoc);
6462
6463
if (Fn->getType() == Context.UnknownAnyTy) {
6464
ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6465
if (result.isInvalid()) return ExprError();
6466
Fn = result.get();
6467
}
6468
6469
if (Fn->getType() == Context.BoundMemberTy) {
6470
return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6471
RParenLoc, ExecConfig, IsExecConfig,
6472
AllowRecovery);
6473
}
6474
}
6475
6476
// Check for overloaded calls. This can happen even in C due to extensions.
6477
if (Fn->getType() == Context.OverloadTy) {
6478
OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6479
6480
// We aren't supposed to apply this logic if there's an '&' involved.
6481
if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {
6482
if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6483
return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6484
VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6485
OverloadExpr *ovl = find.Expression;
6486
if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6487
return BuildOverloadedCallExpr(
6488
Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6489
/*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6490
return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6491
RParenLoc, ExecConfig, IsExecConfig,
6492
AllowRecovery);
6493
}
6494
}
6495
6496
// If we're directly calling a function, get the appropriate declaration.
6497
if (Fn->getType() == Context.UnknownAnyTy) {
6498
ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6499
if (result.isInvalid()) return ExprError();
6500
Fn = result.get();
6501
}
6502
6503
Expr *NakedFn = Fn->IgnoreParens();
6504
6505
bool CallingNDeclIndirectly = false;
6506
NamedDecl *NDecl = nullptr;
6507
if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6508
if (UnOp->getOpcode() == UO_AddrOf) {
6509
CallingNDeclIndirectly = true;
6510
NakedFn = UnOp->getSubExpr()->IgnoreParens();
6511
}
6512
}
6513
6514
if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6515
NDecl = DRE->getDecl();
6516
6517
FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6518
if (FDecl && FDecl->getBuiltinID()) {
6519
// Rewrite the function decl for this builtin by replacing parameters
6520
// with no explicit address space with the address space of the arguments
6521
// in ArgExprs.
6522
if ((FDecl =
6523
rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6524
NDecl = FDecl;
6525
Fn = DeclRefExpr::Create(
6526
Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6527
SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6528
nullptr, DRE->isNonOdrUse());
6529
}
6530
}
6531
} else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6532
NDecl = ME->getMemberDecl();
6533
6534
if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6535
if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6536
FD, /*Complain=*/true, Fn->getBeginLoc()))
6537
return ExprError();
6538
6539
checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6540
6541
// If this expression is a call to a builtin function in HIP device
6542
// compilation, allow a pointer-type argument to default address space to be
6543
// passed as a pointer-type parameter to a non-default address space.
6544
// If Arg is declared in the default address space and Param is declared
6545
// in a non-default address space, perform an implicit address space cast to
6546
// the parameter type.
6547
if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6548
FD->getBuiltinID()) {
6549
for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6550
++Idx) {
6551
ParmVarDecl *Param = FD->getParamDecl(Idx);
6552
if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6553
!ArgExprs[Idx]->getType()->isPointerType())
6554
continue;
6555
6556
auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6557
auto ArgTy = ArgExprs[Idx]->getType();
6558
auto ArgPtTy = ArgTy->getPointeeType();
6559
auto ArgAS = ArgPtTy.getAddressSpace();
6560
6561
// Add address space cast if target address spaces are different
6562
bool NeedImplicitASC =
6563
ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6564
( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6565
// or from specific AS which has target AS matching that of Param.
6566
getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6567
if (!NeedImplicitASC)
6568
continue;
6569
6570
// First, ensure that the Arg is an RValue.
6571
if (ArgExprs[Idx]->isGLValue()) {
6572
ArgExprs[Idx] = ImplicitCastExpr::Create(
6573
Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6574
nullptr, VK_PRValue, FPOptionsOverride());
6575
}
6576
6577
// Construct a new arg type with address space of Param
6578
Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6579
ArgPtQuals.setAddressSpace(ParamAS);
6580
auto NewArgPtTy =
6581
Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6582
auto NewArgTy =
6583
Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6584
ArgTy.getQualifiers());
6585
6586
// Finally perform an implicit address space cast
6587
ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6588
CK_AddressSpaceConversion)
6589
.get();
6590
}
6591
}
6592
}
6593
6594
if (Context.isDependenceAllowed() &&
6595
(Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6596
assert(!getLangOpts().CPlusPlus);
6597
assert((Fn->containsErrors() ||
6598
llvm::any_of(ArgExprs,
6599
[](clang::Expr *E) { return E->containsErrors(); })) &&
6600
"should only occur in error-recovery path.");
6601
return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6602
VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6603
}
6604
return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6605
ExecConfig, IsExecConfig);
6606
}
6607
6608
Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6609
MultiExprArg CallArgs) {
6610
StringRef Name = Context.BuiltinInfo.getName(Id);
6611
LookupResult R(*this, &Context.Idents.get(Name), Loc,
6612
Sema::LookupOrdinaryName);
6613
LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6614
6615
auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6616
assert(BuiltInDecl && "failed to find builtin declaration");
6617
6618
ExprResult DeclRef =
6619
BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6620
assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6621
6622
ExprResult Call =
6623
BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6624
6625
assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6626
return Call.get();
6627
}
6628
6629
ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6630
SourceLocation BuiltinLoc,
6631
SourceLocation RParenLoc) {
6632
QualType DstTy = GetTypeFromParser(ParsedDestTy);
6633
return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6634
}
6635
6636
ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6637
SourceLocation BuiltinLoc,
6638
SourceLocation RParenLoc) {
6639
ExprValueKind VK = VK_PRValue;
6640
ExprObjectKind OK = OK_Ordinary;
6641
QualType SrcTy = E->getType();
6642
if (!SrcTy->isDependentType() &&
6643
Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6644
return ExprError(
6645
Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6646
<< DestTy << SrcTy << E->getSourceRange());
6647
return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6648
}
6649
6650
ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6651
SourceLocation BuiltinLoc,
6652
SourceLocation RParenLoc) {
6653
TypeSourceInfo *TInfo;
6654
GetTypeFromParser(ParsedDestTy, &TInfo);
6655
return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6656
}
6657
6658
ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6659
SourceLocation LParenLoc,
6660
ArrayRef<Expr *> Args,
6661
SourceLocation RParenLoc, Expr *Config,
6662
bool IsExecConfig, ADLCallKind UsesADL) {
6663
FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6664
unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6665
6666
// Functions with 'interrupt' attribute cannot be called directly.
6667
if (FDecl) {
6668
if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6669
Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6670
return ExprError();
6671
}
6672
if (FDecl->hasAttr<ARMInterruptAttr>()) {
6673
Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6674
return ExprError();
6675
}
6676
}
6677
6678
// X86 interrupt handlers may only call routines with attribute
6679
// no_caller_saved_registers since there is no efficient way to
6680
// save and restore the non-GPR state.
6681
if (auto *Caller = getCurFunctionDecl()) {
6682
if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6683
Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6684
const TargetInfo &TI = Context.getTargetInfo();
6685
bool HasNonGPRRegisters =
6686
TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6687
if (HasNonGPRRegisters &&
6688
(!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6689
Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6690
<< (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6691
if (FDecl)
6692
Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6693
}
6694
}
6695
}
6696
6697
// Promote the function operand.
6698
// We special-case function promotion here because we only allow promoting
6699
// builtin functions to function pointers in the callee of a call.
6700
ExprResult Result;
6701
QualType ResultTy;
6702
if (BuiltinID &&
6703
Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6704
// Extract the return type from the (builtin) function pointer type.
6705
// FIXME Several builtins still have setType in
6706
// Sema::CheckBuiltinFunctionCall. One should review their definitions in
6707
// Builtins.td to ensure they are correct before removing setType calls.
6708
QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6709
Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6710
ResultTy = FDecl->getCallResultType();
6711
} else {
6712
Result = CallExprUnaryConversions(Fn);
6713
ResultTy = Context.BoolTy;
6714
}
6715
if (Result.isInvalid())
6716
return ExprError();
6717
Fn = Result.get();
6718
6719
// Check for a valid function type, but only if it is not a builtin which
6720
// requires custom type checking. These will be handled by
6721
// CheckBuiltinFunctionCall below just after creation of the call expression.
6722
const FunctionType *FuncT = nullptr;
6723
if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6724
retry:
6725
if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6726
// C99 6.5.2.2p1 - "The expression that denotes the called function shall
6727
// have type pointer to function".
6728
FuncT = PT->getPointeeType()->getAs<FunctionType>();
6729
if (!FuncT)
6730
return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6731
<< Fn->getType() << Fn->getSourceRange());
6732
} else if (const BlockPointerType *BPT =
6733
Fn->getType()->getAs<BlockPointerType>()) {
6734
FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6735
} else {
6736
// Handle calls to expressions of unknown-any type.
6737
if (Fn->getType() == Context.UnknownAnyTy) {
6738
ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6739
if (rewrite.isInvalid())
6740
return ExprError();
6741
Fn = rewrite.get();
6742
goto retry;
6743
}
6744
6745
return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6746
<< Fn->getType() << Fn->getSourceRange());
6747
}
6748
}
6749
6750
// Get the number of parameters in the function prototype, if any.
6751
// We will allocate space for max(Args.size(), NumParams) arguments
6752
// in the call expression.
6753
const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6754
unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6755
6756
CallExpr *TheCall;
6757
if (Config) {
6758
assert(UsesADL == ADLCallKind::NotADL &&
6759
"CUDAKernelCallExpr should not use ADL");
6760
TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6761
Args, ResultTy, VK_PRValue, RParenLoc,
6762
CurFPFeatureOverrides(), NumParams);
6763
} else {
6764
TheCall =
6765
CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6766
CurFPFeatureOverrides(), NumParams, UsesADL);
6767
}
6768
6769
if (!Context.isDependenceAllowed()) {
6770
// Forget about the nulled arguments since typo correction
6771
// do not handle them well.
6772
TheCall->shrinkNumArgs(Args.size());
6773
// C cannot always handle TypoExpr nodes in builtin calls and direct
6774
// function calls as their argument checking don't necessarily handle
6775
// dependent types properly, so make sure any TypoExprs have been
6776
// dealt with.
6777
ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6778
if (!Result.isUsable()) return ExprError();
6779
CallExpr *TheOldCall = TheCall;
6780
TheCall = dyn_cast<CallExpr>(Result.get());
6781
bool CorrectedTypos = TheCall != TheOldCall;
6782
if (!TheCall) return Result;
6783
Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6784
6785
// A new call expression node was created if some typos were corrected.
6786
// However it may not have been constructed with enough storage. In this
6787
// case, rebuild the node with enough storage. The waste of space is
6788
// immaterial since this only happens when some typos were corrected.
6789
if (CorrectedTypos && Args.size() < NumParams) {
6790
if (Config)
6791
TheCall = CUDAKernelCallExpr::Create(
6792
Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6793
RParenLoc, CurFPFeatureOverrides(), NumParams);
6794
else
6795
TheCall =
6796
CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6797
CurFPFeatureOverrides(), NumParams, UsesADL);
6798
}
6799
// We can now handle the nulled arguments for the default arguments.
6800
TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6801
}
6802
6803
// Bail out early if calling a builtin with custom type checking.
6804
if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6805
ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6806
if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6807
E = CheckForImmediateInvocation(E, FDecl);
6808
return E;
6809
}
6810
6811
if (getLangOpts().CUDA) {
6812
if (Config) {
6813
// CUDA: Kernel calls must be to global functions
6814
if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6815
return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6816
<< FDecl << Fn->getSourceRange());
6817
6818
// CUDA: Kernel function must have 'void' return type
6819
if (!FuncT->getReturnType()->isVoidType() &&
6820
!FuncT->getReturnType()->getAs<AutoType>() &&
6821
!FuncT->getReturnType()->isInstantiationDependentType())
6822
return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6823
<< Fn->getType() << Fn->getSourceRange());
6824
} else {
6825
// CUDA: Calls to global functions must be configured
6826
if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6827
return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6828
<< FDecl << Fn->getSourceRange());
6829
}
6830
}
6831
6832
// Check for a valid return type
6833
if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6834
FDecl))
6835
return ExprError();
6836
6837
// We know the result type of the call, set it.
6838
TheCall->setType(FuncT->getCallResultType(Context));
6839
TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6840
6841
// WebAssembly tables can't be used as arguments.
6842
if (Context.getTargetInfo().getTriple().isWasm()) {
6843
for (const Expr *Arg : Args) {
6844
if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6845
return ExprError(Diag(Arg->getExprLoc(),
6846
diag::err_wasm_table_as_function_parameter));
6847
}
6848
}
6849
}
6850
6851
if (Proto) {
6852
if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6853
IsExecConfig))
6854
return ExprError();
6855
} else {
6856
assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6857
6858
if (FDecl) {
6859
// Check if we have too few/too many template arguments, based
6860
// on our knowledge of the function definition.
6861
const FunctionDecl *Def = nullptr;
6862
if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6863
Proto = Def->getType()->getAs<FunctionProtoType>();
6864
if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6865
Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6866
<< (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6867
}
6868
6869
// If the function we're calling isn't a function prototype, but we have
6870
// a function prototype from a prior declaratiom, use that prototype.
6871
if (!FDecl->hasPrototype())
6872
Proto = FDecl->getType()->getAs<FunctionProtoType>();
6873
}
6874
6875
// If we still haven't found a prototype to use but there are arguments to
6876
// the call, diagnose this as calling a function without a prototype.
6877
// However, if we found a function declaration, check to see if
6878
// -Wdeprecated-non-prototype was disabled where the function was declared.
6879
// If so, we will silence the diagnostic here on the assumption that this
6880
// interface is intentional and the user knows what they're doing. We will
6881
// also silence the diagnostic if there is a function declaration but it
6882
// was implicitly defined (the user already gets diagnostics about the
6883
// creation of the implicit function declaration, so the additional warning
6884
// is not helpful).
6885
if (!Proto && !Args.empty() &&
6886
(!FDecl || (!FDecl->isImplicit() &&
6887
!Diags.isIgnored(diag::warn_strict_uses_without_prototype,
6888
FDecl->getLocation()))))
6889
Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
6890
<< (FDecl != nullptr) << FDecl;
6891
6892
// Promote the arguments (C99 6.5.2.2p6).
6893
for (unsigned i = 0, e = Args.size(); i != e; i++) {
6894
Expr *Arg = Args[i];
6895
6896
if (Proto && i < Proto->getNumParams()) {
6897
InitializedEntity Entity = InitializedEntity::InitializeParameter(
6898
Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6899
ExprResult ArgE =
6900
PerformCopyInitialization(Entity, SourceLocation(), Arg);
6901
if (ArgE.isInvalid())
6902
return true;
6903
6904
Arg = ArgE.getAs<Expr>();
6905
6906
} else {
6907
ExprResult ArgE = DefaultArgumentPromotion(Arg);
6908
6909
if (ArgE.isInvalid())
6910
return true;
6911
6912
Arg = ArgE.getAs<Expr>();
6913
}
6914
6915
if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6916
diag::err_call_incomplete_argument, Arg))
6917
return ExprError();
6918
6919
TheCall->setArg(i, Arg);
6920
}
6921
TheCall->computeDependence();
6922
}
6923
6924
if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6925
if (Method->isImplicitObjectMemberFunction())
6926
return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6927
<< Fn->getSourceRange() << 0);
6928
6929
// Check for sentinels
6930
if (NDecl)
6931
DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6932
6933
// Warn for unions passing across security boundary (CMSE).
6934
if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6935
for (unsigned i = 0, e = Args.size(); i != e; i++) {
6936
if (const auto *RT =
6937
dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6938
if (RT->getDecl()->isOrContainsUnion())
6939
Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6940
<< 0 << i;
6941
}
6942
}
6943
}
6944
6945
// Do special checking on direct calls to functions.
6946
if (FDecl) {
6947
if (CheckFunctionCall(FDecl, TheCall, Proto))
6948
return ExprError();
6949
6950
checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6951
6952
if (BuiltinID)
6953
return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6954
} else if (NDecl) {
6955
if (CheckPointerCall(NDecl, TheCall, Proto))
6956
return ExprError();
6957
} else {
6958
if (CheckOtherCall(TheCall, Proto))
6959
return ExprError();
6960
}
6961
6962
return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6963
}
6964
6965
ExprResult
6966
Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6967
SourceLocation RParenLoc, Expr *InitExpr) {
6968
assert(Ty && "ActOnCompoundLiteral(): missing type");
6969
assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6970
6971
TypeSourceInfo *TInfo;
6972
QualType literalType = GetTypeFromParser(Ty, &TInfo);
6973
if (!TInfo)
6974
TInfo = Context.getTrivialTypeSourceInfo(literalType);
6975
6976
return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6977
}
6978
6979
ExprResult
6980
Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6981
SourceLocation RParenLoc, Expr *LiteralExpr) {
6982
QualType literalType = TInfo->getType();
6983
6984
if (literalType->isArrayType()) {
6985
if (RequireCompleteSizedType(
6986
LParenLoc, Context.getBaseElementType(literalType),
6987
diag::err_array_incomplete_or_sizeless_type,
6988
SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6989
return ExprError();
6990
if (literalType->isVariableArrayType()) {
6991
// C23 6.7.10p4: An entity of variable length array type shall not be
6992
// initialized except by an empty initializer.
6993
//
6994
// The C extension warnings are issued from ParseBraceInitializer() and
6995
// do not need to be issued here. However, we continue to issue an error
6996
// in the case there are initializers or we are compiling C++. We allow
6997
// use of VLAs in C++, but it's not clear we want to allow {} to zero
6998
// init a VLA in C++ in all cases (such as with non-trivial constructors).
6999
// FIXME: should we allow this construct in C++ when it makes sense to do
7000
// so?
7001
//
7002
// But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7003
// shall specify an object type or an array of unknown size, but not a
7004
// variable length array type. This seems odd, as it allows 'int a[size] =
7005
// {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7006
// says, this is what's implemented here for C (except for the extension
7007
// that permits constant foldable size arrays)
7008
7009
auto diagID = LangOpts.CPlusPlus
7010
? diag::err_variable_object_no_init
7011
: diag::err_compound_literal_with_vla_type;
7012
if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7013
diagID))
7014
return ExprError();
7015
}
7016
} else if (!literalType->isDependentType() &&
7017
RequireCompleteType(LParenLoc, literalType,
7018
diag::err_typecheck_decl_incomplete_type,
7019
SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7020
return ExprError();
7021
7022
InitializedEntity Entity
7023
= InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7024
InitializationKind Kind
7025
= InitializationKind::CreateCStyleCast(LParenLoc,
7026
SourceRange(LParenLoc, RParenLoc),
7027
/*InitList=*/true);
7028
InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7029
ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7030
&literalType);
7031
if (Result.isInvalid())
7032
return ExprError();
7033
LiteralExpr = Result.get();
7034
7035
bool isFileScope = !CurContext->isFunctionOrMethod();
7036
7037
// In C, compound literals are l-values for some reason.
7038
// For GCC compatibility, in C++, file-scope array compound literals with
7039
// constant initializers are also l-values, and compound literals are
7040
// otherwise prvalues.
7041
//
7042
// (GCC also treats C++ list-initialized file-scope array prvalues with
7043
// constant initializers as l-values, but that's non-conforming, so we don't
7044
// follow it there.)
7045
//
7046
// FIXME: It would be better to handle the lvalue cases as materializing and
7047
// lifetime-extending a temporary object, but our materialized temporaries
7048
// representation only supports lifetime extension from a variable, not "out
7049
// of thin air".
7050
// FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7051
// is bound to the result of applying array-to-pointer decay to the compound
7052
// literal.
7053
// FIXME: GCC supports compound literals of reference type, which should
7054
// obviously have a value kind derived from the kind of reference involved.
7055
ExprValueKind VK =
7056
(getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7057
? VK_PRValue
7058
: VK_LValue;
7059
7060
if (isFileScope)
7061
if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7062
for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7063
Expr *Init = ILE->getInit(i);
7064
ILE->setInit(i, ConstantExpr::Create(Context, Init));
7065
}
7066
7067
auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7068
VK, LiteralExpr, isFileScope);
7069
if (isFileScope) {
7070
if (!LiteralExpr->isTypeDependent() &&
7071
!LiteralExpr->isValueDependent() &&
7072
!literalType->isDependentType()) // C99 6.5.2.5p3
7073
if (CheckForConstantInitializer(LiteralExpr))
7074
return ExprError();
7075
} else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7076
literalType.getAddressSpace() != LangAS::Default) {
7077
// Embedded-C extensions to C99 6.5.2.5:
7078
// "If the compound literal occurs inside the body of a function, the
7079
// type name shall not be qualified by an address-space qualifier."
7080
Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7081
<< SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7082
return ExprError();
7083
}
7084
7085
if (!isFileScope && !getLangOpts().CPlusPlus) {
7086
// Compound literals that have automatic storage duration are destroyed at
7087
// the end of the scope in C; in C++, they're just temporaries.
7088
7089
// Emit diagnostics if it is or contains a C union type that is non-trivial
7090
// to destruct.
7091
if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7092
checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7093
NTCUC_CompoundLiteral, NTCUK_Destruct);
7094
7095
// Diagnose jumps that enter or exit the lifetime of the compound literal.
7096
if (literalType.isDestructedType()) {
7097
Cleanup.setExprNeedsCleanups(true);
7098
ExprCleanupObjects.push_back(E);
7099
getCurFunction()->setHasBranchProtectedScope();
7100
}
7101
}
7102
7103
if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7104
E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7105
checkNonTrivialCUnionInInitializer(E->getInitializer(),
7106
E->getInitializer()->getExprLoc());
7107
7108
return MaybeBindToTemporary(E);
7109
}
7110
7111
ExprResult
7112
Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7113
SourceLocation RBraceLoc) {
7114
// Only produce each kind of designated initialization diagnostic once.
7115
SourceLocation FirstDesignator;
7116
bool DiagnosedArrayDesignator = false;
7117
bool DiagnosedNestedDesignator = false;
7118
bool DiagnosedMixedDesignator = false;
7119
7120
// Check that any designated initializers are syntactically valid in the
7121
// current language mode.
7122
for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7123
if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7124
if (FirstDesignator.isInvalid())
7125
FirstDesignator = DIE->getBeginLoc();
7126
7127
if (!getLangOpts().CPlusPlus)
7128
break;
7129
7130
if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7131
DiagnosedNestedDesignator = true;
7132
Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7133
<< DIE->getDesignatorsSourceRange();
7134
}
7135
7136
for (auto &Desig : DIE->designators()) {
7137
if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7138
DiagnosedArrayDesignator = true;
7139
Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7140
<< Desig.getSourceRange();
7141
}
7142
}
7143
7144
if (!DiagnosedMixedDesignator &&
7145
!isa<DesignatedInitExpr>(InitArgList[0])) {
7146
DiagnosedMixedDesignator = true;
7147
Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7148
<< DIE->getSourceRange();
7149
Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7150
<< InitArgList[0]->getSourceRange();
7151
}
7152
} else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7153
isa<DesignatedInitExpr>(InitArgList[0])) {
7154
DiagnosedMixedDesignator = true;
7155
auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7156
Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7157
<< DIE->getSourceRange();
7158
Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7159
<< InitArgList[I]->getSourceRange();
7160
}
7161
}
7162
7163
if (FirstDesignator.isValid()) {
7164
// Only diagnose designated initiaization as a C++20 extension if we didn't
7165
// already diagnose use of (non-C++20) C99 designator syntax.
7166
if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7167
!DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7168
Diag(FirstDesignator, getLangOpts().CPlusPlus20
7169
? diag::warn_cxx17_compat_designated_init
7170
: diag::ext_cxx_designated_init);
7171
} else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7172
Diag(FirstDesignator, diag::ext_designated_init);
7173
}
7174
}
7175
7176
return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7177
}
7178
7179
ExprResult
7180
Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7181
SourceLocation RBraceLoc) {
7182
// Semantic analysis for initializers is done by ActOnDeclarator() and
7183
// CheckInitializer() - it requires knowledge of the object being initialized.
7184
7185
// Immediately handle non-overload placeholders. Overloads can be
7186
// resolved contextually, but everything else here can't.
7187
for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7188
if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7189
ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7190
7191
// Ignore failures; dropping the entire initializer list because
7192
// of one failure would be terrible for indexing/etc.
7193
if (result.isInvalid()) continue;
7194
7195
InitArgList[I] = result.get();
7196
}
7197
}
7198
7199
InitListExpr *E =
7200
new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7201
E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7202
return E;
7203
}
7204
7205
void Sema::maybeExtendBlockObject(ExprResult &E) {
7206
assert(E.get()->getType()->isBlockPointerType());
7207
assert(E.get()->isPRValue());
7208
7209
// Only do this in an r-value context.
7210
if (!getLangOpts().ObjCAutoRefCount) return;
7211
7212
E = ImplicitCastExpr::Create(
7213
Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7214
/*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7215
Cleanup.setExprNeedsCleanups(true);
7216
}
7217
7218
CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7219
// Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7220
// Also, callers should have filtered out the invalid cases with
7221
// pointers. Everything else should be possible.
7222
7223
QualType SrcTy = Src.get()->getType();
7224
if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7225
return CK_NoOp;
7226
7227
switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7228
case Type::STK_MemberPointer:
7229
llvm_unreachable("member pointer type in C");
7230
7231
case Type::STK_CPointer:
7232
case Type::STK_BlockPointer:
7233
case Type::STK_ObjCObjectPointer:
7234
switch (DestTy->getScalarTypeKind()) {
7235
case Type::STK_CPointer: {
7236
LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7237
LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7238
if (SrcAS != DestAS)
7239
return CK_AddressSpaceConversion;
7240
if (Context.hasCvrSimilarType(SrcTy, DestTy))
7241
return CK_NoOp;
7242
return CK_BitCast;
7243
}
7244
case Type::STK_BlockPointer:
7245
return (SrcKind == Type::STK_BlockPointer
7246
? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7247
case Type::STK_ObjCObjectPointer:
7248
if (SrcKind == Type::STK_ObjCObjectPointer)
7249
return CK_BitCast;
7250
if (SrcKind == Type::STK_CPointer)
7251
return CK_CPointerToObjCPointerCast;
7252
maybeExtendBlockObject(Src);
7253
return CK_BlockPointerToObjCPointerCast;
7254
case Type::STK_Bool:
7255
return CK_PointerToBoolean;
7256
case Type::STK_Integral:
7257
return CK_PointerToIntegral;
7258
case Type::STK_Floating:
7259
case Type::STK_FloatingComplex:
7260
case Type::STK_IntegralComplex:
7261
case Type::STK_MemberPointer:
7262
case Type::STK_FixedPoint:
7263
llvm_unreachable("illegal cast from pointer");
7264
}
7265
llvm_unreachable("Should have returned before this");
7266
7267
case Type::STK_FixedPoint:
7268
switch (DestTy->getScalarTypeKind()) {
7269
case Type::STK_FixedPoint:
7270
return CK_FixedPointCast;
7271
case Type::STK_Bool:
7272
return CK_FixedPointToBoolean;
7273
case Type::STK_Integral:
7274
return CK_FixedPointToIntegral;
7275
case Type::STK_Floating:
7276
return CK_FixedPointToFloating;
7277
case Type::STK_IntegralComplex:
7278
case Type::STK_FloatingComplex:
7279
Diag(Src.get()->getExprLoc(),
7280
diag::err_unimplemented_conversion_with_fixed_point_type)
7281
<< DestTy;
7282
return CK_IntegralCast;
7283
case Type::STK_CPointer:
7284
case Type::STK_ObjCObjectPointer:
7285
case Type::STK_BlockPointer:
7286
case Type::STK_MemberPointer:
7287
llvm_unreachable("illegal cast to pointer type");
7288
}
7289
llvm_unreachable("Should have returned before this");
7290
7291
case Type::STK_Bool: // casting from bool is like casting from an integer
7292
case Type::STK_Integral:
7293
switch (DestTy->getScalarTypeKind()) {
7294
case Type::STK_CPointer:
7295
case Type::STK_ObjCObjectPointer:
7296
case Type::STK_BlockPointer:
7297
if (Src.get()->isNullPointerConstant(Context,
7298
Expr::NPC_ValueDependentIsNull))
7299
return CK_NullToPointer;
7300
return CK_IntegralToPointer;
7301
case Type::STK_Bool:
7302
return CK_IntegralToBoolean;
7303
case Type::STK_Integral:
7304
return CK_IntegralCast;
7305
case Type::STK_Floating:
7306
return CK_IntegralToFloating;
7307
case Type::STK_IntegralComplex:
7308
Src = ImpCastExprToType(Src.get(),
7309
DestTy->castAs<ComplexType>()->getElementType(),
7310
CK_IntegralCast);
7311
return CK_IntegralRealToComplex;
7312
case Type::STK_FloatingComplex:
7313
Src = ImpCastExprToType(Src.get(),
7314
DestTy->castAs<ComplexType>()->getElementType(),
7315
CK_IntegralToFloating);
7316
return CK_FloatingRealToComplex;
7317
case Type::STK_MemberPointer:
7318
llvm_unreachable("member pointer type in C");
7319
case Type::STK_FixedPoint:
7320
return CK_IntegralToFixedPoint;
7321
}
7322
llvm_unreachable("Should have returned before this");
7323
7324
case Type::STK_Floating:
7325
switch (DestTy->getScalarTypeKind()) {
7326
case Type::STK_Floating:
7327
return CK_FloatingCast;
7328
case Type::STK_Bool:
7329
return CK_FloatingToBoolean;
7330
case Type::STK_Integral:
7331
return CK_FloatingToIntegral;
7332
case Type::STK_FloatingComplex:
7333
Src = ImpCastExprToType(Src.get(),
7334
DestTy->castAs<ComplexType>()->getElementType(),
7335
CK_FloatingCast);
7336
return CK_FloatingRealToComplex;
7337
case Type::STK_IntegralComplex:
7338
Src = ImpCastExprToType(Src.get(),
7339
DestTy->castAs<ComplexType>()->getElementType(),
7340
CK_FloatingToIntegral);
7341
return CK_IntegralRealToComplex;
7342
case Type::STK_CPointer:
7343
case Type::STK_ObjCObjectPointer:
7344
case Type::STK_BlockPointer:
7345
llvm_unreachable("valid float->pointer cast?");
7346
case Type::STK_MemberPointer:
7347
llvm_unreachable("member pointer type in C");
7348
case Type::STK_FixedPoint:
7349
return CK_FloatingToFixedPoint;
7350
}
7351
llvm_unreachable("Should have returned before this");
7352
7353
case Type::STK_FloatingComplex:
7354
switch (DestTy->getScalarTypeKind()) {
7355
case Type::STK_FloatingComplex:
7356
return CK_FloatingComplexCast;
7357
case Type::STK_IntegralComplex:
7358
return CK_FloatingComplexToIntegralComplex;
7359
case Type::STK_Floating: {
7360
QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7361
if (Context.hasSameType(ET, DestTy))
7362
return CK_FloatingComplexToReal;
7363
Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7364
return CK_FloatingCast;
7365
}
7366
case Type::STK_Bool:
7367
return CK_FloatingComplexToBoolean;
7368
case Type::STK_Integral:
7369
Src = ImpCastExprToType(Src.get(),
7370
SrcTy->castAs<ComplexType>()->getElementType(),
7371
CK_FloatingComplexToReal);
7372
return CK_FloatingToIntegral;
7373
case Type::STK_CPointer:
7374
case Type::STK_ObjCObjectPointer:
7375
case Type::STK_BlockPointer:
7376
llvm_unreachable("valid complex float->pointer cast?");
7377
case Type::STK_MemberPointer:
7378
llvm_unreachable("member pointer type in C");
7379
case Type::STK_FixedPoint:
7380
Diag(Src.get()->getExprLoc(),
7381
diag::err_unimplemented_conversion_with_fixed_point_type)
7382
<< SrcTy;
7383
return CK_IntegralCast;
7384
}
7385
llvm_unreachable("Should have returned before this");
7386
7387
case Type::STK_IntegralComplex:
7388
switch (DestTy->getScalarTypeKind()) {
7389
case Type::STK_FloatingComplex:
7390
return CK_IntegralComplexToFloatingComplex;
7391
case Type::STK_IntegralComplex:
7392
return CK_IntegralComplexCast;
7393
case Type::STK_Integral: {
7394
QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7395
if (Context.hasSameType(ET, DestTy))
7396
return CK_IntegralComplexToReal;
7397
Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7398
return CK_IntegralCast;
7399
}
7400
case Type::STK_Bool:
7401
return CK_IntegralComplexToBoolean;
7402
case Type::STK_Floating:
7403
Src = ImpCastExprToType(Src.get(),
7404
SrcTy->castAs<ComplexType>()->getElementType(),
7405
CK_IntegralComplexToReal);
7406
return CK_IntegralToFloating;
7407
case Type::STK_CPointer:
7408
case Type::STK_ObjCObjectPointer:
7409
case Type::STK_BlockPointer:
7410
llvm_unreachable("valid complex int->pointer cast?");
7411
case Type::STK_MemberPointer:
7412
llvm_unreachable("member pointer type in C");
7413
case Type::STK_FixedPoint:
7414
Diag(Src.get()->getExprLoc(),
7415
diag::err_unimplemented_conversion_with_fixed_point_type)
7416
<< SrcTy;
7417
return CK_IntegralCast;
7418
}
7419
llvm_unreachable("Should have returned before this");
7420
}
7421
7422
llvm_unreachable("Unhandled scalar cast");
7423
}
7424
7425
static bool breakDownVectorType(QualType type, uint64_t &len,
7426
QualType &eltType) {
7427
// Vectors are simple.
7428
if (const VectorType *vecType = type->getAs<VectorType>()) {
7429
len = vecType->getNumElements();
7430
eltType = vecType->getElementType();
7431
assert(eltType->isScalarType());
7432
return true;
7433
}
7434
7435
// We allow lax conversion to and from non-vector types, but only if
7436
// they're real types (i.e. non-complex, non-pointer scalar types).
7437
if (!type->isRealType()) return false;
7438
7439
len = 1;
7440
eltType = type;
7441
return true;
7442
}
7443
7444
bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7445
assert(srcTy->isVectorType() || destTy->isVectorType());
7446
7447
auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7448
if (!FirstType->isSVESizelessBuiltinType())
7449
return false;
7450
7451
const auto *VecTy = SecondType->getAs<VectorType>();
7452
return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7453
};
7454
7455
return ValidScalableConversion(srcTy, destTy) ||
7456
ValidScalableConversion(destTy, srcTy);
7457
}
7458
7459
bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7460
if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7461
return false;
7462
7463
const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7464
const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7465
7466
return matSrcType->getNumRows() == matDestType->getNumRows() &&
7467
matSrcType->getNumColumns() == matDestType->getNumColumns();
7468
}
7469
7470
bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7471
assert(DestTy->isVectorType() || SrcTy->isVectorType());
7472
7473
uint64_t SrcLen, DestLen;
7474
QualType SrcEltTy, DestEltTy;
7475
if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7476
return false;
7477
if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7478
return false;
7479
7480
// ASTContext::getTypeSize will return the size rounded up to a
7481
// power of 2, so instead of using that, we need to use the raw
7482
// element size multiplied by the element count.
7483
uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7484
uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7485
7486
return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7487
}
7488
7489
bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7490
assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7491
"expected at least one type to be a vector here");
7492
7493
bool IsSrcTyAltivec =
7494
SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7495
VectorKind::AltiVecVector) ||
7496
(SrcTy->castAs<VectorType>()->getVectorKind() ==
7497
VectorKind::AltiVecBool) ||
7498
(SrcTy->castAs<VectorType>()->getVectorKind() ==
7499
VectorKind::AltiVecPixel));
7500
7501
bool IsDestTyAltivec = DestTy->isVectorType() &&
7502
((DestTy->castAs<VectorType>()->getVectorKind() ==
7503
VectorKind::AltiVecVector) ||
7504
(DestTy->castAs<VectorType>()->getVectorKind() ==
7505
VectorKind::AltiVecBool) ||
7506
(DestTy->castAs<VectorType>()->getVectorKind() ==
7507
VectorKind::AltiVecPixel));
7508
7509
return (IsSrcTyAltivec || IsDestTyAltivec);
7510
}
7511
7512
bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7513
assert(destTy->isVectorType() || srcTy->isVectorType());
7514
7515
// Disallow lax conversions between scalars and ExtVectors (these
7516
// conversions are allowed for other vector types because common headers
7517
// depend on them). Most scalar OP ExtVector cases are handled by the
7518
// splat path anyway, which does what we want (convert, not bitcast).
7519
// What this rules out for ExtVectors is crazy things like char4*float.
7520
if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7521
if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7522
7523
return areVectorTypesSameSize(srcTy, destTy);
7524
}
7525
7526
bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7527
assert(destTy->isVectorType() || srcTy->isVectorType());
7528
7529
switch (Context.getLangOpts().getLaxVectorConversions()) {
7530
case LangOptions::LaxVectorConversionKind::None:
7531
return false;
7532
7533
case LangOptions::LaxVectorConversionKind::Integer:
7534
if (!srcTy->isIntegralOrEnumerationType()) {
7535
auto *Vec = srcTy->getAs<VectorType>();
7536
if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7537
return false;
7538
}
7539
if (!destTy->isIntegralOrEnumerationType()) {
7540
auto *Vec = destTy->getAs<VectorType>();
7541
if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7542
return false;
7543
}
7544
// OK, integer (vector) -> integer (vector) bitcast.
7545
break;
7546
7547
case LangOptions::LaxVectorConversionKind::All:
7548
break;
7549
}
7550
7551
return areLaxCompatibleVectorTypes(srcTy, destTy);
7552
}
7553
7554
bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7555
CastKind &Kind) {
7556
if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7557
if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7558
return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7559
<< DestTy << SrcTy << R;
7560
}
7561
} else if (SrcTy->isMatrixType()) {
7562
return Diag(R.getBegin(),
7563
diag::err_invalid_conversion_between_matrix_and_type)
7564
<< SrcTy << DestTy << R;
7565
} else if (DestTy->isMatrixType()) {
7566
return Diag(R.getBegin(),
7567
diag::err_invalid_conversion_between_matrix_and_type)
7568
<< DestTy << SrcTy << R;
7569
}
7570
7571
Kind = CK_MatrixCast;
7572
return false;
7573
}
7574
7575
bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7576
CastKind &Kind) {
7577
assert(VectorTy->isVectorType() && "Not a vector type!");
7578
7579
if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7580
if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7581
return Diag(R.getBegin(),
7582
Ty->isVectorType() ?
7583
diag::err_invalid_conversion_between_vectors :
7584
diag::err_invalid_conversion_between_vector_and_integer)
7585
<< VectorTy << Ty << R;
7586
} else
7587
return Diag(R.getBegin(),
7588
diag::err_invalid_conversion_between_vector_and_scalar)
7589
<< VectorTy << Ty << R;
7590
7591
Kind = CK_BitCast;
7592
return false;
7593
}
7594
7595
ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7596
QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7597
7598
if (DestElemTy == SplattedExpr->getType())
7599
return SplattedExpr;
7600
7601
assert(DestElemTy->isFloatingType() ||
7602
DestElemTy->isIntegralOrEnumerationType());
7603
7604
CastKind CK;
7605
if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7606
// OpenCL requires that we convert `true` boolean expressions to -1, but
7607
// only when splatting vectors.
7608
if (DestElemTy->isFloatingType()) {
7609
// To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7610
// in two steps: boolean to signed integral, then to floating.
7611
ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7612
CK_BooleanToSignedIntegral);
7613
SplattedExpr = CastExprRes.get();
7614
CK = CK_IntegralToFloating;
7615
} else {
7616
CK = CK_BooleanToSignedIntegral;
7617
}
7618
} else {
7619
ExprResult CastExprRes = SplattedExpr;
7620
CK = PrepareScalarCast(CastExprRes, DestElemTy);
7621
if (CastExprRes.isInvalid())
7622
return ExprError();
7623
SplattedExpr = CastExprRes.get();
7624
}
7625
return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7626
}
7627
7628
ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7629
Expr *CastExpr, CastKind &Kind) {
7630
assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7631
7632
QualType SrcTy = CastExpr->getType();
7633
7634
// If SrcTy is a VectorType, the total size must match to explicitly cast to
7635
// an ExtVectorType.
7636
// In OpenCL, casts between vectors of different types are not allowed.
7637
// (See OpenCL 6.2).
7638
if (SrcTy->isVectorType()) {
7639
if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7640
(getLangOpts().OpenCL &&
7641
!Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7642
Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7643
<< DestTy << SrcTy << R;
7644
return ExprError();
7645
}
7646
Kind = CK_BitCast;
7647
return CastExpr;
7648
}
7649
7650
// All non-pointer scalars can be cast to ExtVector type. The appropriate
7651
// conversion will take place first from scalar to elt type, and then
7652
// splat from elt type to vector.
7653
if (SrcTy->isPointerType())
7654
return Diag(R.getBegin(),
7655
diag::err_invalid_conversion_between_vector_and_scalar)
7656
<< DestTy << SrcTy << R;
7657
7658
Kind = CK_VectorSplat;
7659
return prepareVectorSplat(DestTy, CastExpr);
7660
}
7661
7662
ExprResult
7663
Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7664
Declarator &D, ParsedType &Ty,
7665
SourceLocation RParenLoc, Expr *CastExpr) {
7666
assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7667
"ActOnCastExpr(): missing type or expr");
7668
7669
TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7670
if (D.isInvalidType())
7671
return ExprError();
7672
7673
if (getLangOpts().CPlusPlus) {
7674
// Check that there are no default arguments (C++ only).
7675
CheckExtraCXXDefaultArguments(D);
7676
} else {
7677
// Make sure any TypoExprs have been dealt with.
7678
ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7679
if (!Res.isUsable())
7680
return ExprError();
7681
CastExpr = Res.get();
7682
}
7683
7684
checkUnusedDeclAttributes(D);
7685
7686
QualType castType = castTInfo->getType();
7687
Ty = CreateParsedType(castType, castTInfo);
7688
7689
bool isVectorLiteral = false;
7690
7691
// Check for an altivec or OpenCL literal,
7692
// i.e. all the elements are integer constants.
7693
ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7694
ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7695
if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7696
&& castType->isVectorType() && (PE || PLE)) {
7697
if (PLE && PLE->getNumExprs() == 0) {
7698
Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7699
return ExprError();
7700
}
7701
if (PE || PLE->getNumExprs() == 1) {
7702
Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7703
if (!E->isTypeDependent() && !E->getType()->isVectorType())
7704
isVectorLiteral = true;
7705
}
7706
else
7707
isVectorLiteral = true;
7708
}
7709
7710
// If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7711
// then handle it as such.
7712
if (isVectorLiteral)
7713
return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7714
7715
// If the Expr being casted is a ParenListExpr, handle it specially.
7716
// This is not an AltiVec-style cast, so turn the ParenListExpr into a
7717
// sequence of BinOp comma operators.
7718
if (isa<ParenListExpr>(CastExpr)) {
7719
ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7720
if (Result.isInvalid()) return ExprError();
7721
CastExpr = Result.get();
7722
}
7723
7724
if (getLangOpts().CPlusPlus && !castType->isVoidType())
7725
Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7726
7727
ObjC().CheckTollFreeBridgeCast(castType, CastExpr);
7728
7729
ObjC().CheckObjCBridgeRelatedCast(castType, CastExpr);
7730
7731
DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7732
7733
return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7734
}
7735
7736
ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7737
SourceLocation RParenLoc, Expr *E,
7738
TypeSourceInfo *TInfo) {
7739
assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7740
"Expected paren or paren list expression");
7741
7742
Expr **exprs;
7743
unsigned numExprs;
7744
Expr *subExpr;
7745
SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7746
if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7747
LiteralLParenLoc = PE->getLParenLoc();
7748
LiteralRParenLoc = PE->getRParenLoc();
7749
exprs = PE->getExprs();
7750
numExprs = PE->getNumExprs();
7751
} else { // isa<ParenExpr> by assertion at function entrance
7752
LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7753
LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7754
subExpr = cast<ParenExpr>(E)->getSubExpr();
7755
exprs = &subExpr;
7756
numExprs = 1;
7757
}
7758
7759
QualType Ty = TInfo->getType();
7760
assert(Ty->isVectorType() && "Expected vector type");
7761
7762
SmallVector<Expr *, 8> initExprs;
7763
const VectorType *VTy = Ty->castAs<VectorType>();
7764
unsigned numElems = VTy->getNumElements();
7765
7766
// '(...)' form of vector initialization in AltiVec: the number of
7767
// initializers must be one or must match the size of the vector.
7768
// If a single value is specified in the initializer then it will be
7769
// replicated to all the components of the vector
7770
if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7771
VTy->getElementType()))
7772
return ExprError();
7773
if (ShouldSplatAltivecScalarInCast(VTy)) {
7774
// The number of initializers must be one or must match the size of the
7775
// vector. If a single value is specified in the initializer then it will
7776
// be replicated to all the components of the vector
7777
if (numExprs == 1) {
7778
QualType ElemTy = VTy->getElementType();
7779
ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7780
if (Literal.isInvalid())
7781
return ExprError();
7782
Literal = ImpCastExprToType(Literal.get(), ElemTy,
7783
PrepareScalarCast(Literal, ElemTy));
7784
return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7785
}
7786
else if (numExprs < numElems) {
7787
Diag(E->getExprLoc(),
7788
diag::err_incorrect_number_of_vector_initializers);
7789
return ExprError();
7790
}
7791
else
7792
initExprs.append(exprs, exprs + numExprs);
7793
}
7794
else {
7795
// For OpenCL, when the number of initializers is a single value,
7796
// it will be replicated to all components of the vector.
7797
if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
7798
numExprs == 1) {
7799
QualType ElemTy = VTy->getElementType();
7800
ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7801
if (Literal.isInvalid())
7802
return ExprError();
7803
Literal = ImpCastExprToType(Literal.get(), ElemTy,
7804
PrepareScalarCast(Literal, ElemTy));
7805
return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7806
}
7807
7808
initExprs.append(exprs, exprs + numExprs);
7809
}
7810
// FIXME: This means that pretty-printing the final AST will produce curly
7811
// braces instead of the original commas.
7812
InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7813
initExprs, LiteralRParenLoc);
7814
initE->setType(Ty);
7815
return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7816
}
7817
7818
ExprResult
7819
Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7820
ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7821
if (!E)
7822
return OrigExpr;
7823
7824
ExprResult Result(E->getExpr(0));
7825
7826
for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7827
Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7828
E->getExpr(i));
7829
7830
if (Result.isInvalid()) return ExprError();
7831
7832
return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7833
}
7834
7835
ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7836
SourceLocation R,
7837
MultiExprArg Val) {
7838
return ParenListExpr::Create(Context, L, Val, R);
7839
}
7840
7841
bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7842
SourceLocation QuestionLoc) {
7843
const Expr *NullExpr = LHSExpr;
7844
const Expr *NonPointerExpr = RHSExpr;
7845
Expr::NullPointerConstantKind NullKind =
7846
NullExpr->isNullPointerConstant(Context,
7847
Expr::NPC_ValueDependentIsNotNull);
7848
7849
if (NullKind == Expr::NPCK_NotNull) {
7850
NullExpr = RHSExpr;
7851
NonPointerExpr = LHSExpr;
7852
NullKind =
7853
NullExpr->isNullPointerConstant(Context,
7854
Expr::NPC_ValueDependentIsNotNull);
7855
}
7856
7857
if (NullKind == Expr::NPCK_NotNull)
7858
return false;
7859
7860
if (NullKind == Expr::NPCK_ZeroExpression)
7861
return false;
7862
7863
if (NullKind == Expr::NPCK_ZeroLiteral) {
7864
// In this case, check to make sure that we got here from a "NULL"
7865
// string in the source code.
7866
NullExpr = NullExpr->IgnoreParenImpCasts();
7867
SourceLocation loc = NullExpr->getExprLoc();
7868
if (!findMacroSpelling(loc, "NULL"))
7869
return false;
7870
}
7871
7872
int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7873
Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7874
<< NonPointerExpr->getType() << DiagType
7875
<< NonPointerExpr->getSourceRange();
7876
return true;
7877
}
7878
7879
/// Return false if the condition expression is valid, true otherwise.
7880
static bool checkCondition(Sema &S, const Expr *Cond,
7881
SourceLocation QuestionLoc) {
7882
QualType CondTy = Cond->getType();
7883
7884
// OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7885
if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7886
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7887
<< CondTy << Cond->getSourceRange();
7888
return true;
7889
}
7890
7891
// C99 6.5.15p2
7892
if (CondTy->isScalarType()) return false;
7893
7894
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7895
<< CondTy << Cond->getSourceRange();
7896
return true;
7897
}
7898
7899
/// Return false if the NullExpr can be promoted to PointerTy,
7900
/// true otherwise.
7901
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7902
QualType PointerTy) {
7903
if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7904
!NullExpr.get()->isNullPointerConstant(S.Context,
7905
Expr::NPC_ValueDependentIsNull))
7906
return true;
7907
7908
NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7909
return false;
7910
}
7911
7912
/// Checks compatibility between two pointers and return the resulting
7913
/// type.
7914
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7915
ExprResult &RHS,
7916
SourceLocation Loc) {
7917
QualType LHSTy = LHS.get()->getType();
7918
QualType RHSTy = RHS.get()->getType();
7919
7920
if (S.Context.hasSameType(LHSTy, RHSTy)) {
7921
// Two identical pointers types are always compatible.
7922
return S.Context.getCommonSugaredType(LHSTy, RHSTy);
7923
}
7924
7925
QualType lhptee, rhptee;
7926
7927
// Get the pointee types.
7928
bool IsBlockPointer = false;
7929
if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7930
lhptee = LHSBTy->getPointeeType();
7931
rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7932
IsBlockPointer = true;
7933
} else {
7934
lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7935
rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7936
}
7937
7938
// C99 6.5.15p6: If both operands are pointers to compatible types or to
7939
// differently qualified versions of compatible types, the result type is
7940
// a pointer to an appropriately qualified version of the composite
7941
// type.
7942
7943
// Only CVR-qualifiers exist in the standard, and the differently-qualified
7944
// clause doesn't make sense for our extensions. E.g. address space 2 should
7945
// be incompatible with address space 3: they may live on different devices or
7946
// anything.
7947
Qualifiers lhQual = lhptee.getQualifiers();
7948
Qualifiers rhQual = rhptee.getQualifiers();
7949
7950
LangAS ResultAddrSpace = LangAS::Default;
7951
LangAS LAddrSpace = lhQual.getAddressSpace();
7952
LangAS RAddrSpace = rhQual.getAddressSpace();
7953
7954
// OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7955
// spaces is disallowed.
7956
if (lhQual.isAddressSpaceSupersetOf(rhQual))
7957
ResultAddrSpace = LAddrSpace;
7958
else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7959
ResultAddrSpace = RAddrSpace;
7960
else {
7961
S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7962
<< LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7963
<< RHS.get()->getSourceRange();
7964
return QualType();
7965
}
7966
7967
unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7968
auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7969
lhQual.removeCVRQualifiers();
7970
rhQual.removeCVRQualifiers();
7971
7972
// OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7973
// (C99 6.7.3) for address spaces. We assume that the check should behave in
7974
// the same manner as it's defined for CVR qualifiers, so for OpenCL two
7975
// qual types are compatible iff
7976
// * corresponded types are compatible
7977
// * CVR qualifiers are equal
7978
// * address spaces are equal
7979
// Thus for conditional operator we merge CVR and address space unqualified
7980
// pointees and if there is a composite type we return a pointer to it with
7981
// merged qualifiers.
7982
LHSCastKind =
7983
LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7984
RHSCastKind =
7985
RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7986
lhQual.removeAddressSpace();
7987
rhQual.removeAddressSpace();
7988
7989
lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7990
rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7991
7992
QualType CompositeTy = S.Context.mergeTypes(
7993
lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
7994
/*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
7995
7996
if (CompositeTy.isNull()) {
7997
// In this situation, we assume void* type. No especially good
7998
// reason, but this is what gcc does, and we do have to pick
7999
// to get a consistent AST.
8000
QualType incompatTy;
8001
incompatTy = S.Context.getPointerType(
8002
S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8003
LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8004
RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8005
8006
// FIXME: For OpenCL the warning emission and cast to void* leaves a room
8007
// for casts between types with incompatible address space qualifiers.
8008
// For the following code the compiler produces casts between global and
8009
// local address spaces of the corresponded innermost pointees:
8010
// local int *global *a;
8011
// global int *global *b;
8012
// a = (0 ? a : b); // see C99 6.5.16.1.p1.
8013
S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8014
<< LHSTy << RHSTy << LHS.get()->getSourceRange()
8015
<< RHS.get()->getSourceRange();
8016
8017
return incompatTy;
8018
}
8019
8020
// The pointer types are compatible.
8021
// In case of OpenCL ResultTy should have the address space qualifier
8022
// which is a superset of address spaces of both the 2nd and the 3rd
8023
// operands of the conditional operator.
8024
QualType ResultTy = [&, ResultAddrSpace]() {
8025
if (S.getLangOpts().OpenCL) {
8026
Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8027
CompositeQuals.setAddressSpace(ResultAddrSpace);
8028
return S.Context
8029
.getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8030
.withCVRQualifiers(MergedCVRQual);
8031
}
8032
return CompositeTy.withCVRQualifiers(MergedCVRQual);
8033
}();
8034
if (IsBlockPointer)
8035
ResultTy = S.Context.getBlockPointerType(ResultTy);
8036
else
8037
ResultTy = S.Context.getPointerType(ResultTy);
8038
8039
LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8040
RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8041
return ResultTy;
8042
}
8043
8044
/// Return the resulting type when the operands are both block pointers.
8045
static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8046
ExprResult &LHS,
8047
ExprResult &RHS,
8048
SourceLocation Loc) {
8049
QualType LHSTy = LHS.get()->getType();
8050
QualType RHSTy = RHS.get()->getType();
8051
8052
if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8053
if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8054
QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8055
LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8056
RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8057
return destType;
8058
}
8059
S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8060
<< LHSTy << RHSTy << LHS.get()->getSourceRange()
8061
<< RHS.get()->getSourceRange();
8062
return QualType();
8063
}
8064
8065
// We have 2 block pointer types.
8066
return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8067
}
8068
8069
/// Return the resulting type when the operands are both pointers.
8070
static QualType
8071
checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8072
ExprResult &RHS,
8073
SourceLocation Loc) {
8074
// get the pointer types
8075
QualType LHSTy = LHS.get()->getType();
8076
QualType RHSTy = RHS.get()->getType();
8077
8078
// get the "pointed to" types
8079
QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8080
QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8081
8082
// ignore qualifiers on void (C99 6.5.15p3, clause 6)
8083
if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8084
// Figure out necessary qualifiers (C99 6.5.15p6)
8085
QualType destPointee
8086
= S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8087
QualType destType = S.Context.getPointerType(destPointee);
8088
// Add qualifiers if necessary.
8089
LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8090
// Promote to void*.
8091
RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8092
return destType;
8093
}
8094
if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8095
QualType destPointee
8096
= S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8097
QualType destType = S.Context.getPointerType(destPointee);
8098
// Add qualifiers if necessary.
8099
RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8100
// Promote to void*.
8101
LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8102
return destType;
8103
}
8104
8105
return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8106
}
8107
8108
/// Return false if the first expression is not an integer and the second
8109
/// expression is not a pointer, true otherwise.
8110
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8111
Expr* PointerExpr, SourceLocation Loc,
8112
bool IsIntFirstExpr) {
8113
if (!PointerExpr->getType()->isPointerType() ||
8114
!Int.get()->getType()->isIntegerType())
8115
return false;
8116
8117
Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8118
Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8119
8120
S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8121
<< Expr1->getType() << Expr2->getType()
8122
<< Expr1->getSourceRange() << Expr2->getSourceRange();
8123
Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8124
CK_IntegralToPointer);
8125
return true;
8126
}
8127
8128
/// Simple conversion between integer and floating point types.
8129
///
8130
/// Used when handling the OpenCL conditional operator where the
8131
/// condition is a vector while the other operands are scalar.
8132
///
8133
/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8134
/// types are either integer or floating type. Between the two
8135
/// operands, the type with the higher rank is defined as the "result
8136
/// type". The other operand needs to be promoted to the same type. No
8137
/// other type promotion is allowed. We cannot use
8138
/// UsualArithmeticConversions() for this purpose, since it always
8139
/// promotes promotable types.
8140
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8141
ExprResult &RHS,
8142
SourceLocation QuestionLoc) {
8143
LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8144
if (LHS.isInvalid())
8145
return QualType();
8146
RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8147
if (RHS.isInvalid())
8148
return QualType();
8149
8150
// For conversion purposes, we ignore any qualifiers.
8151
// For example, "const float" and "float" are equivalent.
8152
QualType LHSType =
8153
S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8154
QualType RHSType =
8155
S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8156
8157
if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8158
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8159
<< LHSType << LHS.get()->getSourceRange();
8160
return QualType();
8161
}
8162
8163
if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8164
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8165
<< RHSType << RHS.get()->getSourceRange();
8166
return QualType();
8167
}
8168
8169
// If both types are identical, no conversion is needed.
8170
if (LHSType == RHSType)
8171
return LHSType;
8172
8173
// Now handle "real" floating types (i.e. float, double, long double).
8174
if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8175
return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8176
/*IsCompAssign = */ false);
8177
8178
// Finally, we have two differing integer types.
8179
return handleIntegerConversion<doIntegralCast, doIntegralCast>
8180
(S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8181
}
8182
8183
/// Convert scalar operands to a vector that matches the
8184
/// condition in length.
8185
///
8186
/// Used when handling the OpenCL conditional operator where the
8187
/// condition is a vector while the other operands are scalar.
8188
///
8189
/// We first compute the "result type" for the scalar operands
8190
/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8191
/// into a vector of that type where the length matches the condition
8192
/// vector type. s6.11.6 requires that the element types of the result
8193
/// and the condition must have the same number of bits.
8194
static QualType
8195
OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8196
QualType CondTy, SourceLocation QuestionLoc) {
8197
QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8198
if (ResTy.isNull()) return QualType();
8199
8200
const VectorType *CV = CondTy->getAs<VectorType>();
8201
assert(CV);
8202
8203
// Determine the vector result type
8204
unsigned NumElements = CV->getNumElements();
8205
QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8206
8207
// Ensure that all types have the same number of bits
8208
if (S.Context.getTypeSize(CV->getElementType())
8209
!= S.Context.getTypeSize(ResTy)) {
8210
// Since VectorTy is created internally, it does not pretty print
8211
// with an OpenCL name. Instead, we just print a description.
8212
std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8213
SmallString<64> Str;
8214
llvm::raw_svector_ostream OS(Str);
8215
OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8216
S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8217
<< CondTy << OS.str();
8218
return QualType();
8219
}
8220
8221
// Convert operands to the vector result type
8222
LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8223
RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8224
8225
return VectorTy;
8226
}
8227
8228
/// Return false if this is a valid OpenCL condition vector
8229
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8230
SourceLocation QuestionLoc) {
8231
// OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8232
// integral type.
8233
const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8234
assert(CondTy);
8235
QualType EleTy = CondTy->getElementType();
8236
if (EleTy->isIntegerType()) return false;
8237
8238
S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8239
<< Cond->getType() << Cond->getSourceRange();
8240
return true;
8241
}
8242
8243
/// Return false if the vector condition type and the vector
8244
/// result type are compatible.
8245
///
8246
/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8247
/// number of elements, and their element types have the same number
8248
/// of bits.
8249
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8250
SourceLocation QuestionLoc) {
8251
const VectorType *CV = CondTy->getAs<VectorType>();
8252
const VectorType *RV = VecResTy->getAs<VectorType>();
8253
assert(CV && RV);
8254
8255
if (CV->getNumElements() != RV->getNumElements()) {
8256
S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8257
<< CondTy << VecResTy;
8258
return true;
8259
}
8260
8261
QualType CVE = CV->getElementType();
8262
QualType RVE = RV->getElementType();
8263
8264
if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8265
S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8266
<< CondTy << VecResTy;
8267
return true;
8268
}
8269
8270
return false;
8271
}
8272
8273
/// Return the resulting type for the conditional operator in
8274
/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8275
/// s6.3.i) when the condition is a vector type.
8276
static QualType
8277
OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8278
ExprResult &LHS, ExprResult &RHS,
8279
SourceLocation QuestionLoc) {
8280
Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8281
if (Cond.isInvalid())
8282
return QualType();
8283
QualType CondTy = Cond.get()->getType();
8284
8285
if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8286
return QualType();
8287
8288
// If either operand is a vector then find the vector type of the
8289
// result as specified in OpenCL v1.1 s6.3.i.
8290
if (LHS.get()->getType()->isVectorType() ||
8291
RHS.get()->getType()->isVectorType()) {
8292
bool IsBoolVecLang =
8293
!S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8294
QualType VecResTy =
8295
S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8296
/*isCompAssign*/ false,
8297
/*AllowBothBool*/ true,
8298
/*AllowBoolConversions*/ false,
8299
/*AllowBooleanOperation*/ IsBoolVecLang,
8300
/*ReportInvalid*/ true);
8301
if (VecResTy.isNull())
8302
return QualType();
8303
// The result type must match the condition type as specified in
8304
// OpenCL v1.1 s6.11.6.
8305
if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8306
return QualType();
8307
return VecResTy;
8308
}
8309
8310
// Both operands are scalar.
8311
return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8312
}
8313
8314
/// Return true if the Expr is block type
8315
static bool checkBlockType(Sema &S, const Expr *E) {
8316
if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8317
QualType Ty = CE->getCallee()->getType();
8318
if (Ty->isBlockPointerType()) {
8319
S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8320
return true;
8321
}
8322
}
8323
return false;
8324
}
8325
8326
/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8327
/// In that case, LHS = cond.
8328
/// C99 6.5.15
8329
QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8330
ExprResult &RHS, ExprValueKind &VK,
8331
ExprObjectKind &OK,
8332
SourceLocation QuestionLoc) {
8333
8334
ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8335
if (!LHSResult.isUsable()) return QualType();
8336
LHS = LHSResult;
8337
8338
ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8339
if (!RHSResult.isUsable()) return QualType();
8340
RHS = RHSResult;
8341
8342
// C++ is sufficiently different to merit its own checker.
8343
if (getLangOpts().CPlusPlus)
8344
return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8345
8346
VK = VK_PRValue;
8347
OK = OK_Ordinary;
8348
8349
if (Context.isDependenceAllowed() &&
8350
(Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8351
RHS.get()->isTypeDependent())) {
8352
assert(!getLangOpts().CPlusPlus);
8353
assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8354
RHS.get()->containsErrors()) &&
8355
"should only occur in error-recovery path.");
8356
return Context.DependentTy;
8357
}
8358
8359
// The OpenCL operator with a vector condition is sufficiently
8360
// different to merit its own checker.
8361
if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8362
Cond.get()->getType()->isExtVectorType())
8363
return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8364
8365
// First, check the condition.
8366
Cond = UsualUnaryConversions(Cond.get());
8367
if (Cond.isInvalid())
8368
return QualType();
8369
if (checkCondition(*this, Cond.get(), QuestionLoc))
8370
return QualType();
8371
8372
// Handle vectors.
8373
if (LHS.get()->getType()->isVectorType() ||
8374
RHS.get()->getType()->isVectorType())
8375
return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8376
/*AllowBothBool*/ true,
8377
/*AllowBoolConversions*/ false,
8378
/*AllowBooleanOperation*/ false,
8379
/*ReportInvalid*/ true);
8380
8381
QualType ResTy =
8382
UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8383
if (LHS.isInvalid() || RHS.isInvalid())
8384
return QualType();
8385
8386
// WebAssembly tables are not allowed as conditional LHS or RHS.
8387
QualType LHSTy = LHS.get()->getType();
8388
QualType RHSTy = RHS.get()->getType();
8389
if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8390
Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8391
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8392
return QualType();
8393
}
8394
8395
// Diagnose attempts to convert between __ibm128, __float128 and long double
8396
// where such conversions currently can't be handled.
8397
if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8398
Diag(QuestionLoc,
8399
diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8400
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8401
return QualType();
8402
}
8403
8404
// OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8405
// selection operator (?:).
8406
if (getLangOpts().OpenCL &&
8407
((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8408
return QualType();
8409
}
8410
8411
// If both operands have arithmetic type, do the usual arithmetic conversions
8412
// to find a common type: C99 6.5.15p3,5.
8413
if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8414
// Disallow invalid arithmetic conversions, such as those between bit-
8415
// precise integers types of different sizes, or between a bit-precise
8416
// integer and another type.
8417
if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8418
Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8419
<< LHSTy << RHSTy << LHS.get()->getSourceRange()
8420
<< RHS.get()->getSourceRange();
8421
return QualType();
8422
}
8423
8424
LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8425
RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8426
8427
return ResTy;
8428
}
8429
8430
// If both operands are the same structure or union type, the result is that
8431
// type.
8432
if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8433
if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8434
if (LHSRT->getDecl() == RHSRT->getDecl())
8435
// "If both the operands have structure or union type, the result has
8436
// that type." This implies that CV qualifiers are dropped.
8437
return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8438
RHSTy.getUnqualifiedType());
8439
// FIXME: Type of conditional expression must be complete in C mode.
8440
}
8441
8442
// C99 6.5.15p5: "If both operands have void type, the result has void type."
8443
// The following || allows only one side to be void (a GCC-ism).
8444
if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8445
QualType ResTy;
8446
if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8447
ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8448
} else if (RHSTy->isVoidType()) {
8449
ResTy = RHSTy;
8450
Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8451
<< RHS.get()->getSourceRange();
8452
} else {
8453
ResTy = LHSTy;
8454
Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8455
<< LHS.get()->getSourceRange();
8456
}
8457
LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8458
RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8459
return ResTy;
8460
}
8461
8462
// C23 6.5.15p7:
8463
// ... if both the second and third operands have nullptr_t type, the
8464
// result also has that type.
8465
if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8466
return ResTy;
8467
8468
// C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8469
// the type of the other operand."
8470
if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8471
if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8472
8473
// All objective-c pointer type analysis is done here.
8474
QualType compositeType =
8475
ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8476
if (LHS.isInvalid() || RHS.isInvalid())
8477
return QualType();
8478
if (!compositeType.isNull())
8479
return compositeType;
8480
8481
8482
// Handle block pointer types.
8483
if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8484
return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8485
QuestionLoc);
8486
8487
// Check constraints for C object pointers types (C99 6.5.15p3,6).
8488
if (LHSTy->isPointerType() && RHSTy->isPointerType())
8489
return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8490
QuestionLoc);
8491
8492
// GCC compatibility: soften pointer/integer mismatch. Note that
8493
// null pointers have been filtered out by this point.
8494
if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8495
/*IsIntFirstExpr=*/true))
8496
return RHSTy;
8497
if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8498
/*IsIntFirstExpr=*/false))
8499
return LHSTy;
8500
8501
// Emit a better diagnostic if one of the expressions is a null pointer
8502
// constant and the other is not a pointer type. In this case, the user most
8503
// likely forgot to take the address of the other expression.
8504
if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8505
return QualType();
8506
8507
// Finally, if the LHS and RHS types are canonically the same type, we can
8508
// use the common sugared type.
8509
if (Context.hasSameType(LHSTy, RHSTy))
8510
return Context.getCommonSugaredType(LHSTy, RHSTy);
8511
8512
// Otherwise, the operands are not compatible.
8513
Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8514
<< LHSTy << RHSTy << LHS.get()->getSourceRange()
8515
<< RHS.get()->getSourceRange();
8516
return QualType();
8517
}
8518
8519
/// SuggestParentheses - Emit a note with a fixit hint that wraps
8520
/// ParenRange in parentheses.
8521
static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8522
const PartialDiagnostic &Note,
8523
SourceRange ParenRange) {
8524
SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8525
if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8526
EndLoc.isValid()) {
8527
Self.Diag(Loc, Note)
8528
<< FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8529
<< FixItHint::CreateInsertion(EndLoc, ")");
8530
} else {
8531
// We can't display the parentheses, so just show the bare note.
8532
Self.Diag(Loc, Note) << ParenRange;
8533
}
8534
}
8535
8536
static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8537
return BinaryOperator::isAdditiveOp(Opc) ||
8538
BinaryOperator::isMultiplicativeOp(Opc) ||
8539
BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8540
// This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8541
// not any of the logical operators. Bitwise-xor is commonly used as a
8542
// logical-xor because there is no logical-xor operator. The logical
8543
// operators, including uses of xor, have a high false positive rate for
8544
// precedence warnings.
8545
}
8546
8547
/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8548
/// expression, either using a built-in or overloaded operator,
8549
/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8550
/// expression.
8551
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
8552
const Expr **RHSExprs) {
8553
// Don't strip parenthesis: we should not warn if E is in parenthesis.
8554
E = E->IgnoreImpCasts();
8555
E = E->IgnoreConversionOperatorSingleStep();
8556
E = E->IgnoreImpCasts();
8557
if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8558
E = MTE->getSubExpr();
8559
E = E->IgnoreImpCasts();
8560
}
8561
8562
// Built-in binary operator.
8563
if (const auto *OP = dyn_cast<BinaryOperator>(E);
8564
OP && IsArithmeticOp(OP->getOpcode())) {
8565
*Opcode = OP->getOpcode();
8566
*RHSExprs = OP->getRHS();
8567
return true;
8568
}
8569
8570
// Overloaded operator.
8571
if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8572
if (Call->getNumArgs() != 2)
8573
return false;
8574
8575
// Make sure this is really a binary operator that is safe to pass into
8576
// BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8577
OverloadedOperatorKind OO = Call->getOperator();
8578
if (OO < OO_Plus || OO > OO_Arrow ||
8579
OO == OO_PlusPlus || OO == OO_MinusMinus)
8580
return false;
8581
8582
BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8583
if (IsArithmeticOp(OpKind)) {
8584
*Opcode = OpKind;
8585
*RHSExprs = Call->getArg(1);
8586
return true;
8587
}
8588
}
8589
8590
return false;
8591
}
8592
8593
/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8594
/// or is a logical expression such as (x==y) which has int type, but is
8595
/// commonly interpreted as boolean.
8596
static bool ExprLooksBoolean(const Expr *E) {
8597
E = E->IgnoreParenImpCasts();
8598
8599
if (E->getType()->isBooleanType())
8600
return true;
8601
if (const auto *OP = dyn_cast<BinaryOperator>(E))
8602
return OP->isComparisonOp() || OP->isLogicalOp();
8603
if (const auto *OP = dyn_cast<UnaryOperator>(E))
8604
return OP->getOpcode() == UO_LNot;
8605
if (E->getType()->isPointerType())
8606
return true;
8607
// FIXME: What about overloaded operator calls returning "unspecified boolean
8608
// type"s (commonly pointer-to-members)?
8609
8610
return false;
8611
}
8612
8613
/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8614
/// and binary operator are mixed in a way that suggests the programmer assumed
8615
/// the conditional operator has higher precedence, for example:
8616
/// "int x = a + someBinaryCondition ? 1 : 2".
8617
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
8618
Expr *Condition, const Expr *LHSExpr,
8619
const Expr *RHSExpr) {
8620
BinaryOperatorKind CondOpcode;
8621
const Expr *CondRHS;
8622
8623
if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8624
return;
8625
if (!ExprLooksBoolean(CondRHS))
8626
return;
8627
8628
// The condition is an arithmetic binary expression, with a right-
8629
// hand side that looks boolean, so warn.
8630
8631
unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8632
? diag::warn_precedence_bitwise_conditional
8633
: diag::warn_precedence_conditional;
8634
8635
Self.Diag(OpLoc, DiagID)
8636
<< Condition->getSourceRange()
8637
<< BinaryOperator::getOpcodeStr(CondOpcode);
8638
8639
SuggestParentheses(
8640
Self, OpLoc,
8641
Self.PDiag(diag::note_precedence_silence)
8642
<< BinaryOperator::getOpcodeStr(CondOpcode),
8643
SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8644
8645
SuggestParentheses(Self, OpLoc,
8646
Self.PDiag(diag::note_precedence_conditional_first),
8647
SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8648
}
8649
8650
/// Compute the nullability of a conditional expression.
8651
static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8652
QualType LHSTy, QualType RHSTy,
8653
ASTContext &Ctx) {
8654
if (!ResTy->isAnyPointerType())
8655
return ResTy;
8656
8657
auto GetNullability = [](QualType Ty) {
8658
std::optional<NullabilityKind> Kind = Ty->getNullability();
8659
if (Kind) {
8660
// For our purposes, treat _Nullable_result as _Nullable.
8661
if (*Kind == NullabilityKind::NullableResult)
8662
return NullabilityKind::Nullable;
8663
return *Kind;
8664
}
8665
return NullabilityKind::Unspecified;
8666
};
8667
8668
auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8669
NullabilityKind MergedKind;
8670
8671
// Compute nullability of a binary conditional expression.
8672
if (IsBin) {
8673
if (LHSKind == NullabilityKind::NonNull)
8674
MergedKind = NullabilityKind::NonNull;
8675
else
8676
MergedKind = RHSKind;
8677
// Compute nullability of a normal conditional expression.
8678
} else {
8679
if (LHSKind == NullabilityKind::Nullable ||
8680
RHSKind == NullabilityKind::Nullable)
8681
MergedKind = NullabilityKind::Nullable;
8682
else if (LHSKind == NullabilityKind::NonNull)
8683
MergedKind = RHSKind;
8684
else if (RHSKind == NullabilityKind::NonNull)
8685
MergedKind = LHSKind;
8686
else
8687
MergedKind = NullabilityKind::Unspecified;
8688
}
8689
8690
// Return if ResTy already has the correct nullability.
8691
if (GetNullability(ResTy) == MergedKind)
8692
return ResTy;
8693
8694
// Strip all nullability from ResTy.
8695
while (ResTy->getNullability())
8696
ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8697
8698
// Create a new AttributedType with the new nullability kind.
8699
auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8700
return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8701
}
8702
8703
ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8704
SourceLocation ColonLoc,
8705
Expr *CondExpr, Expr *LHSExpr,
8706
Expr *RHSExpr) {
8707
if (!Context.isDependenceAllowed()) {
8708
// C cannot handle TypoExpr nodes in the condition because it
8709
// doesn't handle dependent types properly, so make sure any TypoExprs have
8710
// been dealt with before checking the operands.
8711
ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8712
ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8713
ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8714
8715
if (!CondResult.isUsable())
8716
return ExprError();
8717
8718
if (LHSExpr) {
8719
if (!LHSResult.isUsable())
8720
return ExprError();
8721
}
8722
8723
if (!RHSResult.isUsable())
8724
return ExprError();
8725
8726
CondExpr = CondResult.get();
8727
LHSExpr = LHSResult.get();
8728
RHSExpr = RHSResult.get();
8729
}
8730
8731
// If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8732
// was the condition.
8733
OpaqueValueExpr *opaqueValue = nullptr;
8734
Expr *commonExpr = nullptr;
8735
if (!LHSExpr) {
8736
commonExpr = CondExpr;
8737
// Lower out placeholder types first. This is important so that we don't
8738
// try to capture a placeholder. This happens in few cases in C++; such
8739
// as Objective-C++'s dictionary subscripting syntax.
8740
if (commonExpr->hasPlaceholderType()) {
8741
ExprResult result = CheckPlaceholderExpr(commonExpr);
8742
if (!result.isUsable()) return ExprError();
8743
commonExpr = result.get();
8744
}
8745
// We usually want to apply unary conversions *before* saving, except
8746
// in the special case of a C++ l-value conditional.
8747
if (!(getLangOpts().CPlusPlus
8748
&& !commonExpr->isTypeDependent()
8749
&& commonExpr->getValueKind() == RHSExpr->getValueKind()
8750
&& commonExpr->isGLValue()
8751
&& commonExpr->isOrdinaryOrBitFieldObject()
8752
&& RHSExpr->isOrdinaryOrBitFieldObject()
8753
&& Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8754
ExprResult commonRes = UsualUnaryConversions(commonExpr);
8755
if (commonRes.isInvalid())
8756
return ExprError();
8757
commonExpr = commonRes.get();
8758
}
8759
8760
// If the common expression is a class or array prvalue, materialize it
8761
// so that we can safely refer to it multiple times.
8762
if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8763
commonExpr->getType()->isArrayType())) {
8764
ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8765
if (MatExpr.isInvalid())
8766
return ExprError();
8767
commonExpr = MatExpr.get();
8768
}
8769
8770
opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8771
commonExpr->getType(),
8772
commonExpr->getValueKind(),
8773
commonExpr->getObjectKind(),
8774
commonExpr);
8775
LHSExpr = CondExpr = opaqueValue;
8776
}
8777
8778
QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8779
ExprValueKind VK = VK_PRValue;
8780
ExprObjectKind OK = OK_Ordinary;
8781
ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8782
QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8783
VK, OK, QuestionLoc);
8784
if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8785
RHS.isInvalid())
8786
return ExprError();
8787
8788
DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8789
RHS.get());
8790
8791
CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8792
8793
result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8794
Context);
8795
8796
if (!commonExpr)
8797
return new (Context)
8798
ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8799
RHS.get(), result, VK, OK);
8800
8801
return new (Context) BinaryConditionalOperator(
8802
commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8803
ColonLoc, result, VK, OK);
8804
}
8805
8806
bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
8807
unsigned FromAttributes = 0, ToAttributes = 0;
8808
if (const auto *FromFn =
8809
dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8810
FromAttributes =
8811
FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8812
if (const auto *ToFn =
8813
dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
8814
ToAttributes =
8815
ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8816
8817
return FromAttributes != ToAttributes;
8818
}
8819
8820
// Check if we have a conversion between incompatible cmse function pointer
8821
// types, that is, a conversion between a function pointer with the
8822
// cmse_nonsecure_call attribute and one without.
8823
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8824
QualType ToType) {
8825
if (const auto *ToFn =
8826
dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8827
if (const auto *FromFn =
8828
dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8829
FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8830
FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8831
8832
return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8833
}
8834
}
8835
return false;
8836
}
8837
8838
// checkPointerTypesForAssignment - This is a very tricky routine (despite
8839
// being closely modeled after the C99 spec:-). The odd characteristic of this
8840
// routine is it effectively iqnores the qualifiers on the top level pointee.
8841
// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8842
// FIXME: add a couple examples in this comment.
8843
static Sema::AssignConvertType
8844
checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
8845
SourceLocation Loc) {
8846
assert(LHSType.isCanonical() && "LHS not canonicalized!");
8847
assert(RHSType.isCanonical() && "RHS not canonicalized!");
8848
8849
// get the "pointed to" type (ignoring qualifiers at the top level)
8850
const Type *lhptee, *rhptee;
8851
Qualifiers lhq, rhq;
8852
std::tie(lhptee, lhq) =
8853
cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8854
std::tie(rhptee, rhq) =
8855
cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8856
8857
Sema::AssignConvertType ConvTy = Sema::Compatible;
8858
8859
// C99 6.5.16.1p1: This following citation is common to constraints
8860
// 3 & 4 (below). ...and the type *pointed to* by the left has all the
8861
// qualifiers of the type *pointed to* by the right;
8862
8863
// As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8864
if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8865
lhq.compatiblyIncludesObjCLifetime(rhq)) {
8866
// Ignore lifetime for further calculation.
8867
lhq.removeObjCLifetime();
8868
rhq.removeObjCLifetime();
8869
}
8870
8871
if (!lhq.compatiblyIncludes(rhq)) {
8872
// Treat address-space mismatches as fatal.
8873
if (!lhq.isAddressSpaceSupersetOf(rhq))
8874
return Sema::IncompatiblePointerDiscardsQualifiers;
8875
8876
// It's okay to add or remove GC or lifetime qualifiers when converting to
8877
// and from void*.
8878
else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8879
.compatiblyIncludes(
8880
rhq.withoutObjCGCAttr().withoutObjCLifetime())
8881
&& (lhptee->isVoidType() || rhptee->isVoidType()))
8882
; // keep old
8883
8884
// Treat lifetime mismatches as fatal.
8885
else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8886
ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8887
8888
// For GCC/MS compatibility, other qualifier mismatches are treated
8889
// as still compatible in C.
8890
else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8891
}
8892
8893
// C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8894
// incomplete type and the other is a pointer to a qualified or unqualified
8895
// version of void...
8896
if (lhptee->isVoidType()) {
8897
if (rhptee->isIncompleteOrObjectType())
8898
return ConvTy;
8899
8900
// As an extension, we allow cast to/from void* to function pointer.
8901
assert(rhptee->isFunctionType());
8902
return Sema::FunctionVoidPointer;
8903
}
8904
8905
if (rhptee->isVoidType()) {
8906
if (lhptee->isIncompleteOrObjectType())
8907
return ConvTy;
8908
8909
// As an extension, we allow cast to/from void* to function pointer.
8910
assert(lhptee->isFunctionType());
8911
return Sema::FunctionVoidPointer;
8912
}
8913
8914
if (!S.Diags.isIgnored(
8915
diag::warn_typecheck_convert_incompatible_function_pointer_strict,
8916
Loc) &&
8917
RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
8918
!S.IsFunctionConversion(RHSType, LHSType, RHSType))
8919
return Sema::IncompatibleFunctionPointerStrict;
8920
8921
// C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8922
// unqualified versions of compatible types, ...
8923
QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8924
if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8925
// Check if the pointee types are compatible ignoring the sign.
8926
// We explicitly check for char so that we catch "char" vs
8927
// "unsigned char" on systems where "char" is unsigned.
8928
if (lhptee->isCharType())
8929
ltrans = S.Context.UnsignedCharTy;
8930
else if (lhptee->hasSignedIntegerRepresentation())
8931
ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8932
8933
if (rhptee->isCharType())
8934
rtrans = S.Context.UnsignedCharTy;
8935
else if (rhptee->hasSignedIntegerRepresentation())
8936
rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8937
8938
if (ltrans == rtrans) {
8939
// Types are compatible ignoring the sign. Qualifier incompatibility
8940
// takes priority over sign incompatibility because the sign
8941
// warning can be disabled.
8942
if (ConvTy != Sema::Compatible)
8943
return ConvTy;
8944
8945
return Sema::IncompatiblePointerSign;
8946
}
8947
8948
// If we are a multi-level pointer, it's possible that our issue is simply
8949
// one of qualification - e.g. char ** -> const char ** is not allowed. If
8950
// the eventual target type is the same and the pointers have the same
8951
// level of indirection, this must be the issue.
8952
if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8953
do {
8954
std::tie(lhptee, lhq) =
8955
cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8956
std::tie(rhptee, rhq) =
8957
cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8958
8959
// Inconsistent address spaces at this point is invalid, even if the
8960
// address spaces would be compatible.
8961
// FIXME: This doesn't catch address space mismatches for pointers of
8962
// different nesting levels, like:
8963
// __local int *** a;
8964
// int ** b = a;
8965
// It's not clear how to actually determine when such pointers are
8966
// invalidly incompatible.
8967
if (lhq.getAddressSpace() != rhq.getAddressSpace())
8968
return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8969
8970
} while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8971
8972
if (lhptee == rhptee)
8973
return Sema::IncompatibleNestedPointerQualifiers;
8974
}
8975
8976
// General pointer incompatibility takes priority over qualifiers.
8977
if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8978
return Sema::IncompatibleFunctionPointer;
8979
return Sema::IncompatiblePointer;
8980
}
8981
if (!S.getLangOpts().CPlusPlus &&
8982
S.IsFunctionConversion(ltrans, rtrans, ltrans))
8983
return Sema::IncompatibleFunctionPointer;
8984
if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8985
return Sema::IncompatibleFunctionPointer;
8986
if (S.IsInvalidSMECallConversion(rtrans, ltrans))
8987
return Sema::IncompatibleFunctionPointer;
8988
return ConvTy;
8989
}
8990
8991
/// checkBlockPointerTypesForAssignment - This routine determines whether two
8992
/// block pointer types are compatible or whether a block and normal pointer
8993
/// are compatible. It is more restrict than comparing two function pointer
8994
// types.
8995
static Sema::AssignConvertType
8996
checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8997
QualType RHSType) {
8998
assert(LHSType.isCanonical() && "LHS not canonicalized!");
8999
assert(RHSType.isCanonical() && "RHS not canonicalized!");
9000
9001
QualType lhptee, rhptee;
9002
9003
// get the "pointed to" type (ignoring qualifiers at the top level)
9004
lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9005
rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9006
9007
// In C++, the types have to match exactly.
9008
if (S.getLangOpts().CPlusPlus)
9009
return Sema::IncompatibleBlockPointer;
9010
9011
Sema::AssignConvertType ConvTy = Sema::Compatible;
9012
9013
// For blocks we enforce that qualifiers are identical.
9014
Qualifiers LQuals = lhptee.getLocalQualifiers();
9015
Qualifiers RQuals = rhptee.getLocalQualifiers();
9016
if (S.getLangOpts().OpenCL) {
9017
LQuals.removeAddressSpace();
9018
RQuals.removeAddressSpace();
9019
}
9020
if (LQuals != RQuals)
9021
ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9022
9023
// FIXME: OpenCL doesn't define the exact compile time semantics for a block
9024
// assignment.
9025
// The current behavior is similar to C++ lambdas. A block might be
9026
// assigned to a variable iff its return type and parameters are compatible
9027
// (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9028
// an assignment. Presumably it should behave in way that a function pointer
9029
// assignment does in C, so for each parameter and return type:
9030
// * CVR and address space of LHS should be a superset of CVR and address
9031
// space of RHS.
9032
// * unqualified types should be compatible.
9033
if (S.getLangOpts().OpenCL) {
9034
if (!S.Context.typesAreBlockPointerCompatible(
9035
S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9036
S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9037
return Sema::IncompatibleBlockPointer;
9038
} else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9039
return Sema::IncompatibleBlockPointer;
9040
9041
return ConvTy;
9042
}
9043
9044
/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9045
/// for assignment compatibility.
9046
static Sema::AssignConvertType
9047
checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9048
QualType RHSType) {
9049
assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9050
assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9051
9052
if (LHSType->isObjCBuiltinType()) {
9053
// Class is not compatible with ObjC object pointers.
9054
if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9055
!RHSType->isObjCQualifiedClassType())
9056
return Sema::IncompatiblePointer;
9057
return Sema::Compatible;
9058
}
9059
if (RHSType->isObjCBuiltinType()) {
9060
if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9061
!LHSType->isObjCQualifiedClassType())
9062
return Sema::IncompatiblePointer;
9063
return Sema::Compatible;
9064
}
9065
QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9066
QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9067
9068
if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9069
// make an exception for id<P>
9070
!LHSType->isObjCQualifiedIdType())
9071
return Sema::CompatiblePointerDiscardsQualifiers;
9072
9073
if (S.Context.typesAreCompatible(LHSType, RHSType))
9074
return Sema::Compatible;
9075
if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9076
return Sema::IncompatibleObjCQualifiedId;
9077
return Sema::IncompatiblePointer;
9078
}
9079
9080
Sema::AssignConvertType
9081
Sema::CheckAssignmentConstraints(SourceLocation Loc,
9082
QualType LHSType, QualType RHSType) {
9083
// Fake up an opaque expression. We don't actually care about what
9084
// cast operations are required, so if CheckAssignmentConstraints
9085
// adds casts to this they'll be wasted, but fortunately that doesn't
9086
// usually happen on valid code.
9087
OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9088
ExprResult RHSPtr = &RHSExpr;
9089
CastKind K;
9090
9091
return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9092
}
9093
9094
/// This helper function returns true if QT is a vector type that has element
9095
/// type ElementType.
9096
static bool isVector(QualType QT, QualType ElementType) {
9097
if (const VectorType *VT = QT->getAs<VectorType>())
9098
return VT->getElementType().getCanonicalType() == ElementType;
9099
return false;
9100
}
9101
9102
/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9103
/// has code to accommodate several GCC extensions when type checking
9104
/// pointers. Here are some objectionable examples that GCC considers warnings:
9105
///
9106
/// int a, *pint;
9107
/// short *pshort;
9108
/// struct foo *pfoo;
9109
///
9110
/// pint = pshort; // warning: assignment from incompatible pointer type
9111
/// a = pint; // warning: assignment makes integer from pointer without a cast
9112
/// pint = a; // warning: assignment makes pointer from integer without a cast
9113
/// pint = pfoo; // warning: assignment from incompatible pointer type
9114
///
9115
/// As a result, the code for dealing with pointers is more complex than the
9116
/// C99 spec dictates.
9117
///
9118
/// Sets 'Kind' for any result kind except Incompatible.
9119
Sema::AssignConvertType
9120
Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9121
CastKind &Kind, bool ConvertRHS) {
9122
QualType RHSType = RHS.get()->getType();
9123
QualType OrigLHSType = LHSType;
9124
9125
// Get canonical types. We're not formatting these types, just comparing
9126
// them.
9127
LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9128
RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9129
9130
// Common case: no conversion required.
9131
if (LHSType == RHSType) {
9132
Kind = CK_NoOp;
9133
return Compatible;
9134
}
9135
9136
// If the LHS has an __auto_type, there are no additional type constraints
9137
// to be worried about.
9138
if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9139
if (AT->isGNUAutoType()) {
9140
Kind = CK_NoOp;
9141
return Compatible;
9142
}
9143
}
9144
9145
// If we have an atomic type, try a non-atomic assignment, then just add an
9146
// atomic qualification step.
9147
if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9148
Sema::AssignConvertType result =
9149
CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9150
if (result != Compatible)
9151
return result;
9152
if (Kind != CK_NoOp && ConvertRHS)
9153
RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9154
Kind = CK_NonAtomicToAtomic;
9155
return Compatible;
9156
}
9157
9158
// If the left-hand side is a reference type, then we are in a
9159
// (rare!) case where we've allowed the use of references in C,
9160
// e.g., as a parameter type in a built-in function. In this case,
9161
// just make sure that the type referenced is compatible with the
9162
// right-hand side type. The caller is responsible for adjusting
9163
// LHSType so that the resulting expression does not have reference
9164
// type.
9165
if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9166
if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9167
Kind = CK_LValueBitCast;
9168
return Compatible;
9169
}
9170
return Incompatible;
9171
}
9172
9173
// Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9174
// to the same ExtVector type.
9175
if (LHSType->isExtVectorType()) {
9176
if (RHSType->isExtVectorType())
9177
return Incompatible;
9178
if (RHSType->isArithmeticType()) {
9179
// CK_VectorSplat does T -> vector T, so first cast to the element type.
9180
if (ConvertRHS)
9181
RHS = prepareVectorSplat(LHSType, RHS.get());
9182
Kind = CK_VectorSplat;
9183
return Compatible;
9184
}
9185
}
9186
9187
// Conversions to or from vector type.
9188
if (LHSType->isVectorType() || RHSType->isVectorType()) {
9189
if (LHSType->isVectorType() && RHSType->isVectorType()) {
9190
// Allow assignments of an AltiVec vector type to an equivalent GCC
9191
// vector type and vice versa
9192
if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9193
Kind = CK_BitCast;
9194
return Compatible;
9195
}
9196
9197
// If we are allowing lax vector conversions, and LHS and RHS are both
9198
// vectors, the total size only needs to be the same. This is a bitcast;
9199
// no bits are changed but the result type is different.
9200
if (isLaxVectorConversion(RHSType, LHSType)) {
9201
// The default for lax vector conversions with Altivec vectors will
9202
// change, so if we are converting between vector types where
9203
// at least one is an Altivec vector, emit a warning.
9204
if (Context.getTargetInfo().getTriple().isPPC() &&
9205
anyAltivecTypes(RHSType, LHSType) &&
9206
!Context.areCompatibleVectorTypes(RHSType, LHSType))
9207
Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9208
<< RHSType << LHSType;
9209
Kind = CK_BitCast;
9210
return IncompatibleVectors;
9211
}
9212
}
9213
9214
// When the RHS comes from another lax conversion (e.g. binops between
9215
// scalars and vectors) the result is canonicalized as a vector. When the
9216
// LHS is also a vector, the lax is allowed by the condition above. Handle
9217
// the case where LHS is a scalar.
9218
if (LHSType->isScalarType()) {
9219
const VectorType *VecType = RHSType->getAs<VectorType>();
9220
if (VecType && VecType->getNumElements() == 1 &&
9221
isLaxVectorConversion(RHSType, LHSType)) {
9222
if (Context.getTargetInfo().getTriple().isPPC() &&
9223
(VecType->getVectorKind() == VectorKind::AltiVecVector ||
9224
VecType->getVectorKind() == VectorKind::AltiVecBool ||
9225
VecType->getVectorKind() == VectorKind::AltiVecPixel))
9226
Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9227
<< RHSType << LHSType;
9228
ExprResult *VecExpr = &RHS;
9229
*VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9230
Kind = CK_BitCast;
9231
return Compatible;
9232
}
9233
}
9234
9235
// Allow assignments between fixed-length and sizeless SVE vectors.
9236
if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9237
(LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9238
if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9239
Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9240
Kind = CK_BitCast;
9241
return Compatible;
9242
}
9243
9244
// Allow assignments between fixed-length and sizeless RVV vectors.
9245
if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9246
(LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9247
if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9248
Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9249
Kind = CK_BitCast;
9250
return Compatible;
9251
}
9252
}
9253
9254
return Incompatible;
9255
}
9256
9257
// Diagnose attempts to convert between __ibm128, __float128 and long double
9258
// where such conversions currently can't be handled.
9259
if (unsupportedTypeConversion(*this, LHSType, RHSType))
9260
return Incompatible;
9261
9262
// Disallow assigning a _Complex to a real type in C++ mode since it simply
9263
// discards the imaginary part.
9264
if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9265
!LHSType->getAs<ComplexType>())
9266
return Incompatible;
9267
9268
// Arithmetic conversions.
9269
if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9270
!(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9271
if (ConvertRHS)
9272
Kind = PrepareScalarCast(RHS, LHSType);
9273
return Compatible;
9274
}
9275
9276
// Conversions to normal pointers.
9277
if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9278
// U* -> T*
9279
if (isa<PointerType>(RHSType)) {
9280
LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9281
LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9282
if (AddrSpaceL != AddrSpaceR)
9283
Kind = CK_AddressSpaceConversion;
9284
else if (Context.hasCvrSimilarType(RHSType, LHSType))
9285
Kind = CK_NoOp;
9286
else
9287
Kind = CK_BitCast;
9288
return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9289
RHS.get()->getBeginLoc());
9290
}
9291
9292
// int -> T*
9293
if (RHSType->isIntegerType()) {
9294
Kind = CK_IntegralToPointer; // FIXME: null?
9295
return IntToPointer;
9296
}
9297
9298
// C pointers are not compatible with ObjC object pointers,
9299
// with two exceptions:
9300
if (isa<ObjCObjectPointerType>(RHSType)) {
9301
// - conversions to void*
9302
if (LHSPointer->getPointeeType()->isVoidType()) {
9303
Kind = CK_BitCast;
9304
return Compatible;
9305
}
9306
9307
// - conversions from 'Class' to the redefinition type
9308
if (RHSType->isObjCClassType() &&
9309
Context.hasSameType(LHSType,
9310
Context.getObjCClassRedefinitionType())) {
9311
Kind = CK_BitCast;
9312
return Compatible;
9313
}
9314
9315
Kind = CK_BitCast;
9316
return IncompatiblePointer;
9317
}
9318
9319
// U^ -> void*
9320
if (RHSType->getAs<BlockPointerType>()) {
9321
if (LHSPointer->getPointeeType()->isVoidType()) {
9322
LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9323
LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9324
->getPointeeType()
9325
.getAddressSpace();
9326
Kind =
9327
AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9328
return Compatible;
9329
}
9330
}
9331
9332
return Incompatible;
9333
}
9334
9335
// Conversions to block pointers.
9336
if (isa<BlockPointerType>(LHSType)) {
9337
// U^ -> T^
9338
if (RHSType->isBlockPointerType()) {
9339
LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9340
->getPointeeType()
9341
.getAddressSpace();
9342
LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9343
->getPointeeType()
9344
.getAddressSpace();
9345
Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9346
return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9347
}
9348
9349
// int or null -> T^
9350
if (RHSType->isIntegerType()) {
9351
Kind = CK_IntegralToPointer; // FIXME: null
9352
return IntToBlockPointer;
9353
}
9354
9355
// id -> T^
9356
if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9357
Kind = CK_AnyPointerToBlockPointerCast;
9358
return Compatible;
9359
}
9360
9361
// void* -> T^
9362
if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9363
if (RHSPT->getPointeeType()->isVoidType()) {
9364
Kind = CK_AnyPointerToBlockPointerCast;
9365
return Compatible;
9366
}
9367
9368
return Incompatible;
9369
}
9370
9371
// Conversions to Objective-C pointers.
9372
if (isa<ObjCObjectPointerType>(LHSType)) {
9373
// A* -> B*
9374
if (RHSType->isObjCObjectPointerType()) {
9375
Kind = CK_BitCast;
9376
Sema::AssignConvertType result =
9377
checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9378
if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9379
result == Compatible &&
9380
!ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9381
result = IncompatibleObjCWeakRef;
9382
return result;
9383
}
9384
9385
// int or null -> A*
9386
if (RHSType->isIntegerType()) {
9387
Kind = CK_IntegralToPointer; // FIXME: null
9388
return IntToPointer;
9389
}
9390
9391
// In general, C pointers are not compatible with ObjC object pointers,
9392
// with two exceptions:
9393
if (isa<PointerType>(RHSType)) {
9394
Kind = CK_CPointerToObjCPointerCast;
9395
9396
// - conversions from 'void*'
9397
if (RHSType->isVoidPointerType()) {
9398
return Compatible;
9399
}
9400
9401
// - conversions to 'Class' from its redefinition type
9402
if (LHSType->isObjCClassType() &&
9403
Context.hasSameType(RHSType,
9404
Context.getObjCClassRedefinitionType())) {
9405
return Compatible;
9406
}
9407
9408
return IncompatiblePointer;
9409
}
9410
9411
// Only under strict condition T^ is compatible with an Objective-C pointer.
9412
if (RHSType->isBlockPointerType() &&
9413
LHSType->isBlockCompatibleObjCPointerType(Context)) {
9414
if (ConvertRHS)
9415
maybeExtendBlockObject(RHS);
9416
Kind = CK_BlockPointerToObjCPointerCast;
9417
return Compatible;
9418
}
9419
9420
return Incompatible;
9421
}
9422
9423
// Conversion to nullptr_t (C23 only)
9424
if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9425
RHS.get()->isNullPointerConstant(Context,
9426
Expr::NPC_ValueDependentIsNull)) {
9427
// null -> nullptr_t
9428
Kind = CK_NullToPointer;
9429
return Compatible;
9430
}
9431
9432
// Conversions from pointers that are not covered by the above.
9433
if (isa<PointerType>(RHSType)) {
9434
// T* -> _Bool
9435
if (LHSType == Context.BoolTy) {
9436
Kind = CK_PointerToBoolean;
9437
return Compatible;
9438
}
9439
9440
// T* -> int
9441
if (LHSType->isIntegerType()) {
9442
Kind = CK_PointerToIntegral;
9443
return PointerToInt;
9444
}
9445
9446
return Incompatible;
9447
}
9448
9449
// Conversions from Objective-C pointers that are not covered by the above.
9450
if (isa<ObjCObjectPointerType>(RHSType)) {
9451
// T* -> _Bool
9452
if (LHSType == Context.BoolTy) {
9453
Kind = CK_PointerToBoolean;
9454
return Compatible;
9455
}
9456
9457
// T* -> int
9458
if (LHSType->isIntegerType()) {
9459
Kind = CK_PointerToIntegral;
9460
return PointerToInt;
9461
}
9462
9463
return Incompatible;
9464
}
9465
9466
// struct A -> struct B
9467
if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9468
if (Context.typesAreCompatible(LHSType, RHSType)) {
9469
Kind = CK_NoOp;
9470
return Compatible;
9471
}
9472
}
9473
9474
if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9475
Kind = CK_IntToOCLSampler;
9476
return Compatible;
9477
}
9478
9479
return Incompatible;
9480
}
9481
9482
/// Constructs a transparent union from an expression that is
9483
/// used to initialize the transparent union.
9484
static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9485
ExprResult &EResult, QualType UnionType,
9486
FieldDecl *Field) {
9487
// Build an initializer list that designates the appropriate member
9488
// of the transparent union.
9489
Expr *E = EResult.get();
9490
InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9491
E, SourceLocation());
9492
Initializer->setType(UnionType);
9493
Initializer->setInitializedFieldInUnion(Field);
9494
9495
// Build a compound literal constructing a value of the transparent
9496
// union type from this initializer list.
9497
TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9498
EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9499
VK_PRValue, Initializer, false);
9500
}
9501
9502
Sema::AssignConvertType
9503
Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9504
ExprResult &RHS) {
9505
QualType RHSType = RHS.get()->getType();
9506
9507
// If the ArgType is a Union type, we want to handle a potential
9508
// transparent_union GCC extension.
9509
const RecordType *UT = ArgType->getAsUnionType();
9510
if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9511
return Incompatible;
9512
9513
// The field to initialize within the transparent union.
9514
RecordDecl *UD = UT->getDecl();
9515
FieldDecl *InitField = nullptr;
9516
// It's compatible if the expression matches any of the fields.
9517
for (auto *it : UD->fields()) {
9518
if (it->getType()->isPointerType()) {
9519
// If the transparent union contains a pointer type, we allow:
9520
// 1) void pointer
9521
// 2) null pointer constant
9522
if (RHSType->isPointerType())
9523
if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9524
RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9525
InitField = it;
9526
break;
9527
}
9528
9529
if (RHS.get()->isNullPointerConstant(Context,
9530
Expr::NPC_ValueDependentIsNull)) {
9531
RHS = ImpCastExprToType(RHS.get(), it->getType(),
9532
CK_NullToPointer);
9533
InitField = it;
9534
break;
9535
}
9536
}
9537
9538
CastKind Kind;
9539
if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9540
== Compatible) {
9541
RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9542
InitField = it;
9543
break;
9544
}
9545
}
9546
9547
if (!InitField)
9548
return Incompatible;
9549
9550
ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9551
return Compatible;
9552
}
9553
9554
Sema::AssignConvertType
9555
Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9556
bool Diagnose,
9557
bool DiagnoseCFAudited,
9558
bool ConvertRHS) {
9559
// We need to be able to tell the caller whether we diagnosed a problem, if
9560
// they ask us to issue diagnostics.
9561
assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9562
9563
// If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9564
// we can't avoid *all* modifications at the moment, so we need some somewhere
9565
// to put the updated value.
9566
ExprResult LocalRHS = CallerRHS;
9567
ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9568
9569
if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9570
if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9571
if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9572
!LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9573
Diag(RHS.get()->getExprLoc(),
9574
diag::warn_noderef_to_dereferenceable_pointer)
9575
<< RHS.get()->getSourceRange();
9576
}
9577
}
9578
}
9579
9580
if (getLangOpts().CPlusPlus) {
9581
if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9582
// C++ 5.17p3: If the left operand is not of class type, the
9583
// expression is implicitly converted (C++ 4) to the
9584
// cv-unqualified type of the left operand.
9585
QualType RHSType = RHS.get()->getType();
9586
if (Diagnose) {
9587
RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9588
AA_Assigning);
9589
} else {
9590
ImplicitConversionSequence ICS =
9591
TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9592
/*SuppressUserConversions=*/false,
9593
AllowedExplicit::None,
9594
/*InOverloadResolution=*/false,
9595
/*CStyle=*/false,
9596
/*AllowObjCWritebackConversion=*/false);
9597
if (ICS.isFailure())
9598
return Incompatible;
9599
RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9600
ICS, AA_Assigning);
9601
}
9602
if (RHS.isInvalid())
9603
return Incompatible;
9604
Sema::AssignConvertType result = Compatible;
9605
if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9606
!ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9607
result = IncompatibleObjCWeakRef;
9608
return result;
9609
}
9610
9611
// FIXME: Currently, we fall through and treat C++ classes like C
9612
// structures.
9613
// FIXME: We also fall through for atomics; not sure what should
9614
// happen there, though.
9615
} else if (RHS.get()->getType() == Context.OverloadTy) {
9616
// As a set of extensions to C, we support overloading on functions. These
9617
// functions need to be resolved here.
9618
DeclAccessPair DAP;
9619
if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9620
RHS.get(), LHSType, /*Complain=*/false, DAP))
9621
RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9622
else
9623
return Incompatible;
9624
}
9625
9626
// This check seems unnatural, however it is necessary to ensure the proper
9627
// conversion of functions/arrays. If the conversion were done for all
9628
// DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9629
// expressions that suppress this implicit conversion (&, sizeof). This needs
9630
// to happen before we check for null pointer conversions because C does not
9631
// undergo the same implicit conversions as C++ does above (by the calls to
9632
// TryImplicitConversion() and PerformImplicitConversion()) which insert the
9633
// lvalue to rvalue cast before checking for null pointer constraints. This
9634
// addresses code like: nullptr_t val; int *ptr; ptr = val;
9635
//
9636
// Suppress this for references: C++ 8.5.3p5.
9637
if (!LHSType->isReferenceType()) {
9638
// FIXME: We potentially allocate here even if ConvertRHS is false.
9639
RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9640
if (RHS.isInvalid())
9641
return Incompatible;
9642
}
9643
9644
// The constraints are expressed in terms of the atomic, qualified, or
9645
// unqualified type of the LHS.
9646
QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9647
9648
// C99 6.5.16.1p1: the left operand is a pointer and the right is
9649
// a null pointer constant <C23>or its type is nullptr_t;</C23>.
9650
if ((LHSTypeAfterConversion->isPointerType() ||
9651
LHSTypeAfterConversion->isObjCObjectPointerType() ||
9652
LHSTypeAfterConversion->isBlockPointerType()) &&
9653
((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9654
RHS.get()->isNullPointerConstant(Context,
9655
Expr::NPC_ValueDependentIsNull))) {
9656
if (Diagnose || ConvertRHS) {
9657
CastKind Kind;
9658
CXXCastPath Path;
9659
CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9660
/*IgnoreBaseAccess=*/false, Diagnose);
9661
if (ConvertRHS)
9662
RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9663
}
9664
return Compatible;
9665
}
9666
// C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9667
// unqualified bool, and the right operand is a pointer or its type is
9668
// nullptr_t.
9669
if (getLangOpts().C23 && LHSType->isBooleanType() &&
9670
RHS.get()->getType()->isNullPtrType()) {
9671
// NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9672
// only handles nullptr -> _Bool due to needing an extra conversion
9673
// step.
9674
// We model this by converting from nullptr -> void * and then let the
9675
// conversion from void * -> _Bool happen naturally.
9676
if (Diagnose || ConvertRHS) {
9677
CastKind Kind;
9678
CXXCastPath Path;
9679
CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
9680
/*IgnoreBaseAccess=*/false, Diagnose);
9681
if (ConvertRHS)
9682
RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9683
&Path);
9684
}
9685
}
9686
9687
// OpenCL queue_t type assignment.
9688
if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9689
Context, Expr::NPC_ValueDependentIsNull)) {
9690
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9691
return Compatible;
9692
}
9693
9694
CastKind Kind;
9695
Sema::AssignConvertType result =
9696
CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9697
9698
// C99 6.5.16.1p2: The value of the right operand is converted to the
9699
// type of the assignment expression.
9700
// CheckAssignmentConstraints allows the left-hand side to be a reference,
9701
// so that we can use references in built-in functions even in C.
9702
// The getNonReferenceType() call makes sure that the resulting expression
9703
// does not have reference type.
9704
if (result != Incompatible && RHS.get()->getType() != LHSType) {
9705
QualType Ty = LHSType.getNonLValueExprType(Context);
9706
Expr *E = RHS.get();
9707
9708
// Check for various Objective-C errors. If we are not reporting
9709
// diagnostics and just checking for errors, e.g., during overload
9710
// resolution, return Incompatible to indicate the failure.
9711
if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9712
ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9713
CheckedConversionKind::Implicit, Diagnose,
9714
DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9715
if (!Diagnose)
9716
return Incompatible;
9717
}
9718
if (getLangOpts().ObjC &&
9719
(ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9720
E->getType(), E, Diagnose) ||
9721
ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9722
if (!Diagnose)
9723
return Incompatible;
9724
// Replace the expression with a corrected version and continue so we
9725
// can find further errors.
9726
RHS = E;
9727
return Compatible;
9728
}
9729
9730
if (ConvertRHS)
9731
RHS = ImpCastExprToType(E, Ty, Kind);
9732
}
9733
9734
return result;
9735
}
9736
9737
namespace {
9738
/// The original operand to an operator, prior to the application of the usual
9739
/// arithmetic conversions and converting the arguments of a builtin operator
9740
/// candidate.
9741
struct OriginalOperand {
9742
explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9743
if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9744
Op = MTE->getSubExpr();
9745
if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9746
Op = BTE->getSubExpr();
9747
if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9748
Orig = ICE->getSubExprAsWritten();
9749
Conversion = ICE->getConversionFunction();
9750
}
9751
}
9752
9753
QualType getType() const { return Orig->getType(); }
9754
9755
Expr *Orig;
9756
NamedDecl *Conversion;
9757
};
9758
}
9759
9760
QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9761
ExprResult &RHS) {
9762
OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9763
9764
Diag(Loc, diag::err_typecheck_invalid_operands)
9765
<< OrigLHS.getType() << OrigRHS.getType()
9766
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9767
9768
// If a user-defined conversion was applied to either of the operands prior
9769
// to applying the built-in operator rules, tell the user about it.
9770
if (OrigLHS.Conversion) {
9771
Diag(OrigLHS.Conversion->getLocation(),
9772
diag::note_typecheck_invalid_operands_converted)
9773
<< 0 << LHS.get()->getType();
9774
}
9775
if (OrigRHS.Conversion) {
9776
Diag(OrigRHS.Conversion->getLocation(),
9777
diag::note_typecheck_invalid_operands_converted)
9778
<< 1 << RHS.get()->getType();
9779
}
9780
9781
return QualType();
9782
}
9783
9784
QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9785
ExprResult &RHS) {
9786
QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9787
QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9788
9789
bool LHSNatVec = LHSType->isVectorType();
9790
bool RHSNatVec = RHSType->isVectorType();
9791
9792
if (!(LHSNatVec && RHSNatVec)) {
9793
Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9794
Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9795
Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9796
<< 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9797
<< Vector->getSourceRange();
9798
return QualType();
9799
}
9800
9801
Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9802
<< 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9803
<< RHS.get()->getSourceRange();
9804
9805
return QualType();
9806
}
9807
9808
/// Try to convert a value of non-vector type to a vector type by converting
9809
/// the type to the element type of the vector and then performing a splat.
9810
/// If the language is OpenCL, we only use conversions that promote scalar
9811
/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9812
/// for float->int.
9813
///
9814
/// OpenCL V2.0 6.2.6.p2:
9815
/// An error shall occur if any scalar operand type has greater rank
9816
/// than the type of the vector element.
9817
///
9818
/// \param scalar - if non-null, actually perform the conversions
9819
/// \return true if the operation fails (but without diagnosing the failure)
9820
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9821
QualType scalarTy,
9822
QualType vectorEltTy,
9823
QualType vectorTy,
9824
unsigned &DiagID) {
9825
// The conversion to apply to the scalar before splatting it,
9826
// if necessary.
9827
CastKind scalarCast = CK_NoOp;
9828
9829
if (vectorEltTy->isIntegralType(S.Context)) {
9830
if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9831
(scalarTy->isIntegerType() &&
9832
S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9833
DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9834
return true;
9835
}
9836
if (!scalarTy->isIntegralType(S.Context))
9837
return true;
9838
scalarCast = CK_IntegralCast;
9839
} else if (vectorEltTy->isRealFloatingType()) {
9840
if (scalarTy->isRealFloatingType()) {
9841
if (S.getLangOpts().OpenCL &&
9842
S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9843
DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9844
return true;
9845
}
9846
scalarCast = CK_FloatingCast;
9847
}
9848
else if (scalarTy->isIntegralType(S.Context))
9849
scalarCast = CK_IntegralToFloating;
9850
else
9851
return true;
9852
} else {
9853
return true;
9854
}
9855
9856
// Adjust scalar if desired.
9857
if (scalar) {
9858
if (scalarCast != CK_NoOp)
9859
*scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9860
*scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9861
}
9862
return false;
9863
}
9864
9865
/// Convert vector E to a vector with the same number of elements but different
9866
/// element type.
9867
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9868
const auto *VecTy = E->getType()->getAs<VectorType>();
9869
assert(VecTy && "Expression E must be a vector");
9870
QualType NewVecTy =
9871
VecTy->isExtVectorType()
9872
? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
9873
: S.Context.getVectorType(ElementType, VecTy->getNumElements(),
9874
VecTy->getVectorKind());
9875
9876
// Look through the implicit cast. Return the subexpression if its type is
9877
// NewVecTy.
9878
if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9879
if (ICE->getSubExpr()->getType() == NewVecTy)
9880
return ICE->getSubExpr();
9881
9882
auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9883
return S.ImpCastExprToType(E, NewVecTy, Cast);
9884
}
9885
9886
/// Test if a (constant) integer Int can be casted to another integer type
9887
/// IntTy without losing precision.
9888
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9889
QualType OtherIntTy) {
9890
QualType IntTy = Int->get()->getType().getUnqualifiedType();
9891
9892
// Reject cases where the value of the Int is unknown as that would
9893
// possibly cause truncation, but accept cases where the scalar can be
9894
// demoted without loss of precision.
9895
Expr::EvalResult EVResult;
9896
bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9897
int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9898
bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9899
bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9900
9901
if (CstInt) {
9902
// If the scalar is constant and is of a higher order and has more active
9903
// bits that the vector element type, reject it.
9904
llvm::APSInt Result = EVResult.Val.getInt();
9905
unsigned NumBits = IntSigned
9906
? (Result.isNegative() ? Result.getSignificantBits()
9907
: Result.getActiveBits())
9908
: Result.getActiveBits();
9909
if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9910
return true;
9911
9912
// If the signedness of the scalar type and the vector element type
9913
// differs and the number of bits is greater than that of the vector
9914
// element reject it.
9915
return (IntSigned != OtherIntSigned &&
9916
NumBits > S.Context.getIntWidth(OtherIntTy));
9917
}
9918
9919
// Reject cases where the value of the scalar is not constant and it's
9920
// order is greater than that of the vector element type.
9921
return (Order < 0);
9922
}
9923
9924
/// Test if a (constant) integer Int can be casted to floating point type
9925
/// FloatTy without losing precision.
9926
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9927
QualType FloatTy) {
9928
QualType IntTy = Int->get()->getType().getUnqualifiedType();
9929
9930
// Determine if the integer constant can be expressed as a floating point
9931
// number of the appropriate type.
9932
Expr::EvalResult EVResult;
9933
bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9934
9935
uint64_t Bits = 0;
9936
if (CstInt) {
9937
// Reject constants that would be truncated if they were converted to
9938
// the floating point type. Test by simple to/from conversion.
9939
// FIXME: Ideally the conversion to an APFloat and from an APFloat
9940
// could be avoided if there was a convertFromAPInt method
9941
// which could signal back if implicit truncation occurred.
9942
llvm::APSInt Result = EVResult.Val.getInt();
9943
llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9944
Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9945
llvm::APFloat::rmTowardZero);
9946
llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9947
!IntTy->hasSignedIntegerRepresentation());
9948
bool Ignored = false;
9949
Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9950
&Ignored);
9951
if (Result != ConvertBack)
9952
return true;
9953
} else {
9954
// Reject types that cannot be fully encoded into the mantissa of
9955
// the float.
9956
Bits = S.Context.getTypeSize(IntTy);
9957
unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9958
S.Context.getFloatTypeSemantics(FloatTy));
9959
if (Bits > FloatPrec)
9960
return true;
9961
}
9962
9963
return false;
9964
}
9965
9966
/// Attempt to convert and splat Scalar into a vector whose types matches
9967
/// Vector following GCC conversion rules. The rule is that implicit
9968
/// conversion can occur when Scalar can be casted to match Vector's element
9969
/// type without causing truncation of Scalar.
9970
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9971
ExprResult *Vector) {
9972
QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9973
QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9974
QualType VectorEltTy;
9975
9976
if (const auto *VT = VectorTy->getAs<VectorType>()) {
9977
assert(!isa<ExtVectorType>(VT) &&
9978
"ExtVectorTypes should not be handled here!");
9979
VectorEltTy = VT->getElementType();
9980
} else if (VectorTy->isSveVLSBuiltinType()) {
9981
VectorEltTy =
9982
VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
9983
} else {
9984
llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
9985
}
9986
9987
// Reject cases where the vector element type or the scalar element type are
9988
// not integral or floating point types.
9989
if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9990
return true;
9991
9992
// The conversion to apply to the scalar before splatting it,
9993
// if necessary.
9994
CastKind ScalarCast = CK_NoOp;
9995
9996
// Accept cases where the vector elements are integers and the scalar is
9997
// an integer.
9998
// FIXME: Notionally if the scalar was a floating point value with a precise
9999
// integral representation, we could cast it to an appropriate integer
10000
// type and then perform the rest of the checks here. GCC will perform
10001
// this conversion in some cases as determined by the input language.
10002
// We should accept it on a language independent basis.
10003
if (VectorEltTy->isIntegralType(S.Context) &&
10004
ScalarTy->isIntegralType(S.Context) &&
10005
S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10006
10007
if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10008
return true;
10009
10010
ScalarCast = CK_IntegralCast;
10011
} else if (VectorEltTy->isIntegralType(S.Context) &&
10012
ScalarTy->isRealFloatingType()) {
10013
if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10014
ScalarCast = CK_FloatingToIntegral;
10015
else
10016
return true;
10017
} else if (VectorEltTy->isRealFloatingType()) {
10018
if (ScalarTy->isRealFloatingType()) {
10019
10020
// Reject cases where the scalar type is not a constant and has a higher
10021
// Order than the vector element type.
10022
llvm::APFloat Result(0.0);
10023
10024
// Determine whether this is a constant scalar. In the event that the
10025
// value is dependent (and thus cannot be evaluated by the constant
10026
// evaluator), skip the evaluation. This will then diagnose once the
10027
// expression is instantiated.
10028
bool CstScalar = Scalar->get()->isValueDependent() ||
10029
Scalar->get()->EvaluateAsFloat(Result, S.Context);
10030
int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10031
if (!CstScalar && Order < 0)
10032
return true;
10033
10034
// If the scalar cannot be safely casted to the vector element type,
10035
// reject it.
10036
if (CstScalar) {
10037
bool Truncated = false;
10038
Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10039
llvm::APFloat::rmNearestTiesToEven, &Truncated);
10040
if (Truncated)
10041
return true;
10042
}
10043
10044
ScalarCast = CK_FloatingCast;
10045
} else if (ScalarTy->isIntegralType(S.Context)) {
10046
if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10047
return true;
10048
10049
ScalarCast = CK_IntegralToFloating;
10050
} else
10051
return true;
10052
} else if (ScalarTy->isEnumeralType())
10053
return true;
10054
10055
// Adjust scalar if desired.
10056
if (ScalarCast != CK_NoOp)
10057
*Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10058
*Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10059
return false;
10060
}
10061
10062
QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10063
SourceLocation Loc, bool IsCompAssign,
10064
bool AllowBothBool,
10065
bool AllowBoolConversions,
10066
bool AllowBoolOperation,
10067
bool ReportInvalid) {
10068
if (!IsCompAssign) {
10069
LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10070
if (LHS.isInvalid())
10071
return QualType();
10072
}
10073
RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10074
if (RHS.isInvalid())
10075
return QualType();
10076
10077
// For conversion purposes, we ignore any qualifiers.
10078
// For example, "const float" and "float" are equivalent.
10079
QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10080
QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10081
10082
const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10083
const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10084
assert(LHSVecType || RHSVecType);
10085
10086
// AltiVec-style "vector bool op vector bool" combinations are allowed
10087
// for some operators but not others.
10088
if (!AllowBothBool && LHSVecType &&
10089
LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10090
RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10091
return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10092
10093
// This operation may not be performed on boolean vectors.
10094
if (!AllowBoolOperation &&
10095
(LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10096
return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10097
10098
// If the vector types are identical, return.
10099
if (Context.hasSameType(LHSType, RHSType))
10100
return Context.getCommonSugaredType(LHSType, RHSType);
10101
10102
// If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10103
if (LHSVecType && RHSVecType &&
10104
Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10105
if (isa<ExtVectorType>(LHSVecType)) {
10106
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10107
return LHSType;
10108
}
10109
10110
if (!IsCompAssign)
10111
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10112
return RHSType;
10113
}
10114
10115
// AllowBoolConversions says that bool and non-bool AltiVec vectors
10116
// can be mixed, with the result being the non-bool type. The non-bool
10117
// operand must have integer element type.
10118
if (AllowBoolConversions && LHSVecType && RHSVecType &&
10119
LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10120
(Context.getTypeSize(LHSVecType->getElementType()) ==
10121
Context.getTypeSize(RHSVecType->getElementType()))) {
10122
if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10123
LHSVecType->getElementType()->isIntegerType() &&
10124
RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10125
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10126
return LHSType;
10127
}
10128
if (!IsCompAssign &&
10129
LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10130
RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10131
RHSVecType->getElementType()->isIntegerType()) {
10132
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10133
return RHSType;
10134
}
10135
}
10136
10137
// Expressions containing fixed-length and sizeless SVE/RVV vectors are
10138
// invalid since the ambiguity can affect the ABI.
10139
auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10140
unsigned &SVEorRVV) {
10141
const VectorType *VecType = SecondType->getAs<VectorType>();
10142
SVEorRVV = 0;
10143
if (FirstType->isSizelessBuiltinType() && VecType) {
10144
if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10145
VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10146
return true;
10147
if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10148
VecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10149
SVEorRVV = 1;
10150
return true;
10151
}
10152
}
10153
10154
return false;
10155
};
10156
10157
unsigned SVEorRVV;
10158
if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10159
IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10160
Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10161
<< SVEorRVV << LHSType << RHSType;
10162
return QualType();
10163
}
10164
10165
// Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10166
// invalid since the ambiguity can affect the ABI.
10167
auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10168
unsigned &SVEorRVV) {
10169
const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10170
const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10171
10172
SVEorRVV = 0;
10173
if (FirstVecType && SecondVecType) {
10174
if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10175
if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10176
SecondVecType->getVectorKind() ==
10177
VectorKind::SveFixedLengthPredicate)
10178
return true;
10179
if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10180
SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10181
SVEorRVV = 1;
10182
return true;
10183
}
10184
}
10185
return false;
10186
}
10187
10188
if (SecondVecType &&
10189
SecondVecType->getVectorKind() == VectorKind::Generic) {
10190
if (FirstType->isSVESizelessBuiltinType())
10191
return true;
10192
if (FirstType->isRVVSizelessBuiltinType()) {
10193
SVEorRVV = 1;
10194
return true;
10195
}
10196
}
10197
10198
return false;
10199
};
10200
10201
if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10202
IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10203
Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10204
<< SVEorRVV << LHSType << RHSType;
10205
return QualType();
10206
}
10207
10208
// If there's a vector type and a scalar, try to convert the scalar to
10209
// the vector element type and splat.
10210
unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10211
if (!RHSVecType) {
10212
if (isa<ExtVectorType>(LHSVecType)) {
10213
if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10214
LHSVecType->getElementType(), LHSType,
10215
DiagID))
10216
return LHSType;
10217
} else {
10218
if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10219
return LHSType;
10220
}
10221
}
10222
if (!LHSVecType) {
10223
if (isa<ExtVectorType>(RHSVecType)) {
10224
if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10225
LHSType, RHSVecType->getElementType(),
10226
RHSType, DiagID))
10227
return RHSType;
10228
} else {
10229
if (LHS.get()->isLValue() ||
10230
!tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10231
return RHSType;
10232
}
10233
}
10234
10235
// FIXME: The code below also handles conversion between vectors and
10236
// non-scalars, we should break this down into fine grained specific checks
10237
// and emit proper diagnostics.
10238
QualType VecType = LHSVecType ? LHSType : RHSType;
10239
const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10240
QualType OtherType = LHSVecType ? RHSType : LHSType;
10241
ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10242
if (isLaxVectorConversion(OtherType, VecType)) {
10243
if (Context.getTargetInfo().getTriple().isPPC() &&
10244
anyAltivecTypes(RHSType, LHSType) &&
10245
!Context.areCompatibleVectorTypes(RHSType, LHSType))
10246
Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10247
// If we're allowing lax vector conversions, only the total (data) size
10248
// needs to be the same. For non compound assignment, if one of the types is
10249
// scalar, the result is always the vector type.
10250
if (!IsCompAssign) {
10251
*OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10252
return VecType;
10253
// In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10254
// any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10255
// type. Note that this is already done by non-compound assignments in
10256
// CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10257
// <1 x T> -> T. The result is also a vector type.
10258
} else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10259
(OtherType->isScalarType() && VT->getNumElements() == 1)) {
10260
ExprResult *RHSExpr = &RHS;
10261
*RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10262
return VecType;
10263
}
10264
}
10265
10266
// Okay, the expression is invalid.
10267
10268
// If there's a non-vector, non-real operand, diagnose that.
10269
if ((!RHSVecType && !RHSType->isRealType()) ||
10270
(!LHSVecType && !LHSType->isRealType())) {
10271
Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10272
<< LHSType << RHSType
10273
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10274
return QualType();
10275
}
10276
10277
// OpenCL V1.1 6.2.6.p1:
10278
// If the operands are of more than one vector type, then an error shall
10279
// occur. Implicit conversions between vector types are not permitted, per
10280
// section 6.2.1.
10281
if (getLangOpts().OpenCL &&
10282
RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10283
LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10284
Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10285
<< RHSType;
10286
return QualType();
10287
}
10288
10289
10290
// If there is a vector type that is not a ExtVector and a scalar, we reach
10291
// this point if scalar could not be converted to the vector's element type
10292
// without truncation.
10293
if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10294
(LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10295
QualType Scalar = LHSVecType ? RHSType : LHSType;
10296
QualType Vector = LHSVecType ? LHSType : RHSType;
10297
unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10298
Diag(Loc,
10299
diag::err_typecheck_vector_not_convertable_implict_truncation)
10300
<< ScalarOrVector << Scalar << Vector;
10301
10302
return QualType();
10303
}
10304
10305
// Otherwise, use the generic diagnostic.
10306
Diag(Loc, DiagID)
10307
<< LHSType << RHSType
10308
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10309
return QualType();
10310
}
10311
10312
QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10313
SourceLocation Loc,
10314
bool IsCompAssign,
10315
ArithConvKind OperationKind) {
10316
if (!IsCompAssign) {
10317
LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10318
if (LHS.isInvalid())
10319
return QualType();
10320
}
10321
RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10322
if (RHS.isInvalid())
10323
return QualType();
10324
10325
QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10326
QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10327
10328
const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10329
const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10330
10331
unsigned DiagID = diag::err_typecheck_invalid_operands;
10332
if ((OperationKind == ACK_Arithmetic) &&
10333
((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10334
(RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10335
Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10336
<< RHS.get()->getSourceRange();
10337
return QualType();
10338
}
10339
10340
if (Context.hasSameType(LHSType, RHSType))
10341
return LHSType;
10342
10343
if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10344
if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10345
return LHSType;
10346
}
10347
if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10348
if (LHS.get()->isLValue() ||
10349
!tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10350
return RHSType;
10351
}
10352
10353
if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10354
(!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10355
Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10356
<< LHSType << RHSType << LHS.get()->getSourceRange()
10357
<< RHS.get()->getSourceRange();
10358
return QualType();
10359
}
10360
10361
if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10362
Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10363
Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10364
Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10365
<< LHSType << RHSType << LHS.get()->getSourceRange()
10366
<< RHS.get()->getSourceRange();
10367
return QualType();
10368
}
10369
10370
if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10371
QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10372
QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10373
bool ScalarOrVector =
10374
LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10375
10376
Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10377
<< ScalarOrVector << Scalar << Vector;
10378
10379
return QualType();
10380
}
10381
10382
Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10383
<< RHS.get()->getSourceRange();
10384
return QualType();
10385
}
10386
10387
// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10388
// expression. These are mainly cases where the null pointer is used as an
10389
// integer instead of a pointer.
10390
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10391
SourceLocation Loc, bool IsCompare) {
10392
// The canonical way to check for a GNU null is with isNullPointerConstant,
10393
// but we use a bit of a hack here for speed; this is a relatively
10394
// hot path, and isNullPointerConstant is slow.
10395
bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10396
bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10397
10398
QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10399
10400
// Avoid analyzing cases where the result will either be invalid (and
10401
// diagnosed as such) or entirely valid and not something to warn about.
10402
if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10403
NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10404
return;
10405
10406
// Comparison operations would not make sense with a null pointer no matter
10407
// what the other expression is.
10408
if (!IsCompare) {
10409
S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10410
<< (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10411
<< (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10412
return;
10413
}
10414
10415
// The rest of the operations only make sense with a null pointer
10416
// if the other expression is a pointer.
10417
if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10418
NonNullType->canDecayToPointerType())
10419
return;
10420
10421
S.Diag(Loc, diag::warn_null_in_comparison_operation)
10422
<< LHSNull /* LHS is NULL */ << NonNullType
10423
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10424
}
10425
10426
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10427
SourceLocation Loc) {
10428
const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10429
const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10430
if (!LUE || !RUE)
10431
return;
10432
if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10433
RUE->getKind() != UETT_SizeOf)
10434
return;
10435
10436
const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10437
QualType LHSTy = LHSArg->getType();
10438
QualType RHSTy;
10439
10440
if (RUE->isArgumentType())
10441
RHSTy = RUE->getArgumentType().getNonReferenceType();
10442
else
10443
RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10444
10445
if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10446
if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10447
return;
10448
10449
S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10450
if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10451
if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10452
S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10453
<< LHSArgDecl;
10454
}
10455
} else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10456
QualType ArrayElemTy = ArrayTy->getElementType();
10457
if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10458
ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10459
RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10460
S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10461
return;
10462
S.Diag(Loc, diag::warn_division_sizeof_array)
10463
<< LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10464
if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10465
if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10466
S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10467
<< LHSArgDecl;
10468
}
10469
10470
S.Diag(Loc, diag::note_precedence_silence) << RHS;
10471
}
10472
}
10473
10474
static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10475
ExprResult &RHS,
10476
SourceLocation Loc, bool IsDiv) {
10477
// Check for division/remainder by zero.
10478
Expr::EvalResult RHSValue;
10479
if (!RHS.get()->isValueDependent() &&
10480
RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10481
RHSValue.Val.getInt() == 0)
10482
S.DiagRuntimeBehavior(Loc, RHS.get(),
10483
S.PDiag(diag::warn_remainder_division_by_zero)
10484
<< IsDiv << RHS.get()->getSourceRange());
10485
}
10486
10487
QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10488
SourceLocation Loc,
10489
bool IsCompAssign, bool IsDiv) {
10490
checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10491
10492
QualType LHSTy = LHS.get()->getType();
10493
QualType RHSTy = RHS.get()->getType();
10494
if (LHSTy->isVectorType() || RHSTy->isVectorType())
10495
return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10496
/*AllowBothBool*/ getLangOpts().AltiVec,
10497
/*AllowBoolConversions*/ false,
10498
/*AllowBooleanOperation*/ false,
10499
/*ReportInvalid*/ true);
10500
if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10501
return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10502
ACK_Arithmetic);
10503
if (!IsDiv &&
10504
(LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10505
return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10506
// For division, only matrix-by-scalar is supported. Other combinations with
10507
// matrix types are invalid.
10508
if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10509
return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10510
10511
QualType compType = UsualArithmeticConversions(
10512
LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10513
if (LHS.isInvalid() || RHS.isInvalid())
10514
return QualType();
10515
10516
10517
if (compType.isNull() || !compType->isArithmeticType())
10518
return InvalidOperands(Loc, LHS, RHS);
10519
if (IsDiv) {
10520
DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10521
DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10522
}
10523
return compType;
10524
}
10525
10526
QualType Sema::CheckRemainderOperands(
10527
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10528
checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10529
10530
if (LHS.get()->getType()->isVectorType() ||
10531
RHS.get()->getType()->isVectorType()) {
10532
if (LHS.get()->getType()->hasIntegerRepresentation() &&
10533
RHS.get()->getType()->hasIntegerRepresentation())
10534
return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10535
/*AllowBothBool*/ getLangOpts().AltiVec,
10536
/*AllowBoolConversions*/ false,
10537
/*AllowBooleanOperation*/ false,
10538
/*ReportInvalid*/ true);
10539
return InvalidOperands(Loc, LHS, RHS);
10540
}
10541
10542
if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10543
RHS.get()->getType()->isSveVLSBuiltinType()) {
10544
if (LHS.get()->getType()->hasIntegerRepresentation() &&
10545
RHS.get()->getType()->hasIntegerRepresentation())
10546
return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10547
ACK_Arithmetic);
10548
10549
return InvalidOperands(Loc, LHS, RHS);
10550
}
10551
10552
QualType compType = UsualArithmeticConversions(
10553
LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10554
if (LHS.isInvalid() || RHS.isInvalid())
10555
return QualType();
10556
10557
if (compType.isNull() || !compType->isIntegerType())
10558
return InvalidOperands(Loc, LHS, RHS);
10559
DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10560
return compType;
10561
}
10562
10563
/// Diagnose invalid arithmetic on two void pointers.
10564
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10565
Expr *LHSExpr, Expr *RHSExpr) {
10566
S.Diag(Loc, S.getLangOpts().CPlusPlus
10567
? diag::err_typecheck_pointer_arith_void_type
10568
: diag::ext_gnu_void_ptr)
10569
<< 1 /* two pointers */ << LHSExpr->getSourceRange()
10570
<< RHSExpr->getSourceRange();
10571
}
10572
10573
/// Diagnose invalid arithmetic on a void pointer.
10574
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10575
Expr *Pointer) {
10576
S.Diag(Loc, S.getLangOpts().CPlusPlus
10577
? diag::err_typecheck_pointer_arith_void_type
10578
: diag::ext_gnu_void_ptr)
10579
<< 0 /* one pointer */ << Pointer->getSourceRange();
10580
}
10581
10582
/// Diagnose invalid arithmetic on a null pointer.
10583
///
10584
/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10585
/// idiom, which we recognize as a GNU extension.
10586
///
10587
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10588
Expr *Pointer, bool IsGNUIdiom) {
10589
if (IsGNUIdiom)
10590
S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10591
<< Pointer->getSourceRange();
10592
else
10593
S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10594
<< S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10595
}
10596
10597
/// Diagnose invalid subraction on a null pointer.
10598
///
10599
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10600
Expr *Pointer, bool BothNull) {
10601
// Null - null is valid in C++ [expr.add]p7
10602
if (BothNull && S.getLangOpts().CPlusPlus)
10603
return;
10604
10605
// Is this s a macro from a system header?
10606
if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10607
return;
10608
10609
S.DiagRuntimeBehavior(Loc, Pointer,
10610
S.PDiag(diag::warn_pointer_sub_null_ptr)
10611
<< S.getLangOpts().CPlusPlus
10612
<< Pointer->getSourceRange());
10613
}
10614
10615
/// Diagnose invalid arithmetic on two function pointers.
10616
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10617
Expr *LHS, Expr *RHS) {
10618
assert(LHS->getType()->isAnyPointerType());
10619
assert(RHS->getType()->isAnyPointerType());
10620
S.Diag(Loc, S.getLangOpts().CPlusPlus
10621
? diag::err_typecheck_pointer_arith_function_type
10622
: diag::ext_gnu_ptr_func_arith)
10623
<< 1 /* two pointers */ << LHS->getType()->getPointeeType()
10624
// We only show the second type if it differs from the first.
10625
<< (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10626
RHS->getType())
10627
<< RHS->getType()->getPointeeType()
10628
<< LHS->getSourceRange() << RHS->getSourceRange();
10629
}
10630
10631
/// Diagnose invalid arithmetic on a function pointer.
10632
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10633
Expr *Pointer) {
10634
assert(Pointer->getType()->isAnyPointerType());
10635
S.Diag(Loc, S.getLangOpts().CPlusPlus
10636
? diag::err_typecheck_pointer_arith_function_type
10637
: diag::ext_gnu_ptr_func_arith)
10638
<< 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10639
<< 0 /* one pointer, so only one type */
10640
<< Pointer->getSourceRange();
10641
}
10642
10643
/// Emit error if Operand is incomplete pointer type
10644
///
10645
/// \returns True if pointer has incomplete type
10646
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10647
Expr *Operand) {
10648
QualType ResType = Operand->getType();
10649
if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10650
ResType = ResAtomicType->getValueType();
10651
10652
assert(ResType->isAnyPointerType());
10653
QualType PointeeTy = ResType->getPointeeType();
10654
return S.RequireCompleteSizedType(
10655
Loc, PointeeTy,
10656
diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10657
Operand->getSourceRange());
10658
}
10659
10660
/// Check the validity of an arithmetic pointer operand.
10661
///
10662
/// If the operand has pointer type, this code will check for pointer types
10663
/// which are invalid in arithmetic operations. These will be diagnosed
10664
/// appropriately, including whether or not the use is supported as an
10665
/// extension.
10666
///
10667
/// \returns True when the operand is valid to use (even if as an extension).
10668
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10669
Expr *Operand) {
10670
QualType ResType = Operand->getType();
10671
if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10672
ResType = ResAtomicType->getValueType();
10673
10674
if (!ResType->isAnyPointerType()) return true;
10675
10676
QualType PointeeTy = ResType->getPointeeType();
10677
if (PointeeTy->isVoidType()) {
10678
diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10679
return !S.getLangOpts().CPlusPlus;
10680
}
10681
if (PointeeTy->isFunctionType()) {
10682
diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10683
return !S.getLangOpts().CPlusPlus;
10684
}
10685
10686
if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10687
10688
return true;
10689
}
10690
10691
/// Check the validity of a binary arithmetic operation w.r.t. pointer
10692
/// operands.
10693
///
10694
/// This routine will diagnose any invalid arithmetic on pointer operands much
10695
/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10696
/// for emitting a single diagnostic even for operations where both LHS and RHS
10697
/// are (potentially problematic) pointers.
10698
///
10699
/// \returns True when the operand is valid to use (even if as an extension).
10700
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10701
Expr *LHSExpr, Expr *RHSExpr) {
10702
bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10703
bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10704
if (!isLHSPointer && !isRHSPointer) return true;
10705
10706
QualType LHSPointeeTy, RHSPointeeTy;
10707
if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10708
if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10709
10710
// if both are pointers check if operation is valid wrt address spaces
10711
if (isLHSPointer && isRHSPointer) {
10712
if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10713
S.Diag(Loc,
10714
diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10715
<< LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10716
<< LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10717
return false;
10718
}
10719
}
10720
10721
// Check for arithmetic on pointers to incomplete types.
10722
bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10723
bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10724
if (isLHSVoidPtr || isRHSVoidPtr) {
10725
if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10726
else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10727
else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10728
10729
return !S.getLangOpts().CPlusPlus;
10730
}
10731
10732
bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10733
bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10734
if (isLHSFuncPtr || isRHSFuncPtr) {
10735
if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10736
else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10737
RHSExpr);
10738
else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10739
10740
return !S.getLangOpts().CPlusPlus;
10741
}
10742
10743
if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10744
return false;
10745
if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10746
return false;
10747
10748
return true;
10749
}
10750
10751
/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10752
/// literal.
10753
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10754
Expr *LHSExpr, Expr *RHSExpr) {
10755
StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10756
Expr* IndexExpr = RHSExpr;
10757
if (!StrExpr) {
10758
StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10759
IndexExpr = LHSExpr;
10760
}
10761
10762
bool IsStringPlusInt = StrExpr &&
10763
IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10764
if (!IsStringPlusInt || IndexExpr->isValueDependent())
10765
return;
10766
10767
SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10768
Self.Diag(OpLoc, diag::warn_string_plus_int)
10769
<< DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10770
10771
// Only print a fixit for "str" + int, not for int + "str".
10772
if (IndexExpr == RHSExpr) {
10773
SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10774
Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10775
<< FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10776
<< FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10777
<< FixItHint::CreateInsertion(EndLoc, "]");
10778
} else
10779
Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10780
}
10781
10782
/// Emit a warning when adding a char literal to a string.
10783
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10784
Expr *LHSExpr, Expr *RHSExpr) {
10785
const Expr *StringRefExpr = LHSExpr;
10786
const CharacterLiteral *CharExpr =
10787
dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10788
10789
if (!CharExpr) {
10790
CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10791
StringRefExpr = RHSExpr;
10792
}
10793
10794
if (!CharExpr || !StringRefExpr)
10795
return;
10796
10797
const QualType StringType = StringRefExpr->getType();
10798
10799
// Return if not a PointerType.
10800
if (!StringType->isAnyPointerType())
10801
return;
10802
10803
// Return if not a CharacterType.
10804
if (!StringType->getPointeeType()->isAnyCharacterType())
10805
return;
10806
10807
ASTContext &Ctx = Self.getASTContext();
10808
SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10809
10810
const QualType CharType = CharExpr->getType();
10811
if (!CharType->isAnyCharacterType() &&
10812
CharType->isIntegerType() &&
10813
llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10814
Self.Diag(OpLoc, diag::warn_string_plus_char)
10815
<< DiagRange << Ctx.CharTy;
10816
} else {
10817
Self.Diag(OpLoc, diag::warn_string_plus_char)
10818
<< DiagRange << CharExpr->getType();
10819
}
10820
10821
// Only print a fixit for str + char, not for char + str.
10822
if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10823
SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10824
Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10825
<< FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10826
<< FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10827
<< FixItHint::CreateInsertion(EndLoc, "]");
10828
} else {
10829
Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10830
}
10831
}
10832
10833
/// Emit error when two pointers are incompatible.
10834
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10835
Expr *LHSExpr, Expr *RHSExpr) {
10836
assert(LHSExpr->getType()->isAnyPointerType());
10837
assert(RHSExpr->getType()->isAnyPointerType());
10838
S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10839
<< LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10840
<< RHSExpr->getSourceRange();
10841
}
10842
10843
// C99 6.5.6
10844
QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10845
SourceLocation Loc, BinaryOperatorKind Opc,
10846
QualType* CompLHSTy) {
10847
checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10848
10849
if (LHS.get()->getType()->isVectorType() ||
10850
RHS.get()->getType()->isVectorType()) {
10851
QualType compType =
10852
CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10853
/*AllowBothBool*/ getLangOpts().AltiVec,
10854
/*AllowBoolConversions*/ getLangOpts().ZVector,
10855
/*AllowBooleanOperation*/ false,
10856
/*ReportInvalid*/ true);
10857
if (CompLHSTy) *CompLHSTy = compType;
10858
return compType;
10859
}
10860
10861
if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10862
RHS.get()->getType()->isSveVLSBuiltinType()) {
10863
QualType compType =
10864
CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10865
if (CompLHSTy)
10866
*CompLHSTy = compType;
10867
return compType;
10868
}
10869
10870
if (LHS.get()->getType()->isConstantMatrixType() ||
10871
RHS.get()->getType()->isConstantMatrixType()) {
10872
QualType compType =
10873
CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10874
if (CompLHSTy)
10875
*CompLHSTy = compType;
10876
return compType;
10877
}
10878
10879
QualType compType = UsualArithmeticConversions(
10880
LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10881
if (LHS.isInvalid() || RHS.isInvalid())
10882
return QualType();
10883
10884
// Diagnose "string literal" '+' int and string '+' "char literal".
10885
if (Opc == BO_Add) {
10886
diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10887
diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10888
}
10889
10890
// handle the common case first (both operands are arithmetic).
10891
if (!compType.isNull() && compType->isArithmeticType()) {
10892
if (CompLHSTy) *CompLHSTy = compType;
10893
return compType;
10894
}
10895
10896
// Type-checking. Ultimately the pointer's going to be in PExp;
10897
// note that we bias towards the LHS being the pointer.
10898
Expr *PExp = LHS.get(), *IExp = RHS.get();
10899
10900
bool isObjCPointer;
10901
if (PExp->getType()->isPointerType()) {
10902
isObjCPointer = false;
10903
} else if (PExp->getType()->isObjCObjectPointerType()) {
10904
isObjCPointer = true;
10905
} else {
10906
std::swap(PExp, IExp);
10907
if (PExp->getType()->isPointerType()) {
10908
isObjCPointer = false;
10909
} else if (PExp->getType()->isObjCObjectPointerType()) {
10910
isObjCPointer = true;
10911
} else {
10912
return InvalidOperands(Loc, LHS, RHS);
10913
}
10914
}
10915
assert(PExp->getType()->isAnyPointerType());
10916
10917
if (!IExp->getType()->isIntegerType())
10918
return InvalidOperands(Loc, LHS, RHS);
10919
10920
// Adding to a null pointer results in undefined behavior.
10921
if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10922
Context, Expr::NPC_ValueDependentIsNotNull)) {
10923
// In C++ adding zero to a null pointer is defined.
10924
Expr::EvalResult KnownVal;
10925
if (!getLangOpts().CPlusPlus ||
10926
(!IExp->isValueDependent() &&
10927
(!IExp->EvaluateAsInt(KnownVal, Context) ||
10928
KnownVal.Val.getInt() != 0))) {
10929
// Check the conditions to see if this is the 'p = nullptr + n' idiom.
10930
bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10931
Context, BO_Add, PExp, IExp);
10932
diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10933
}
10934
}
10935
10936
if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10937
return QualType();
10938
10939
if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10940
return QualType();
10941
10942
// Arithmetic on label addresses is normally allowed, except when we add
10943
// a ptrauth signature to the addresses.
10944
if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
10945
Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
10946
<< /*addition*/ 1;
10947
return QualType();
10948
}
10949
10950
// Check array bounds for pointer arithemtic
10951
CheckArrayAccess(PExp, IExp);
10952
10953
if (CompLHSTy) {
10954
QualType LHSTy = Context.isPromotableBitField(LHS.get());
10955
if (LHSTy.isNull()) {
10956
LHSTy = LHS.get()->getType();
10957
if (Context.isPromotableIntegerType(LHSTy))
10958
LHSTy = Context.getPromotedIntegerType(LHSTy);
10959
}
10960
*CompLHSTy = LHSTy;
10961
}
10962
10963
return PExp->getType();
10964
}
10965
10966
// C99 6.5.6
10967
QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10968
SourceLocation Loc,
10969
QualType* CompLHSTy) {
10970
checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10971
10972
if (LHS.get()->getType()->isVectorType() ||
10973
RHS.get()->getType()->isVectorType()) {
10974
QualType compType =
10975
CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10976
/*AllowBothBool*/ getLangOpts().AltiVec,
10977
/*AllowBoolConversions*/ getLangOpts().ZVector,
10978
/*AllowBooleanOperation*/ false,
10979
/*ReportInvalid*/ true);
10980
if (CompLHSTy) *CompLHSTy = compType;
10981
return compType;
10982
}
10983
10984
if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10985
RHS.get()->getType()->isSveVLSBuiltinType()) {
10986
QualType compType =
10987
CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10988
if (CompLHSTy)
10989
*CompLHSTy = compType;
10990
return compType;
10991
}
10992
10993
if (LHS.get()->getType()->isConstantMatrixType() ||
10994
RHS.get()->getType()->isConstantMatrixType()) {
10995
QualType compType =
10996
CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10997
if (CompLHSTy)
10998
*CompLHSTy = compType;
10999
return compType;
11000
}
11001
11002
QualType compType = UsualArithmeticConversions(
11003
LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11004
if (LHS.isInvalid() || RHS.isInvalid())
11005
return QualType();
11006
11007
// Enforce type constraints: C99 6.5.6p3.
11008
11009
// Handle the common case first (both operands are arithmetic).
11010
if (!compType.isNull() && compType->isArithmeticType()) {
11011
if (CompLHSTy) *CompLHSTy = compType;
11012
return compType;
11013
}
11014
11015
// Either ptr - int or ptr - ptr.
11016
if (LHS.get()->getType()->isAnyPointerType()) {
11017
QualType lpointee = LHS.get()->getType()->getPointeeType();
11018
11019
// Diagnose bad cases where we step over interface counts.
11020
if (LHS.get()->getType()->isObjCObjectPointerType() &&
11021
checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11022
return QualType();
11023
11024
// Arithmetic on label addresses is normally allowed, except when we add
11025
// a ptrauth signature to the addresses.
11026
if (isa<AddrLabelExpr>(LHS.get()) &&
11027
getLangOpts().PointerAuthIndirectGotos) {
11028
Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11029
<< /*subtraction*/ 0;
11030
return QualType();
11031
}
11032
11033
// The result type of a pointer-int computation is the pointer type.
11034
if (RHS.get()->getType()->isIntegerType()) {
11035
// Subtracting from a null pointer should produce a warning.
11036
// The last argument to the diagnose call says this doesn't match the
11037
// GNU int-to-pointer idiom.
11038
if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11039
Expr::NPC_ValueDependentIsNotNull)) {
11040
// In C++ adding zero to a null pointer is defined.
11041
Expr::EvalResult KnownVal;
11042
if (!getLangOpts().CPlusPlus ||
11043
(!RHS.get()->isValueDependent() &&
11044
(!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11045
KnownVal.Val.getInt() != 0))) {
11046
diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11047
}
11048
}
11049
11050
if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11051
return QualType();
11052
11053
// Check array bounds for pointer arithemtic
11054
CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11055
/*AllowOnePastEnd*/true, /*IndexNegated*/true);
11056
11057
if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11058
return LHS.get()->getType();
11059
}
11060
11061
// Handle pointer-pointer subtractions.
11062
if (const PointerType *RHSPTy
11063
= RHS.get()->getType()->getAs<PointerType>()) {
11064
QualType rpointee = RHSPTy->getPointeeType();
11065
11066
if (getLangOpts().CPlusPlus) {
11067
// Pointee types must be the same: C++ [expr.add]
11068
if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11069
diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11070
}
11071
} else {
11072
// Pointee types must be compatible C99 6.5.6p3
11073
if (!Context.typesAreCompatible(
11074
Context.getCanonicalType(lpointee).getUnqualifiedType(),
11075
Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11076
diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11077
return QualType();
11078
}
11079
}
11080
11081
if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11082
LHS.get(), RHS.get()))
11083
return QualType();
11084
11085
bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11086
Context, Expr::NPC_ValueDependentIsNotNull);
11087
bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11088
Context, Expr::NPC_ValueDependentIsNotNull);
11089
11090
// Subtracting nullptr or from nullptr is suspect
11091
if (LHSIsNullPtr)
11092
diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11093
if (RHSIsNullPtr)
11094
diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11095
11096
// The pointee type may have zero size. As an extension, a structure or
11097
// union may have zero size or an array may have zero length. In this
11098
// case subtraction does not make sense.
11099
if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11100
CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11101
if (ElementSize.isZero()) {
11102
Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11103
<< rpointee.getUnqualifiedType()
11104
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11105
}
11106
}
11107
11108
if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11109
return Context.getPointerDiffType();
11110
}
11111
}
11112
11113
return InvalidOperands(Loc, LHS, RHS);
11114
}
11115
11116
static bool isScopedEnumerationType(QualType T) {
11117
if (const EnumType *ET = T->getAs<EnumType>())
11118
return ET->getDecl()->isScoped();
11119
return false;
11120
}
11121
11122
static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11123
SourceLocation Loc, BinaryOperatorKind Opc,
11124
QualType LHSType) {
11125
// OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11126
// so skip remaining warnings as we don't want to modify values within Sema.
11127
if (S.getLangOpts().OpenCL)
11128
return;
11129
11130
// Check right/shifter operand
11131
Expr::EvalResult RHSResult;
11132
if (RHS.get()->isValueDependent() ||
11133
!RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11134
return;
11135
llvm::APSInt Right = RHSResult.Val.getInt();
11136
11137
if (Right.isNegative()) {
11138
S.DiagRuntimeBehavior(Loc, RHS.get(),
11139
S.PDiag(diag::warn_shift_negative)
11140
<< RHS.get()->getSourceRange());
11141
return;
11142
}
11143
11144
QualType LHSExprType = LHS.get()->getType();
11145
uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11146
if (LHSExprType->isBitIntType())
11147
LeftSize = S.Context.getIntWidth(LHSExprType);
11148
else if (LHSExprType->isFixedPointType()) {
11149
auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11150
LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11151
}
11152
if (Right.uge(LeftSize)) {
11153
S.DiagRuntimeBehavior(Loc, RHS.get(),
11154
S.PDiag(diag::warn_shift_gt_typewidth)
11155
<< RHS.get()->getSourceRange());
11156
return;
11157
}
11158
11159
// FIXME: We probably need to handle fixed point types specially here.
11160
if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11161
return;
11162
11163
// When left shifting an ICE which is signed, we can check for overflow which
11164
// according to C++ standards prior to C++2a has undefined behavior
11165
// ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11166
// more than the maximum value representable in the result type, so never
11167
// warn for those. (FIXME: Unsigned left-shift overflow in a constant
11168
// expression is still probably a bug.)
11169
Expr::EvalResult LHSResult;
11170
if (LHS.get()->isValueDependent() ||
11171
LHSType->hasUnsignedIntegerRepresentation() ||
11172
!LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11173
return;
11174
llvm::APSInt Left = LHSResult.Val.getInt();
11175
11176
// Don't warn if signed overflow is defined, then all the rest of the
11177
// diagnostics will not be triggered because the behavior is defined.
11178
// Also don't warn in C++20 mode (and newer), as signed left shifts
11179
// always wrap and never overflow.
11180
if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11181
return;
11182
11183
// If LHS does not have a non-negative value then, the
11184
// behavior is undefined before C++2a. Warn about it.
11185
if (Left.isNegative()) {
11186
S.DiagRuntimeBehavior(Loc, LHS.get(),
11187
S.PDiag(diag::warn_shift_lhs_negative)
11188
<< LHS.get()->getSourceRange());
11189
return;
11190
}
11191
11192
llvm::APInt ResultBits =
11193
static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11194
if (ResultBits.ule(LeftSize))
11195
return;
11196
llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11197
Result = Result.shl(Right);
11198
11199
// Print the bit representation of the signed integer as an unsigned
11200
// hexadecimal number.
11201
SmallString<40> HexResult;
11202
Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11203
11204
// If we are only missing a sign bit, this is less likely to result in actual
11205
// bugs -- if the result is cast back to an unsigned type, it will have the
11206
// expected value. Thus we place this behind a different warning that can be
11207
// turned off separately if needed.
11208
if (ResultBits - 1 == LeftSize) {
11209
S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11210
<< HexResult << LHSType
11211
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11212
return;
11213
}
11214
11215
S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11216
<< HexResult.str() << Result.getSignificantBits() << LHSType
11217
<< Left.getBitWidth() << LHS.get()->getSourceRange()
11218
<< RHS.get()->getSourceRange();
11219
}
11220
11221
/// Return the resulting type when a vector is shifted
11222
/// by a scalar or vector shift amount.
11223
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11224
SourceLocation Loc, bool IsCompAssign) {
11225
// OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11226
if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11227
!LHS.get()->getType()->isVectorType()) {
11228
S.Diag(Loc, diag::err_shift_rhs_only_vector)
11229
<< RHS.get()->getType() << LHS.get()->getType()
11230
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11231
return QualType();
11232
}
11233
11234
if (!IsCompAssign) {
11235
LHS = S.UsualUnaryConversions(LHS.get());
11236
if (LHS.isInvalid()) return QualType();
11237
}
11238
11239
RHS = S.UsualUnaryConversions(RHS.get());
11240
if (RHS.isInvalid()) return QualType();
11241
11242
QualType LHSType = LHS.get()->getType();
11243
// Note that LHS might be a scalar because the routine calls not only in
11244
// OpenCL case.
11245
const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11246
QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11247
11248
// Note that RHS might not be a vector.
11249
QualType RHSType = RHS.get()->getType();
11250
const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11251
QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11252
11253
// Do not allow shifts for boolean vectors.
11254
if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11255
(RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11256
S.Diag(Loc, diag::err_typecheck_invalid_operands)
11257
<< LHS.get()->getType() << RHS.get()->getType()
11258
<< LHS.get()->getSourceRange();
11259
return QualType();
11260
}
11261
11262
// The operands need to be integers.
11263
if (!LHSEleType->isIntegerType()) {
11264
S.Diag(Loc, diag::err_typecheck_expect_int)
11265
<< LHS.get()->getType() << LHS.get()->getSourceRange();
11266
return QualType();
11267
}
11268
11269
if (!RHSEleType->isIntegerType()) {
11270
S.Diag(Loc, diag::err_typecheck_expect_int)
11271
<< RHS.get()->getType() << RHS.get()->getSourceRange();
11272
return QualType();
11273
}
11274
11275
if (!LHSVecTy) {
11276
assert(RHSVecTy);
11277
if (IsCompAssign)
11278
return RHSType;
11279
if (LHSEleType != RHSEleType) {
11280
LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11281
LHSEleType = RHSEleType;
11282
}
11283
QualType VecTy =
11284
S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11285
LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11286
LHSType = VecTy;
11287
} else if (RHSVecTy) {
11288
// OpenCL v1.1 s6.3.j says that for vector types, the operators
11289
// are applied component-wise. So if RHS is a vector, then ensure
11290
// that the number of elements is the same as LHS...
11291
if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11292
S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11293
<< LHS.get()->getType() << RHS.get()->getType()
11294
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11295
return QualType();
11296
}
11297
if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11298
const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11299
const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11300
if (LHSBT != RHSBT &&
11301
S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11302
S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11303
<< LHS.get()->getType() << RHS.get()->getType()
11304
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11305
}
11306
}
11307
} else {
11308
// ...else expand RHS to match the number of elements in LHS.
11309
QualType VecTy =
11310
S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11311
RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11312
}
11313
11314
return LHSType;
11315
}
11316
11317
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11318
ExprResult &RHS, SourceLocation Loc,
11319
bool IsCompAssign) {
11320
if (!IsCompAssign) {
11321
LHS = S.UsualUnaryConversions(LHS.get());
11322
if (LHS.isInvalid())
11323
return QualType();
11324
}
11325
11326
RHS = S.UsualUnaryConversions(RHS.get());
11327
if (RHS.isInvalid())
11328
return QualType();
11329
11330
QualType LHSType = LHS.get()->getType();
11331
const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11332
QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11333
? LHSBuiltinTy->getSveEltType(S.getASTContext())
11334
: LHSType;
11335
11336
// Note that RHS might not be a vector
11337
QualType RHSType = RHS.get()->getType();
11338
const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11339
QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11340
? RHSBuiltinTy->getSveEltType(S.getASTContext())
11341
: RHSType;
11342
11343
if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11344
(RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11345
S.Diag(Loc, diag::err_typecheck_invalid_operands)
11346
<< LHSType << RHSType << LHS.get()->getSourceRange();
11347
return QualType();
11348
}
11349
11350
if (!LHSEleType->isIntegerType()) {
11351
S.Diag(Loc, diag::err_typecheck_expect_int)
11352
<< LHS.get()->getType() << LHS.get()->getSourceRange();
11353
return QualType();
11354
}
11355
11356
if (!RHSEleType->isIntegerType()) {
11357
S.Diag(Loc, diag::err_typecheck_expect_int)
11358
<< RHS.get()->getType() << RHS.get()->getSourceRange();
11359
return QualType();
11360
}
11361
11362
if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11363
(S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11364
S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11365
S.Diag(Loc, diag::err_typecheck_invalid_operands)
11366
<< LHSType << RHSType << LHS.get()->getSourceRange()
11367
<< RHS.get()->getSourceRange();
11368
return QualType();
11369
}
11370
11371
if (!LHSType->isSveVLSBuiltinType()) {
11372
assert(RHSType->isSveVLSBuiltinType());
11373
if (IsCompAssign)
11374
return RHSType;
11375
if (LHSEleType != RHSEleType) {
11376
LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11377
LHSEleType = RHSEleType;
11378
}
11379
const llvm::ElementCount VecSize =
11380
S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11381
QualType VecTy =
11382
S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11383
LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11384
LHSType = VecTy;
11385
} else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11386
if (S.Context.getTypeSize(RHSBuiltinTy) !=
11387
S.Context.getTypeSize(LHSBuiltinTy)) {
11388
S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11389
<< LHSType << RHSType << LHS.get()->getSourceRange()
11390
<< RHS.get()->getSourceRange();
11391
return QualType();
11392
}
11393
} else {
11394
const llvm::ElementCount VecSize =
11395
S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11396
if (LHSEleType != RHSEleType) {
11397
RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11398
RHSEleType = LHSEleType;
11399
}
11400
QualType VecTy =
11401
S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11402
RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11403
}
11404
11405
return LHSType;
11406
}
11407
11408
// C99 6.5.7
11409
QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11410
SourceLocation Loc, BinaryOperatorKind Opc,
11411
bool IsCompAssign) {
11412
checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11413
11414
// Vector shifts promote their scalar inputs to vector type.
11415
if (LHS.get()->getType()->isVectorType() ||
11416
RHS.get()->getType()->isVectorType()) {
11417
if (LangOpts.ZVector) {
11418
// The shift operators for the z vector extensions work basically
11419
// like general shifts, except that neither the LHS nor the RHS is
11420
// allowed to be a "vector bool".
11421
if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11422
if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11423
return InvalidOperands(Loc, LHS, RHS);
11424
if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11425
if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11426
return InvalidOperands(Loc, LHS, RHS);
11427
}
11428
return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11429
}
11430
11431
if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11432
RHS.get()->getType()->isSveVLSBuiltinType())
11433
return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11434
11435
// Shifts don't perform usual arithmetic conversions, they just do integer
11436
// promotions on each operand. C99 6.5.7p3
11437
11438
// For the LHS, do usual unary conversions, but then reset them away
11439
// if this is a compound assignment.
11440
ExprResult OldLHS = LHS;
11441
LHS = UsualUnaryConversions(LHS.get());
11442
if (LHS.isInvalid())
11443
return QualType();
11444
QualType LHSType = LHS.get()->getType();
11445
if (IsCompAssign) LHS = OldLHS;
11446
11447
// The RHS is simpler.
11448
RHS = UsualUnaryConversions(RHS.get());
11449
if (RHS.isInvalid())
11450
return QualType();
11451
QualType RHSType = RHS.get()->getType();
11452
11453
// C99 6.5.7p2: Each of the operands shall have integer type.
11454
// Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11455
if ((!LHSType->isFixedPointOrIntegerType() &&
11456
!LHSType->hasIntegerRepresentation()) ||
11457
!RHSType->hasIntegerRepresentation())
11458
return InvalidOperands(Loc, LHS, RHS);
11459
11460
// C++0x: Don't allow scoped enums. FIXME: Use something better than
11461
// hasIntegerRepresentation() above instead of this.
11462
if (isScopedEnumerationType(LHSType) ||
11463
isScopedEnumerationType(RHSType)) {
11464
return InvalidOperands(Loc, LHS, RHS);
11465
}
11466
DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11467
11468
// "The type of the result is that of the promoted left operand."
11469
return LHSType;
11470
}
11471
11472
/// Diagnose bad pointer comparisons.
11473
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11474
ExprResult &LHS, ExprResult &RHS,
11475
bool IsError) {
11476
S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11477
: diag::ext_typecheck_comparison_of_distinct_pointers)
11478
<< LHS.get()->getType() << RHS.get()->getType()
11479
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11480
}
11481
11482
/// Returns false if the pointers are converted to a composite type,
11483
/// true otherwise.
11484
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11485
ExprResult &LHS, ExprResult &RHS) {
11486
// C++ [expr.rel]p2:
11487
// [...] Pointer conversions (4.10) and qualification
11488
// conversions (4.4) are performed on pointer operands (or on
11489
// a pointer operand and a null pointer constant) to bring
11490
// them to their composite pointer type. [...]
11491
//
11492
// C++ [expr.eq]p1 uses the same notion for (in)equality
11493
// comparisons of pointers.
11494
11495
QualType LHSType = LHS.get()->getType();
11496
QualType RHSType = RHS.get()->getType();
11497
assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11498
LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11499
11500
QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11501
if (T.isNull()) {
11502
if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11503
(RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11504
diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11505
else
11506
S.InvalidOperands(Loc, LHS, RHS);
11507
return true;
11508
}
11509
11510
return false;
11511
}
11512
11513
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11514
ExprResult &LHS,
11515
ExprResult &RHS,
11516
bool IsError) {
11517
S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11518
: diag::ext_typecheck_comparison_of_fptr_to_void)
11519
<< LHS.get()->getType() << RHS.get()->getType()
11520
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11521
}
11522
11523
static bool isObjCObjectLiteral(ExprResult &E) {
11524
switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11525
case Stmt::ObjCArrayLiteralClass:
11526
case Stmt::ObjCDictionaryLiteralClass:
11527
case Stmt::ObjCStringLiteralClass:
11528
case Stmt::ObjCBoxedExprClass:
11529
return true;
11530
default:
11531
// Note that ObjCBoolLiteral is NOT an object literal!
11532
return false;
11533
}
11534
}
11535
11536
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11537
const ObjCObjectPointerType *Type =
11538
LHS->getType()->getAs<ObjCObjectPointerType>();
11539
11540
// If this is not actually an Objective-C object, bail out.
11541
if (!Type)
11542
return false;
11543
11544
// Get the LHS object's interface type.
11545
QualType InterfaceType = Type->getPointeeType();
11546
11547
// If the RHS isn't an Objective-C object, bail out.
11548
if (!RHS->getType()->isObjCObjectPointerType())
11549
return false;
11550
11551
// Try to find the -isEqual: method.
11552
Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11553
ObjCMethodDecl *Method =
11554
S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11555
/*IsInstance=*/true);
11556
if (!Method) {
11557
if (Type->isObjCIdType()) {
11558
// For 'id', just check the global pool.
11559
Method =
11560
S.ObjC().LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11561
/*receiverId=*/true);
11562
} else {
11563
// Check protocols.
11564
Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11565
/*IsInstance=*/true);
11566
}
11567
}
11568
11569
if (!Method)
11570
return false;
11571
11572
QualType T = Method->parameters()[0]->getType();
11573
if (!T->isObjCObjectPointerType())
11574
return false;
11575
11576
QualType R = Method->getReturnType();
11577
if (!R->isScalarType())
11578
return false;
11579
11580
return true;
11581
}
11582
11583
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11584
ExprResult &LHS, ExprResult &RHS,
11585
BinaryOperator::Opcode Opc){
11586
Expr *Literal;
11587
Expr *Other;
11588
if (isObjCObjectLiteral(LHS)) {
11589
Literal = LHS.get();
11590
Other = RHS.get();
11591
} else {
11592
Literal = RHS.get();
11593
Other = LHS.get();
11594
}
11595
11596
// Don't warn on comparisons against nil.
11597
Other = Other->IgnoreParenCasts();
11598
if (Other->isNullPointerConstant(S.getASTContext(),
11599
Expr::NPC_ValueDependentIsNotNull))
11600
return;
11601
11602
// This should be kept in sync with warn_objc_literal_comparison.
11603
// LK_String should always be after the other literals, since it has its own
11604
// warning flag.
11605
SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11606
assert(LiteralKind != SemaObjC::LK_Block);
11607
if (LiteralKind == SemaObjC::LK_None) {
11608
llvm_unreachable("Unknown Objective-C object literal kind");
11609
}
11610
11611
if (LiteralKind == SemaObjC::LK_String)
11612
S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11613
<< Literal->getSourceRange();
11614
else
11615
S.Diag(Loc, diag::warn_objc_literal_comparison)
11616
<< LiteralKind << Literal->getSourceRange();
11617
11618
if (BinaryOperator::isEqualityOp(Opc) &&
11619
hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11620
SourceLocation Start = LHS.get()->getBeginLoc();
11621
SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11622
CharSourceRange OpRange =
11623
CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11624
11625
S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11626
<< FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11627
<< FixItHint::CreateReplacement(OpRange, " isEqual:")
11628
<< FixItHint::CreateInsertion(End, "]");
11629
}
11630
}
11631
11632
/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11633
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11634
ExprResult &RHS, SourceLocation Loc,
11635
BinaryOperatorKind Opc) {
11636
// Check that left hand side is !something.
11637
UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11638
if (!UO || UO->getOpcode() != UO_LNot) return;
11639
11640
// Only check if the right hand side is non-bool arithmetic type.
11641
if (RHS.get()->isKnownToHaveBooleanValue()) return;
11642
11643
// Make sure that the something in !something is not bool.
11644
Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11645
if (SubExpr->isKnownToHaveBooleanValue()) return;
11646
11647
// Emit warning.
11648
bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11649
S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11650
<< Loc << IsBitwiseOp;
11651
11652
// First note suggest !(x < y)
11653
SourceLocation FirstOpen = SubExpr->getBeginLoc();
11654
SourceLocation FirstClose = RHS.get()->getEndLoc();
11655
FirstClose = S.getLocForEndOfToken(FirstClose);
11656
if (FirstClose.isInvalid())
11657
FirstOpen = SourceLocation();
11658
S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11659
<< IsBitwiseOp
11660
<< FixItHint::CreateInsertion(FirstOpen, "(")
11661
<< FixItHint::CreateInsertion(FirstClose, ")");
11662
11663
// Second note suggests (!x) < y
11664
SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11665
SourceLocation SecondClose = LHS.get()->getEndLoc();
11666
SecondClose = S.getLocForEndOfToken(SecondClose);
11667
if (SecondClose.isInvalid())
11668
SecondOpen = SourceLocation();
11669
S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11670
<< FixItHint::CreateInsertion(SecondOpen, "(")
11671
<< FixItHint::CreateInsertion(SecondClose, ")");
11672
}
11673
11674
// Returns true if E refers to a non-weak array.
11675
static bool checkForArray(const Expr *E) {
11676
const ValueDecl *D = nullptr;
11677
if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11678
D = DR->getDecl();
11679
} else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11680
if (Mem->isImplicitAccess())
11681
D = Mem->getMemberDecl();
11682
}
11683
if (!D)
11684
return false;
11685
return D->getType()->isArrayType() && !D->isWeak();
11686
}
11687
11688
/// Diagnose some forms of syntactically-obvious tautological comparison.
11689
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11690
Expr *LHS, Expr *RHS,
11691
BinaryOperatorKind Opc) {
11692
Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11693
Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11694
11695
QualType LHSType = LHS->getType();
11696
QualType RHSType = RHS->getType();
11697
if (LHSType->hasFloatingRepresentation() ||
11698
(LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11699
S.inTemplateInstantiation())
11700
return;
11701
11702
// WebAssembly Tables cannot be compared, therefore shouldn't emit
11703
// Tautological diagnostics.
11704
if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11705
return;
11706
11707
// Comparisons between two array types are ill-formed for operator<=>, so
11708
// we shouldn't emit any additional warnings about it.
11709
if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11710
return;
11711
11712
// For non-floating point types, check for self-comparisons of the form
11713
// x == x, x != x, x < x, etc. These always evaluate to a constant, and
11714
// often indicate logic errors in the program.
11715
//
11716
// NOTE: Don't warn about comparison expressions resulting from macro
11717
// expansion. Also don't warn about comparisons which are only self
11718
// comparisons within a template instantiation. The warnings should catch
11719
// obvious cases in the definition of the template anyways. The idea is to
11720
// warn when the typed comparison operator will always evaluate to the same
11721
// result.
11722
11723
// Used for indexing into %select in warn_comparison_always
11724
enum {
11725
AlwaysConstant,
11726
AlwaysTrue,
11727
AlwaysFalse,
11728
AlwaysEqual, // std::strong_ordering::equal from operator<=>
11729
};
11730
11731
// C++2a [depr.array.comp]:
11732
// Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11733
// operands of array type are deprecated.
11734
if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11735
RHSStripped->getType()->isArrayType()) {
11736
S.Diag(Loc, diag::warn_depr_array_comparison)
11737
<< LHS->getSourceRange() << RHS->getSourceRange()
11738
<< LHSStripped->getType() << RHSStripped->getType();
11739
// Carry on to produce the tautological comparison warning, if this
11740
// expression is potentially-evaluated, we can resolve the array to a
11741
// non-weak declaration, and so on.
11742
}
11743
11744
if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11745
if (Expr::isSameComparisonOperand(LHS, RHS)) {
11746
unsigned Result;
11747
switch (Opc) {
11748
case BO_EQ:
11749
case BO_LE:
11750
case BO_GE:
11751
Result = AlwaysTrue;
11752
break;
11753
case BO_NE:
11754
case BO_LT:
11755
case BO_GT:
11756
Result = AlwaysFalse;
11757
break;
11758
case BO_Cmp:
11759
Result = AlwaysEqual;
11760
break;
11761
default:
11762
Result = AlwaysConstant;
11763
break;
11764
}
11765
S.DiagRuntimeBehavior(Loc, nullptr,
11766
S.PDiag(diag::warn_comparison_always)
11767
<< 0 /*self-comparison*/
11768
<< Result);
11769
} else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11770
// What is it always going to evaluate to?
11771
unsigned Result;
11772
switch (Opc) {
11773
case BO_EQ: // e.g. array1 == array2
11774
Result = AlwaysFalse;
11775
break;
11776
case BO_NE: // e.g. array1 != array2
11777
Result = AlwaysTrue;
11778
break;
11779
default: // e.g. array1 <= array2
11780
// The best we can say is 'a constant'
11781
Result = AlwaysConstant;
11782
break;
11783
}
11784
S.DiagRuntimeBehavior(Loc, nullptr,
11785
S.PDiag(diag::warn_comparison_always)
11786
<< 1 /*array comparison*/
11787
<< Result);
11788
}
11789
}
11790
11791
if (isa<CastExpr>(LHSStripped))
11792
LHSStripped = LHSStripped->IgnoreParenCasts();
11793
if (isa<CastExpr>(RHSStripped))
11794
RHSStripped = RHSStripped->IgnoreParenCasts();
11795
11796
// Warn about comparisons against a string constant (unless the other
11797
// operand is null); the user probably wants string comparison function.
11798
Expr *LiteralString = nullptr;
11799
Expr *LiteralStringStripped = nullptr;
11800
if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11801
!RHSStripped->isNullPointerConstant(S.Context,
11802
Expr::NPC_ValueDependentIsNull)) {
11803
LiteralString = LHS;
11804
LiteralStringStripped = LHSStripped;
11805
} else if ((isa<StringLiteral>(RHSStripped) ||
11806
isa<ObjCEncodeExpr>(RHSStripped)) &&
11807
!LHSStripped->isNullPointerConstant(S.Context,
11808
Expr::NPC_ValueDependentIsNull)) {
11809
LiteralString = RHS;
11810
LiteralStringStripped = RHSStripped;
11811
}
11812
11813
if (LiteralString) {
11814
S.DiagRuntimeBehavior(Loc, nullptr,
11815
S.PDiag(diag::warn_stringcompare)
11816
<< isa<ObjCEncodeExpr>(LiteralStringStripped)
11817
<< LiteralString->getSourceRange());
11818
}
11819
}
11820
11821
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11822
switch (CK) {
11823
default: {
11824
#ifndef NDEBUG
11825
llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11826
<< "\n";
11827
#endif
11828
llvm_unreachable("unhandled cast kind");
11829
}
11830
case CK_UserDefinedConversion:
11831
return ICK_Identity;
11832
case CK_LValueToRValue:
11833
return ICK_Lvalue_To_Rvalue;
11834
case CK_ArrayToPointerDecay:
11835
return ICK_Array_To_Pointer;
11836
case CK_FunctionToPointerDecay:
11837
return ICK_Function_To_Pointer;
11838
case CK_IntegralCast:
11839
return ICK_Integral_Conversion;
11840
case CK_FloatingCast:
11841
return ICK_Floating_Conversion;
11842
case CK_IntegralToFloating:
11843
case CK_FloatingToIntegral:
11844
return ICK_Floating_Integral;
11845
case CK_IntegralComplexCast:
11846
case CK_FloatingComplexCast:
11847
case CK_FloatingComplexToIntegralComplex:
11848
case CK_IntegralComplexToFloatingComplex:
11849
return ICK_Complex_Conversion;
11850
case CK_FloatingComplexToReal:
11851
case CK_FloatingRealToComplex:
11852
case CK_IntegralComplexToReal:
11853
case CK_IntegralRealToComplex:
11854
return ICK_Complex_Real;
11855
case CK_HLSLArrayRValue:
11856
return ICK_HLSL_Array_RValue;
11857
}
11858
}
11859
11860
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11861
QualType FromType,
11862
SourceLocation Loc) {
11863
// Check for a narrowing implicit conversion.
11864
StandardConversionSequence SCS;
11865
SCS.setAsIdentityConversion();
11866
SCS.setToType(0, FromType);
11867
SCS.setToType(1, ToType);
11868
if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11869
SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11870
11871
APValue PreNarrowingValue;
11872
QualType PreNarrowingType;
11873
switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11874
PreNarrowingType,
11875
/*IgnoreFloatToIntegralConversion*/ true)) {
11876
case NK_Dependent_Narrowing:
11877
// Implicit conversion to a narrower type, but the expression is
11878
// value-dependent so we can't tell whether it's actually narrowing.
11879
case NK_Not_Narrowing:
11880
return false;
11881
11882
case NK_Constant_Narrowing:
11883
// Implicit conversion to a narrower type, and the value is not a constant
11884
// expression.
11885
S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11886
<< /*Constant*/ 1
11887
<< PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11888
return true;
11889
11890
case NK_Variable_Narrowing:
11891
// Implicit conversion to a narrower type, and the value is not a constant
11892
// expression.
11893
case NK_Type_Narrowing:
11894
S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11895
<< /*Constant*/ 0 << FromType << ToType;
11896
// TODO: It's not a constant expression, but what if the user intended it
11897
// to be? Can we produce notes to help them figure out why it isn't?
11898
return true;
11899
}
11900
llvm_unreachable("unhandled case in switch");
11901
}
11902
11903
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11904
ExprResult &LHS,
11905
ExprResult &RHS,
11906
SourceLocation Loc) {
11907
QualType LHSType = LHS.get()->getType();
11908
QualType RHSType = RHS.get()->getType();
11909
// Dig out the original argument type and expression before implicit casts
11910
// were applied. These are the types/expressions we need to check the
11911
// [expr.spaceship] requirements against.
11912
ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11913
ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11914
QualType LHSStrippedType = LHSStripped.get()->getType();
11915
QualType RHSStrippedType = RHSStripped.get()->getType();
11916
11917
// C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11918
// other is not, the program is ill-formed.
11919
if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11920
S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11921
return QualType();
11922
}
11923
11924
// FIXME: Consider combining this with checkEnumArithmeticConversions.
11925
int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11926
RHSStrippedType->isEnumeralType();
11927
if (NumEnumArgs == 1) {
11928
bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11929
QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11930
if (OtherTy->hasFloatingRepresentation()) {
11931
S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11932
return QualType();
11933
}
11934
}
11935
if (NumEnumArgs == 2) {
11936
// C++2a [expr.spaceship]p5: If both operands have the same enumeration
11937
// type E, the operator yields the result of converting the operands
11938
// to the underlying type of E and applying <=> to the converted operands.
11939
if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11940
S.InvalidOperands(Loc, LHS, RHS);
11941
return QualType();
11942
}
11943
QualType IntType =
11944
LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11945
assert(IntType->isArithmeticType());
11946
11947
// We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11948
// promote the boolean type, and all other promotable integer types, to
11949
// avoid this.
11950
if (S.Context.isPromotableIntegerType(IntType))
11951
IntType = S.Context.getPromotedIntegerType(IntType);
11952
11953
LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11954
RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11955
LHSType = RHSType = IntType;
11956
}
11957
11958
// C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11959
// usual arithmetic conversions are applied to the operands.
11960
QualType Type =
11961
S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11962
if (LHS.isInvalid() || RHS.isInvalid())
11963
return QualType();
11964
if (Type.isNull())
11965
return S.InvalidOperands(Loc, LHS, RHS);
11966
11967
std::optional<ComparisonCategoryType> CCT =
11968
getComparisonCategoryForBuiltinCmp(Type);
11969
if (!CCT)
11970
return S.InvalidOperands(Loc, LHS, RHS);
11971
11972
bool HasNarrowing = checkThreeWayNarrowingConversion(
11973
S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11974
HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11975
RHS.get()->getBeginLoc());
11976
if (HasNarrowing)
11977
return QualType();
11978
11979
assert(!Type.isNull() && "composite type for <=> has not been set");
11980
11981
return S.CheckComparisonCategoryType(
11982
*CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11983
}
11984
11985
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11986
ExprResult &RHS,
11987
SourceLocation Loc,
11988
BinaryOperatorKind Opc) {
11989
if (Opc == BO_Cmp)
11990
return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11991
11992
// C99 6.5.8p3 / C99 6.5.9p4
11993
QualType Type =
11994
S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11995
if (LHS.isInvalid() || RHS.isInvalid())
11996
return QualType();
11997
if (Type.isNull())
11998
return S.InvalidOperands(Loc, LHS, RHS);
11999
assert(Type->isArithmeticType() || Type->isEnumeralType());
12000
12001
if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12002
return S.InvalidOperands(Loc, LHS, RHS);
12003
12004
// Check for comparisons of floating point operands using != and ==.
12005
if (Type->hasFloatingRepresentation())
12006
S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12007
12008
// The result of comparisons is 'bool' in C++, 'int' in C.
12009
return S.Context.getLogicalOperationType();
12010
}
12011
12012
void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12013
if (!NullE.get()->getType()->isAnyPointerType())
12014
return;
12015
int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12016
if (!E.get()->getType()->isAnyPointerType() &&
12017
E.get()->isNullPointerConstant(Context,
12018
Expr::NPC_ValueDependentIsNotNull) ==
12019
Expr::NPCK_ZeroExpression) {
12020
if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12021
if (CL->getValue() == 0)
12022
Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12023
<< NullValue
12024
<< FixItHint::CreateReplacement(E.get()->getExprLoc(),
12025
NullValue ? "NULL" : "(void *)0");
12026
} else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12027
TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12028
QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12029
if (T == Context.CharTy)
12030
Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12031
<< NullValue
12032
<< FixItHint::CreateReplacement(E.get()->getExprLoc(),
12033
NullValue ? "NULL" : "(void *)0");
12034
}
12035
}
12036
}
12037
12038
// C99 6.5.8, C++ [expr.rel]
12039
QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12040
SourceLocation Loc,
12041
BinaryOperatorKind Opc) {
12042
bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12043
bool IsThreeWay = Opc == BO_Cmp;
12044
bool IsOrdered = IsRelational || IsThreeWay;
12045
auto IsAnyPointerType = [](ExprResult E) {
12046
QualType Ty = E.get()->getType();
12047
return Ty->isPointerType() || Ty->isMemberPointerType();
12048
};
12049
12050
// C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12051
// type, array-to-pointer, ..., conversions are performed on both operands to
12052
// bring them to their composite type.
12053
// Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12054
// any type-related checks.
12055
if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12056
LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12057
if (LHS.isInvalid())
12058
return QualType();
12059
RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12060
if (RHS.isInvalid())
12061
return QualType();
12062
} else {
12063
LHS = DefaultLvalueConversion(LHS.get());
12064
if (LHS.isInvalid())
12065
return QualType();
12066
RHS = DefaultLvalueConversion(RHS.get());
12067
if (RHS.isInvalid())
12068
return QualType();
12069
}
12070
12071
checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12072
if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12073
CheckPtrComparisonWithNullChar(LHS, RHS);
12074
CheckPtrComparisonWithNullChar(RHS, LHS);
12075
}
12076
12077
// Handle vector comparisons separately.
12078
if (LHS.get()->getType()->isVectorType() ||
12079
RHS.get()->getType()->isVectorType())
12080
return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12081
12082
if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12083
RHS.get()->getType()->isSveVLSBuiltinType())
12084
return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12085
12086
diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12087
diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12088
12089
QualType LHSType = LHS.get()->getType();
12090
QualType RHSType = RHS.get()->getType();
12091
if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12092
(RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12093
return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12094
12095
if ((LHSType->isPointerType() &&
12096
LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12097
(RHSType->isPointerType() &&
12098
RHSType->getPointeeType().isWebAssemblyReferenceType()))
12099
return InvalidOperands(Loc, LHS, RHS);
12100
12101
const Expr::NullPointerConstantKind LHSNullKind =
12102
LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12103
const Expr::NullPointerConstantKind RHSNullKind =
12104
RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12105
bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12106
bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12107
12108
auto computeResultTy = [&]() {
12109
if (Opc != BO_Cmp)
12110
return Context.getLogicalOperationType();
12111
assert(getLangOpts().CPlusPlus);
12112
assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12113
12114
QualType CompositeTy = LHS.get()->getType();
12115
assert(!CompositeTy->isReferenceType());
12116
12117
std::optional<ComparisonCategoryType> CCT =
12118
getComparisonCategoryForBuiltinCmp(CompositeTy);
12119
if (!CCT)
12120
return InvalidOperands(Loc, LHS, RHS);
12121
12122
if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12123
// P0946R0: Comparisons between a null pointer constant and an object
12124
// pointer result in std::strong_equality, which is ill-formed under
12125
// P1959R0.
12126
Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12127
<< (LHSIsNull ? LHS.get()->getSourceRange()
12128
: RHS.get()->getSourceRange());
12129
return QualType();
12130
}
12131
12132
return CheckComparisonCategoryType(
12133
*CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12134
};
12135
12136
if (!IsOrdered && LHSIsNull != RHSIsNull) {
12137
bool IsEquality = Opc == BO_EQ;
12138
if (RHSIsNull)
12139
DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12140
RHS.get()->getSourceRange());
12141
else
12142
DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12143
LHS.get()->getSourceRange());
12144
}
12145
12146
if (IsOrdered && LHSType->isFunctionPointerType() &&
12147
RHSType->isFunctionPointerType()) {
12148
// Valid unless a relational comparison of function pointers
12149
bool IsError = Opc == BO_Cmp;
12150
auto DiagID =
12151
IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12152
: getLangOpts().CPlusPlus
12153
? diag::warn_typecheck_ordered_comparison_of_function_pointers
12154
: diag::ext_typecheck_ordered_comparison_of_function_pointers;
12155
Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12156
<< RHS.get()->getSourceRange();
12157
if (IsError)
12158
return QualType();
12159
}
12160
12161
if ((LHSType->isIntegerType() && !LHSIsNull) ||
12162
(RHSType->isIntegerType() && !RHSIsNull)) {
12163
// Skip normal pointer conversion checks in this case; we have better
12164
// diagnostics for this below.
12165
} else if (getLangOpts().CPlusPlus) {
12166
// Equality comparison of a function pointer to a void pointer is invalid,
12167
// but we allow it as an extension.
12168
// FIXME: If we really want to allow this, should it be part of composite
12169
// pointer type computation so it works in conditionals too?
12170
if (!IsOrdered &&
12171
((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12172
(RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12173
// This is a gcc extension compatibility comparison.
12174
// In a SFINAE context, we treat this as a hard error to maintain
12175
// conformance with the C++ standard.
12176
diagnoseFunctionPointerToVoidComparison(
12177
*this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12178
12179
if (isSFINAEContext())
12180
return QualType();
12181
12182
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12183
return computeResultTy();
12184
}
12185
12186
// C++ [expr.eq]p2:
12187
// If at least one operand is a pointer [...] bring them to their
12188
// composite pointer type.
12189
// C++ [expr.spaceship]p6
12190
// If at least one of the operands is of pointer type, [...] bring them
12191
// to their composite pointer type.
12192
// C++ [expr.rel]p2:
12193
// If both operands are pointers, [...] bring them to their composite
12194
// pointer type.
12195
// For <=>, the only valid non-pointer types are arrays and functions, and
12196
// we already decayed those, so this is really the same as the relational
12197
// comparison rule.
12198
if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12199
(IsOrdered ? 2 : 1) &&
12200
(!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12201
RHSType->isObjCObjectPointerType()))) {
12202
if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12203
return QualType();
12204
return computeResultTy();
12205
}
12206
} else if (LHSType->isPointerType() &&
12207
RHSType->isPointerType()) { // C99 6.5.8p2
12208
// All of the following pointer-related warnings are GCC extensions, except
12209
// when handling null pointer constants.
12210
QualType LCanPointeeTy =
12211
LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12212
QualType RCanPointeeTy =
12213
RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12214
12215
// C99 6.5.9p2 and C99 6.5.8p2
12216
if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12217
RCanPointeeTy.getUnqualifiedType())) {
12218
if (IsRelational) {
12219
// Pointers both need to point to complete or incomplete types
12220
if ((LCanPointeeTy->isIncompleteType() !=
12221
RCanPointeeTy->isIncompleteType()) &&
12222
!getLangOpts().C11) {
12223
Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12224
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12225
<< LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12226
<< RCanPointeeTy->isIncompleteType();
12227
}
12228
}
12229
} else if (!IsRelational &&
12230
(LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12231
// Valid unless comparison between non-null pointer and function pointer
12232
if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12233
&& !LHSIsNull && !RHSIsNull)
12234
diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12235
/*isError*/false);
12236
} else {
12237
// Invalid
12238
diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12239
}
12240
if (LCanPointeeTy != RCanPointeeTy) {
12241
// Treat NULL constant as a special case in OpenCL.
12242
if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12243
if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12244
Diag(Loc,
12245
diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12246
<< LHSType << RHSType << 0 /* comparison */
12247
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12248
}
12249
}
12250
LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12251
LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12252
CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12253
: CK_BitCast;
12254
if (LHSIsNull && !RHSIsNull)
12255
LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12256
else
12257
RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12258
}
12259
return computeResultTy();
12260
}
12261
12262
12263
// C++ [expr.eq]p4:
12264
// Two operands of type std::nullptr_t or one operand of type
12265
// std::nullptr_t and the other a null pointer constant compare
12266
// equal.
12267
// C23 6.5.9p5:
12268
// If both operands have type nullptr_t or one operand has type nullptr_t
12269
// and the other is a null pointer constant, they compare equal if the
12270
// former is a null pointer.
12271
if (!IsOrdered && LHSIsNull && RHSIsNull) {
12272
if (LHSType->isNullPtrType()) {
12273
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12274
return computeResultTy();
12275
}
12276
if (RHSType->isNullPtrType()) {
12277
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12278
return computeResultTy();
12279
}
12280
}
12281
12282
if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12283
// C23 6.5.9p6:
12284
// Otherwise, at least one operand is a pointer. If one is a pointer and
12285
// the other is a null pointer constant or has type nullptr_t, they
12286
// compare equal
12287
if (LHSIsNull && RHSType->isPointerType()) {
12288
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12289
return computeResultTy();
12290
}
12291
if (RHSIsNull && LHSType->isPointerType()) {
12292
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12293
return computeResultTy();
12294
}
12295
}
12296
12297
// Comparison of Objective-C pointers and block pointers against nullptr_t.
12298
// These aren't covered by the composite pointer type rules.
12299
if (!IsOrdered && RHSType->isNullPtrType() &&
12300
(LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12301
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12302
return computeResultTy();
12303
}
12304
if (!IsOrdered && LHSType->isNullPtrType() &&
12305
(RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12306
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12307
return computeResultTy();
12308
}
12309
12310
if (getLangOpts().CPlusPlus) {
12311
if (IsRelational &&
12312
((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12313
(RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12314
// HACK: Relational comparison of nullptr_t against a pointer type is
12315
// invalid per DR583, but we allow it within std::less<> and friends,
12316
// since otherwise common uses of it break.
12317
// FIXME: Consider removing this hack once LWG fixes std::less<> and
12318
// friends to have std::nullptr_t overload candidates.
12319
DeclContext *DC = CurContext;
12320
if (isa<FunctionDecl>(DC))
12321
DC = DC->getParent();
12322
if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12323
if (CTSD->isInStdNamespace() &&
12324
llvm::StringSwitch<bool>(CTSD->getName())
12325
.Cases("less", "less_equal", "greater", "greater_equal", true)
12326
.Default(false)) {
12327
if (RHSType->isNullPtrType())
12328
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12329
else
12330
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12331
return computeResultTy();
12332
}
12333
}
12334
}
12335
12336
// C++ [expr.eq]p2:
12337
// If at least one operand is a pointer to member, [...] bring them to
12338
// their composite pointer type.
12339
if (!IsOrdered &&
12340
(LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12341
if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12342
return QualType();
12343
else
12344
return computeResultTy();
12345
}
12346
}
12347
12348
// Handle block pointer types.
12349
if (!IsOrdered && LHSType->isBlockPointerType() &&
12350
RHSType->isBlockPointerType()) {
12351
QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12352
QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12353
12354
if (!LHSIsNull && !RHSIsNull &&
12355
!Context.typesAreCompatible(lpointee, rpointee)) {
12356
Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12357
<< LHSType << RHSType << LHS.get()->getSourceRange()
12358
<< RHS.get()->getSourceRange();
12359
}
12360
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12361
return computeResultTy();
12362
}
12363
12364
// Allow block pointers to be compared with null pointer constants.
12365
if (!IsOrdered
12366
&& ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12367
|| (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12368
if (!LHSIsNull && !RHSIsNull) {
12369
if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12370
->getPointeeType()->isVoidType())
12371
|| (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12372
->getPointeeType()->isVoidType())))
12373
Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12374
<< LHSType << RHSType << LHS.get()->getSourceRange()
12375
<< RHS.get()->getSourceRange();
12376
}
12377
if (LHSIsNull && !RHSIsNull)
12378
LHS = ImpCastExprToType(LHS.get(), RHSType,
12379
RHSType->isPointerType() ? CK_BitCast
12380
: CK_AnyPointerToBlockPointerCast);
12381
else
12382
RHS = ImpCastExprToType(RHS.get(), LHSType,
12383
LHSType->isPointerType() ? CK_BitCast
12384
: CK_AnyPointerToBlockPointerCast);
12385
return computeResultTy();
12386
}
12387
12388
if (LHSType->isObjCObjectPointerType() ||
12389
RHSType->isObjCObjectPointerType()) {
12390
const PointerType *LPT = LHSType->getAs<PointerType>();
12391
const PointerType *RPT = RHSType->getAs<PointerType>();
12392
if (LPT || RPT) {
12393
bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12394
bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12395
12396
if (!LPtrToVoid && !RPtrToVoid &&
12397
!Context.typesAreCompatible(LHSType, RHSType)) {
12398
diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12399
/*isError*/false);
12400
}
12401
// FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12402
// the RHS, but we have test coverage for this behavior.
12403
// FIXME: Consider using convertPointersToCompositeType in C++.
12404
if (LHSIsNull && !RHSIsNull) {
12405
Expr *E = LHS.get();
12406
if (getLangOpts().ObjCAutoRefCount)
12407
ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12408
CheckedConversionKind::Implicit);
12409
LHS = ImpCastExprToType(E, RHSType,
12410
RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12411
}
12412
else {
12413
Expr *E = RHS.get();
12414
if (getLangOpts().ObjCAutoRefCount)
12415
ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12416
CheckedConversionKind::Implicit,
12417
/*Diagnose=*/true,
12418
/*DiagnoseCFAudited=*/false, Opc);
12419
RHS = ImpCastExprToType(E, LHSType,
12420
LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12421
}
12422
return computeResultTy();
12423
}
12424
if (LHSType->isObjCObjectPointerType() &&
12425
RHSType->isObjCObjectPointerType()) {
12426
if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12427
diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12428
/*isError*/false);
12429
if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12430
diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12431
12432
if (LHSIsNull && !RHSIsNull)
12433
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12434
else
12435
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12436
return computeResultTy();
12437
}
12438
12439
if (!IsOrdered && LHSType->isBlockPointerType() &&
12440
RHSType->isBlockCompatibleObjCPointerType(Context)) {
12441
LHS = ImpCastExprToType(LHS.get(), RHSType,
12442
CK_BlockPointerToObjCPointerCast);
12443
return computeResultTy();
12444
} else if (!IsOrdered &&
12445
LHSType->isBlockCompatibleObjCPointerType(Context) &&
12446
RHSType->isBlockPointerType()) {
12447
RHS = ImpCastExprToType(RHS.get(), LHSType,
12448
CK_BlockPointerToObjCPointerCast);
12449
return computeResultTy();
12450
}
12451
}
12452
if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12453
(LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12454
unsigned DiagID = 0;
12455
bool isError = false;
12456
if (LangOpts.DebuggerSupport) {
12457
// Under a debugger, allow the comparison of pointers to integers,
12458
// since users tend to want to compare addresses.
12459
} else if ((LHSIsNull && LHSType->isIntegerType()) ||
12460
(RHSIsNull && RHSType->isIntegerType())) {
12461
if (IsOrdered) {
12462
isError = getLangOpts().CPlusPlus;
12463
DiagID =
12464
isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12465
: diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12466
}
12467
} else if (getLangOpts().CPlusPlus) {
12468
DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12469
isError = true;
12470
} else if (IsOrdered)
12471
DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12472
else
12473
DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12474
12475
if (DiagID) {
12476
Diag(Loc, DiagID)
12477
<< LHSType << RHSType << LHS.get()->getSourceRange()
12478
<< RHS.get()->getSourceRange();
12479
if (isError)
12480
return QualType();
12481
}
12482
12483
if (LHSType->isIntegerType())
12484
LHS = ImpCastExprToType(LHS.get(), RHSType,
12485
LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12486
else
12487
RHS = ImpCastExprToType(RHS.get(), LHSType,
12488
RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12489
return computeResultTy();
12490
}
12491
12492
// Handle block pointers.
12493
if (!IsOrdered && RHSIsNull
12494
&& LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12495
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12496
return computeResultTy();
12497
}
12498
if (!IsOrdered && LHSIsNull
12499
&& LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12500
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12501
return computeResultTy();
12502
}
12503
12504
if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12505
if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12506
return computeResultTy();
12507
}
12508
12509
if (LHSType->isQueueT() && RHSType->isQueueT()) {
12510
return computeResultTy();
12511
}
12512
12513
if (LHSIsNull && RHSType->isQueueT()) {
12514
LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12515
return computeResultTy();
12516
}
12517
12518
if (LHSType->isQueueT() && RHSIsNull) {
12519
RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12520
return computeResultTy();
12521
}
12522
}
12523
12524
return InvalidOperands(Loc, LHS, RHS);
12525
}
12526
12527
QualType Sema::GetSignedVectorType(QualType V) {
12528
const VectorType *VTy = V->castAs<VectorType>();
12529
unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12530
12531
if (isa<ExtVectorType>(VTy)) {
12532
if (VTy->isExtVectorBoolType())
12533
return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12534
if (TypeSize == Context.getTypeSize(Context.CharTy))
12535
return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12536
if (TypeSize == Context.getTypeSize(Context.ShortTy))
12537
return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12538
if (TypeSize == Context.getTypeSize(Context.IntTy))
12539
return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12540
if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12541
return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12542
if (TypeSize == Context.getTypeSize(Context.LongTy))
12543
return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12544
assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12545
"Unhandled vector element size in vector compare");
12546
return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12547
}
12548
12549
if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12550
return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12551
VectorKind::Generic);
12552
if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12553
return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12554
VectorKind::Generic);
12555
if (TypeSize == Context.getTypeSize(Context.LongTy))
12556
return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12557
VectorKind::Generic);
12558
if (TypeSize == Context.getTypeSize(Context.IntTy))
12559
return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12560
VectorKind::Generic);
12561
if (TypeSize == Context.getTypeSize(Context.ShortTy))
12562
return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12563
VectorKind::Generic);
12564
assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12565
"Unhandled vector element size in vector compare");
12566
return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12567
VectorKind::Generic);
12568
}
12569
12570
QualType Sema::GetSignedSizelessVectorType(QualType V) {
12571
const BuiltinType *VTy = V->castAs<BuiltinType>();
12572
assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12573
12574
const QualType ETy = V->getSveEltType(Context);
12575
const auto TypeSize = Context.getTypeSize(ETy);
12576
12577
const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12578
const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12579
return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12580
}
12581
12582
QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12583
SourceLocation Loc,
12584
BinaryOperatorKind Opc) {
12585
if (Opc == BO_Cmp) {
12586
Diag(Loc, diag::err_three_way_vector_comparison);
12587
return QualType();
12588
}
12589
12590
// Check to make sure we're operating on vectors of the same type and width,
12591
// Allowing one side to be a scalar of element type.
12592
QualType vType =
12593
CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12594
/*AllowBothBool*/ true,
12595
/*AllowBoolConversions*/ getLangOpts().ZVector,
12596
/*AllowBooleanOperation*/ true,
12597
/*ReportInvalid*/ true);
12598
if (vType.isNull())
12599
return vType;
12600
12601
QualType LHSType = LHS.get()->getType();
12602
12603
// Determine the return type of a vector compare. By default clang will return
12604
// a scalar for all vector compares except vector bool and vector pixel.
12605
// With the gcc compiler we will always return a vector type and with the xl
12606
// compiler we will always return a scalar type. This switch allows choosing
12607
// which behavior is prefered.
12608
if (getLangOpts().AltiVec) {
12609
switch (getLangOpts().getAltivecSrcCompat()) {
12610
case LangOptions::AltivecSrcCompatKind::Mixed:
12611
// If AltiVec, the comparison results in a numeric type, i.e.
12612
// bool for C++, int for C
12613
if (vType->castAs<VectorType>()->getVectorKind() ==
12614
VectorKind::AltiVecVector)
12615
return Context.getLogicalOperationType();
12616
else
12617
Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12618
break;
12619
case LangOptions::AltivecSrcCompatKind::GCC:
12620
// For GCC we always return the vector type.
12621
break;
12622
case LangOptions::AltivecSrcCompatKind::XL:
12623
return Context.getLogicalOperationType();
12624
break;
12625
}
12626
}
12627
12628
// For non-floating point types, check for self-comparisons of the form
12629
// x == x, x != x, x < x, etc. These always evaluate to a constant, and
12630
// often indicate logic errors in the program.
12631
diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12632
12633
// Check for comparisons of floating point operands using != and ==.
12634
if (LHSType->hasFloatingRepresentation()) {
12635
assert(RHS.get()->getType()->hasFloatingRepresentation());
12636
CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12637
}
12638
12639
// Return a signed type for the vector.
12640
return GetSignedVectorType(vType);
12641
}
12642
12643
QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
12644
ExprResult &RHS,
12645
SourceLocation Loc,
12646
BinaryOperatorKind Opc) {
12647
if (Opc == BO_Cmp) {
12648
Diag(Loc, diag::err_three_way_vector_comparison);
12649
return QualType();
12650
}
12651
12652
// Check to make sure we're operating on vectors of the same type and width,
12653
// Allowing one side to be a scalar of element type.
12654
QualType vType = CheckSizelessVectorOperands(
12655
LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12656
12657
if (vType.isNull())
12658
return vType;
12659
12660
QualType LHSType = LHS.get()->getType();
12661
12662
// For non-floating point types, check for self-comparisons of the form
12663
// x == x, x != x, x < x, etc. These always evaluate to a constant, and
12664
// often indicate logic errors in the program.
12665
diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12666
12667
// Check for comparisons of floating point operands using != and ==.
12668
if (LHSType->hasFloatingRepresentation()) {
12669
assert(RHS.get()->getType()->hasFloatingRepresentation());
12670
CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12671
}
12672
12673
const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12674
const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12675
12676
if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12677
RHSBuiltinTy->isSVEBool())
12678
return LHSType;
12679
12680
// Return a signed type for the vector.
12681
return GetSignedSizelessVectorType(vType);
12682
}
12683
12684
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12685
const ExprResult &XorRHS,
12686
const SourceLocation Loc) {
12687
// Do not diagnose macros.
12688
if (Loc.isMacroID())
12689
return;
12690
12691
// Do not diagnose if both LHS and RHS are macros.
12692
if (XorLHS.get()->getExprLoc().isMacroID() &&
12693
XorRHS.get()->getExprLoc().isMacroID())
12694
return;
12695
12696
bool Negative = false;
12697
bool ExplicitPlus = false;
12698
const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12699
const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12700
12701
if (!LHSInt)
12702
return;
12703
if (!RHSInt) {
12704
// Check negative literals.
12705
if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12706
UnaryOperatorKind Opc = UO->getOpcode();
12707
if (Opc != UO_Minus && Opc != UO_Plus)
12708
return;
12709
RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12710
if (!RHSInt)
12711
return;
12712
Negative = (Opc == UO_Minus);
12713
ExplicitPlus = !Negative;
12714
} else {
12715
return;
12716
}
12717
}
12718
12719
const llvm::APInt &LeftSideValue = LHSInt->getValue();
12720
llvm::APInt RightSideValue = RHSInt->getValue();
12721
if (LeftSideValue != 2 && LeftSideValue != 10)
12722
return;
12723
12724
if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12725
return;
12726
12727
CharSourceRange ExprRange = CharSourceRange::getCharRange(
12728
LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12729
llvm::StringRef ExprStr =
12730
Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12731
12732
CharSourceRange XorRange =
12733
CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12734
llvm::StringRef XorStr =
12735
Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12736
// Do not diagnose if xor keyword/macro is used.
12737
if (XorStr == "xor")
12738
return;
12739
12740
std::string LHSStr = std::string(Lexer::getSourceText(
12741
CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12742
S.getSourceManager(), S.getLangOpts()));
12743
std::string RHSStr = std::string(Lexer::getSourceText(
12744
CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12745
S.getSourceManager(), S.getLangOpts()));
12746
12747
if (Negative) {
12748
RightSideValue = -RightSideValue;
12749
RHSStr = "-" + RHSStr;
12750
} else if (ExplicitPlus) {
12751
RHSStr = "+" + RHSStr;
12752
}
12753
12754
StringRef LHSStrRef = LHSStr;
12755
StringRef RHSStrRef = RHSStr;
12756
// Do not diagnose literals with digit separators, binary, hexadecimal, octal
12757
// literals.
12758
if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12759
RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12760
LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12761
RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12762
(LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12763
(RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12764
LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12765
return;
12766
12767
bool SuggestXor =
12768
S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12769
const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12770
int64_t RightSideIntValue = RightSideValue.getSExtValue();
12771
if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12772
std::string SuggestedExpr = "1 << " + RHSStr;
12773
bool Overflow = false;
12774
llvm::APInt One = (LeftSideValue - 1);
12775
llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12776
if (Overflow) {
12777
if (RightSideIntValue < 64)
12778
S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12779
<< ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12780
<< FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12781
else if (RightSideIntValue == 64)
12782
S.Diag(Loc, diag::warn_xor_used_as_pow)
12783
<< ExprStr << toString(XorValue, 10, true);
12784
else
12785
return;
12786
} else {
12787
S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12788
<< ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12789
<< toString(PowValue, 10, true)
12790
<< FixItHint::CreateReplacement(
12791
ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12792
}
12793
12794
S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12795
<< ("0x2 ^ " + RHSStr) << SuggestXor;
12796
} else if (LeftSideValue == 10) {
12797
std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12798
S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12799
<< ExprStr << toString(XorValue, 10, true) << SuggestedValue
12800
<< FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12801
S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12802
<< ("0xA ^ " + RHSStr) << SuggestXor;
12803
}
12804
}
12805
12806
QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12807
SourceLocation Loc) {
12808
// Ensure that either both operands are of the same vector type, or
12809
// one operand is of a vector type and the other is of its element type.
12810
QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12811
/*AllowBothBool*/ true,
12812
/*AllowBoolConversions*/ false,
12813
/*AllowBooleanOperation*/ false,
12814
/*ReportInvalid*/ false);
12815
if (vType.isNull())
12816
return InvalidOperands(Loc, LHS, RHS);
12817
if (getLangOpts().OpenCL &&
12818
getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12819
vType->hasFloatingRepresentation())
12820
return InvalidOperands(Loc, LHS, RHS);
12821
// FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12822
// usage of the logical operators && and || with vectors in C. This
12823
// check could be notionally dropped.
12824
if (!getLangOpts().CPlusPlus &&
12825
!(isa<ExtVectorType>(vType->getAs<VectorType>())))
12826
return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12827
12828
return GetSignedVectorType(LHS.get()->getType());
12829
}
12830
12831
QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12832
SourceLocation Loc,
12833
bool IsCompAssign) {
12834
if (!IsCompAssign) {
12835
LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12836
if (LHS.isInvalid())
12837
return QualType();
12838
}
12839
RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12840
if (RHS.isInvalid())
12841
return QualType();
12842
12843
// For conversion purposes, we ignore any qualifiers.
12844
// For example, "const float" and "float" are equivalent.
12845
QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12846
QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12847
12848
const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12849
const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12850
assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12851
12852
if (Context.hasSameType(LHSType, RHSType))
12853
return Context.getCommonSugaredType(LHSType, RHSType);
12854
12855
// Type conversion may change LHS/RHS. Keep copies to the original results, in
12856
// case we have to return InvalidOperands.
12857
ExprResult OriginalLHS = LHS;
12858
ExprResult OriginalRHS = RHS;
12859
if (LHSMatType && !RHSMatType) {
12860
RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12861
if (!RHS.isInvalid())
12862
return LHSType;
12863
12864
return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12865
}
12866
12867
if (!LHSMatType && RHSMatType) {
12868
LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12869
if (!LHS.isInvalid())
12870
return RHSType;
12871
return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12872
}
12873
12874
return InvalidOperands(Loc, LHS, RHS);
12875
}
12876
12877
QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12878
SourceLocation Loc,
12879
bool IsCompAssign) {
12880
if (!IsCompAssign) {
12881
LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12882
if (LHS.isInvalid())
12883
return QualType();
12884
}
12885
RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12886
if (RHS.isInvalid())
12887
return QualType();
12888
12889
auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12890
auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12891
assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12892
12893
if (LHSMatType && RHSMatType) {
12894
if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12895
return InvalidOperands(Loc, LHS, RHS);
12896
12897
if (Context.hasSameType(LHSMatType, RHSMatType))
12898
return Context.getCommonSugaredType(
12899
LHS.get()->getType().getUnqualifiedType(),
12900
RHS.get()->getType().getUnqualifiedType());
12901
12902
QualType LHSELTy = LHSMatType->getElementType(),
12903
RHSELTy = RHSMatType->getElementType();
12904
if (!Context.hasSameType(LHSELTy, RHSELTy))
12905
return InvalidOperands(Loc, LHS, RHS);
12906
12907
return Context.getConstantMatrixType(
12908
Context.getCommonSugaredType(LHSELTy, RHSELTy),
12909
LHSMatType->getNumRows(), RHSMatType->getNumColumns());
12910
}
12911
return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12912
}
12913
12914
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
12915
switch (Opc) {
12916
default:
12917
return false;
12918
case BO_And:
12919
case BO_AndAssign:
12920
case BO_Or:
12921
case BO_OrAssign:
12922
case BO_Xor:
12923
case BO_XorAssign:
12924
return true;
12925
}
12926
}
12927
12928
inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12929
SourceLocation Loc,
12930
BinaryOperatorKind Opc) {
12931
checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12932
12933
bool IsCompAssign =
12934
Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12935
12936
bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
12937
12938
if (LHS.get()->getType()->isVectorType() ||
12939
RHS.get()->getType()->isVectorType()) {
12940
if (LHS.get()->getType()->hasIntegerRepresentation() &&
12941
RHS.get()->getType()->hasIntegerRepresentation())
12942
return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12943
/*AllowBothBool*/ true,
12944
/*AllowBoolConversions*/ getLangOpts().ZVector,
12945
/*AllowBooleanOperation*/ LegalBoolVecOperator,
12946
/*ReportInvalid*/ true);
12947
return InvalidOperands(Loc, LHS, RHS);
12948
}
12949
12950
if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12951
RHS.get()->getType()->isSveVLSBuiltinType()) {
12952
if (LHS.get()->getType()->hasIntegerRepresentation() &&
12953
RHS.get()->getType()->hasIntegerRepresentation())
12954
return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12955
ACK_BitwiseOp);
12956
return InvalidOperands(Loc, LHS, RHS);
12957
}
12958
12959
if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12960
RHS.get()->getType()->isSveVLSBuiltinType()) {
12961
if (LHS.get()->getType()->hasIntegerRepresentation() &&
12962
RHS.get()->getType()->hasIntegerRepresentation())
12963
return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12964
ACK_BitwiseOp);
12965
return InvalidOperands(Loc, LHS, RHS);
12966
}
12967
12968
if (Opc == BO_And)
12969
diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12970
12971
if (LHS.get()->getType()->hasFloatingRepresentation() ||
12972
RHS.get()->getType()->hasFloatingRepresentation())
12973
return InvalidOperands(Loc, LHS, RHS);
12974
12975
ExprResult LHSResult = LHS, RHSResult = RHS;
12976
QualType compType = UsualArithmeticConversions(
12977
LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12978
if (LHSResult.isInvalid() || RHSResult.isInvalid())
12979
return QualType();
12980
LHS = LHSResult.get();
12981
RHS = RHSResult.get();
12982
12983
if (Opc == BO_Xor)
12984
diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12985
12986
if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12987
return compType;
12988
return InvalidOperands(Loc, LHS, RHS);
12989
}
12990
12991
// C99 6.5.[13,14]
12992
inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12993
SourceLocation Loc,
12994
BinaryOperatorKind Opc) {
12995
// Check vector operands differently.
12996
if (LHS.get()->getType()->isVectorType() ||
12997
RHS.get()->getType()->isVectorType())
12998
return CheckVectorLogicalOperands(LHS, RHS, Loc);
12999
13000
bool EnumConstantInBoolContext = false;
13001
for (const ExprResult &HS : {LHS, RHS}) {
13002
if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13003
const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13004
if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13005
EnumConstantInBoolContext = true;
13006
}
13007
}
13008
13009
if (EnumConstantInBoolContext)
13010
Diag(Loc, diag::warn_enum_constant_in_bool_context);
13011
13012
// WebAssembly tables can't be used with logical operators.
13013
QualType LHSTy = LHS.get()->getType();
13014
QualType RHSTy = RHS.get()->getType();
13015
const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13016
const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13017
if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13018
(RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13019
return InvalidOperands(Loc, LHS, RHS);
13020
}
13021
13022
// Diagnose cases where the user write a logical and/or but probably meant a
13023
// bitwise one. We do this when the LHS is a non-bool integer and the RHS
13024
// is a constant.
13025
if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13026
!LHS.get()->getType()->isBooleanType() &&
13027
RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13028
// Don't warn in macros or template instantiations.
13029
!Loc.isMacroID() && !inTemplateInstantiation()) {
13030
// If the RHS can be constant folded, and if it constant folds to something
13031
// that isn't 0 or 1 (which indicate a potential logical operation that
13032
// happened to fold to true/false) then warn.
13033
// Parens on the RHS are ignored.
13034
Expr::EvalResult EVResult;
13035
if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13036
llvm::APSInt Result = EVResult.Val.getInt();
13037
if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13038
!RHS.get()->getExprLoc().isMacroID()) ||
13039
(Result != 0 && Result != 1)) {
13040
Diag(Loc, diag::warn_logical_instead_of_bitwise)
13041
<< RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13042
// Suggest replacing the logical operator with the bitwise version
13043
Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13044
<< (Opc == BO_LAnd ? "&" : "|")
13045
<< FixItHint::CreateReplacement(
13046
SourceRange(Loc, getLocForEndOfToken(Loc)),
13047
Opc == BO_LAnd ? "&" : "|");
13048
if (Opc == BO_LAnd)
13049
// Suggest replacing "Foo() && kNonZero" with "Foo()"
13050
Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13051
<< FixItHint::CreateRemoval(
13052
SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13053
RHS.get()->getEndLoc()));
13054
}
13055
}
13056
}
13057
13058
if (!Context.getLangOpts().CPlusPlus) {
13059
// OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13060
// not operate on the built-in scalar and vector float types.
13061
if (Context.getLangOpts().OpenCL &&
13062
Context.getLangOpts().OpenCLVersion < 120) {
13063
if (LHS.get()->getType()->isFloatingType() ||
13064
RHS.get()->getType()->isFloatingType())
13065
return InvalidOperands(Loc, LHS, RHS);
13066
}
13067
13068
LHS = UsualUnaryConversions(LHS.get());
13069
if (LHS.isInvalid())
13070
return QualType();
13071
13072
RHS = UsualUnaryConversions(RHS.get());
13073
if (RHS.isInvalid())
13074
return QualType();
13075
13076
if (!LHS.get()->getType()->isScalarType() ||
13077
!RHS.get()->getType()->isScalarType())
13078
return InvalidOperands(Loc, LHS, RHS);
13079
13080
return Context.IntTy;
13081
}
13082
13083
// The following is safe because we only use this method for
13084
// non-overloadable operands.
13085
13086
// C++ [expr.log.and]p1
13087
// C++ [expr.log.or]p1
13088
// The operands are both contextually converted to type bool.
13089
ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13090
if (LHSRes.isInvalid())
13091
return InvalidOperands(Loc, LHS, RHS);
13092
LHS = LHSRes;
13093
13094
ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13095
if (RHSRes.isInvalid())
13096
return InvalidOperands(Loc, LHS, RHS);
13097
RHS = RHSRes;
13098
13099
// C++ [expr.log.and]p2
13100
// C++ [expr.log.or]p2
13101
// The result is a bool.
13102
return Context.BoolTy;
13103
}
13104
13105
static bool IsReadonlyMessage(Expr *E, Sema &S) {
13106
const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13107
if (!ME) return false;
13108
if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13109
ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13110
ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13111
if (!Base) return false;
13112
return Base->getMethodDecl() != nullptr;
13113
}
13114
13115
/// Is the given expression (which must be 'const') a reference to a
13116
/// variable which was originally non-const, but which has become
13117
/// 'const' due to being captured within a block?
13118
enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13119
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13120
assert(E->isLValue() && E->getType().isConstQualified());
13121
E = E->IgnoreParens();
13122
13123
// Must be a reference to a declaration from an enclosing scope.
13124
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13125
if (!DRE) return NCCK_None;
13126
if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13127
13128
// The declaration must be a variable which is not declared 'const'.
13129
VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13130
if (!var) return NCCK_None;
13131
if (var->getType().isConstQualified()) return NCCK_None;
13132
assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13133
13134
// Decide whether the first capture was for a block or a lambda.
13135
DeclContext *DC = S.CurContext, *Prev = nullptr;
13136
// Decide whether the first capture was for a block or a lambda.
13137
while (DC) {
13138
// For init-capture, it is possible that the variable belongs to the
13139
// template pattern of the current context.
13140
if (auto *FD = dyn_cast<FunctionDecl>(DC))
13141
if (var->isInitCapture() &&
13142
FD->getTemplateInstantiationPattern() == var->getDeclContext())
13143
break;
13144
if (DC == var->getDeclContext())
13145
break;
13146
Prev = DC;
13147
DC = DC->getParent();
13148
}
13149
// Unless we have an init-capture, we've gone one step too far.
13150
if (!var->isInitCapture())
13151
DC = Prev;
13152
return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13153
}
13154
13155
static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13156
Ty = Ty.getNonReferenceType();
13157
if (IsDereference && Ty->isPointerType())
13158
Ty = Ty->getPointeeType();
13159
return !Ty.isConstQualified();
13160
}
13161
13162
// Update err_typecheck_assign_const and note_typecheck_assign_const
13163
// when this enum is changed.
13164
enum {
13165
ConstFunction,
13166
ConstVariable,
13167
ConstMember,
13168
ConstMethod,
13169
NestedConstMember,
13170
ConstUnknown, // Keep as last element
13171
};
13172
13173
/// Emit the "read-only variable not assignable" error and print notes to give
13174
/// more information about why the variable is not assignable, such as pointing
13175
/// to the declaration of a const variable, showing that a method is const, or
13176
/// that the function is returning a const reference.
13177
static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13178
SourceLocation Loc) {
13179
SourceRange ExprRange = E->getSourceRange();
13180
13181
// Only emit one error on the first const found. All other consts will emit
13182
// a note to the error.
13183
bool DiagnosticEmitted = false;
13184
13185
// Track if the current expression is the result of a dereference, and if the
13186
// next checked expression is the result of a dereference.
13187
bool IsDereference = false;
13188
bool NextIsDereference = false;
13189
13190
// Loop to process MemberExpr chains.
13191
while (true) {
13192
IsDereference = NextIsDereference;
13193
13194
E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13195
if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13196
NextIsDereference = ME->isArrow();
13197
const ValueDecl *VD = ME->getMemberDecl();
13198
if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13199
// Mutable fields can be modified even if the class is const.
13200
if (Field->isMutable()) {
13201
assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13202
break;
13203
}
13204
13205
if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13206
if (!DiagnosticEmitted) {
13207
S.Diag(Loc, diag::err_typecheck_assign_const)
13208
<< ExprRange << ConstMember << false /*static*/ << Field
13209
<< Field->getType();
13210
DiagnosticEmitted = true;
13211
}
13212
S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13213
<< ConstMember << false /*static*/ << Field << Field->getType()
13214
<< Field->getSourceRange();
13215
}
13216
E = ME->getBase();
13217
continue;
13218
} else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13219
if (VDecl->getType().isConstQualified()) {
13220
if (!DiagnosticEmitted) {
13221
S.Diag(Loc, diag::err_typecheck_assign_const)
13222
<< ExprRange << ConstMember << true /*static*/ << VDecl
13223
<< VDecl->getType();
13224
DiagnosticEmitted = true;
13225
}
13226
S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13227
<< ConstMember << true /*static*/ << VDecl << VDecl->getType()
13228
<< VDecl->getSourceRange();
13229
}
13230
// Static fields do not inherit constness from parents.
13231
break;
13232
}
13233
break; // End MemberExpr
13234
} else if (const ArraySubscriptExpr *ASE =
13235
dyn_cast<ArraySubscriptExpr>(E)) {
13236
E = ASE->getBase()->IgnoreParenImpCasts();
13237
continue;
13238
} else if (const ExtVectorElementExpr *EVE =
13239
dyn_cast<ExtVectorElementExpr>(E)) {
13240
E = EVE->getBase()->IgnoreParenImpCasts();
13241
continue;
13242
}
13243
break;
13244
}
13245
13246
if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13247
// Function calls
13248
const FunctionDecl *FD = CE->getDirectCallee();
13249
if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13250
if (!DiagnosticEmitted) {
13251
S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13252
<< ConstFunction << FD;
13253
DiagnosticEmitted = true;
13254
}
13255
S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13256
diag::note_typecheck_assign_const)
13257
<< ConstFunction << FD << FD->getReturnType()
13258
<< FD->getReturnTypeSourceRange();
13259
}
13260
} else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13261
// Point to variable declaration.
13262
if (const ValueDecl *VD = DRE->getDecl()) {
13263
if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13264
if (!DiagnosticEmitted) {
13265
S.Diag(Loc, diag::err_typecheck_assign_const)
13266
<< ExprRange << ConstVariable << VD << VD->getType();
13267
DiagnosticEmitted = true;
13268
}
13269
S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13270
<< ConstVariable << VD << VD->getType() << VD->getSourceRange();
13271
}
13272
}
13273
} else if (isa<CXXThisExpr>(E)) {
13274
if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13275
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13276
if (MD->isConst()) {
13277
if (!DiagnosticEmitted) {
13278
S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13279
<< ConstMethod << MD;
13280
DiagnosticEmitted = true;
13281
}
13282
S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13283
<< ConstMethod << MD << MD->getSourceRange();
13284
}
13285
}
13286
}
13287
}
13288
13289
if (DiagnosticEmitted)
13290
return;
13291
13292
// Can't determine a more specific message, so display the generic error.
13293
S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13294
}
13295
13296
enum OriginalExprKind {
13297
OEK_Variable,
13298
OEK_Member,
13299
OEK_LValue
13300
};
13301
13302
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13303
const RecordType *Ty,
13304
SourceLocation Loc, SourceRange Range,
13305
OriginalExprKind OEK,
13306
bool &DiagnosticEmitted) {
13307
std::vector<const RecordType *> RecordTypeList;
13308
RecordTypeList.push_back(Ty);
13309
unsigned NextToCheckIndex = 0;
13310
// We walk the record hierarchy breadth-first to ensure that we print
13311
// diagnostics in field nesting order.
13312
while (RecordTypeList.size() > NextToCheckIndex) {
13313
bool IsNested = NextToCheckIndex > 0;
13314
for (const FieldDecl *Field :
13315
RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13316
// First, check every field for constness.
13317
QualType FieldTy = Field->getType();
13318
if (FieldTy.isConstQualified()) {
13319
if (!DiagnosticEmitted) {
13320
S.Diag(Loc, diag::err_typecheck_assign_const)
13321
<< Range << NestedConstMember << OEK << VD
13322
<< IsNested << Field;
13323
DiagnosticEmitted = true;
13324
}
13325
S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13326
<< NestedConstMember << IsNested << Field
13327
<< FieldTy << Field->getSourceRange();
13328
}
13329
13330
// Then we append it to the list to check next in order.
13331
FieldTy = FieldTy.getCanonicalType();
13332
if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13333
if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13334
RecordTypeList.push_back(FieldRecTy);
13335
}
13336
}
13337
++NextToCheckIndex;
13338
}
13339
}
13340
13341
/// Emit an error for the case where a record we are trying to assign to has a
13342
/// const-qualified field somewhere in its hierarchy.
13343
static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13344
SourceLocation Loc) {
13345
QualType Ty = E->getType();
13346
assert(Ty->isRecordType() && "lvalue was not record?");
13347
SourceRange Range = E->getSourceRange();
13348
const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13349
bool DiagEmitted = false;
13350
13351
if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13352
DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13353
Range, OEK_Member, DiagEmitted);
13354
else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13355
DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13356
Range, OEK_Variable, DiagEmitted);
13357
else
13358
DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13359
Range, OEK_LValue, DiagEmitted);
13360
if (!DiagEmitted)
13361
DiagnoseConstAssignment(S, E, Loc);
13362
}
13363
13364
/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13365
/// emit an error and return true. If so, return false.
13366
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13367
assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13368
13369
S.CheckShadowingDeclModification(E, Loc);
13370
13371
SourceLocation OrigLoc = Loc;
13372
Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13373
&Loc);
13374
if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13375
IsLV = Expr::MLV_InvalidMessageExpression;
13376
if (IsLV == Expr::MLV_Valid)
13377
return false;
13378
13379
unsigned DiagID = 0;
13380
bool NeedType = false;
13381
switch (IsLV) { // C99 6.5.16p2
13382
case Expr::MLV_ConstQualified:
13383
// Use a specialized diagnostic when we're assigning to an object
13384
// from an enclosing function or block.
13385
if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13386
if (NCCK == NCCK_Block)
13387
DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13388
else
13389
DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13390
break;
13391
}
13392
13393
// In ARC, use some specialized diagnostics for occasions where we
13394
// infer 'const'. These are always pseudo-strong variables.
13395
if (S.getLangOpts().ObjCAutoRefCount) {
13396
DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13397
if (declRef && isa<VarDecl>(declRef->getDecl())) {
13398
VarDecl *var = cast<VarDecl>(declRef->getDecl());
13399
13400
// Use the normal diagnostic if it's pseudo-__strong but the
13401
// user actually wrote 'const'.
13402
if (var->isARCPseudoStrong() &&
13403
(!var->getTypeSourceInfo() ||
13404
!var->getTypeSourceInfo()->getType().isConstQualified())) {
13405
// There are three pseudo-strong cases:
13406
// - self
13407
ObjCMethodDecl *method = S.getCurMethodDecl();
13408
if (method && var == method->getSelfDecl()) {
13409
DiagID = method->isClassMethod()
13410
? diag::err_typecheck_arc_assign_self_class_method
13411
: diag::err_typecheck_arc_assign_self;
13412
13413
// - Objective-C externally_retained attribute.
13414
} else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13415
isa<ParmVarDecl>(var)) {
13416
DiagID = diag::err_typecheck_arc_assign_externally_retained;
13417
13418
// - fast enumeration variables
13419
} else {
13420
DiagID = diag::err_typecheck_arr_assign_enumeration;
13421
}
13422
13423
SourceRange Assign;
13424
if (Loc != OrigLoc)
13425
Assign = SourceRange(OrigLoc, OrigLoc);
13426
S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13427
// We need to preserve the AST regardless, so migration tool
13428
// can do its job.
13429
return false;
13430
}
13431
}
13432
}
13433
13434
// If none of the special cases above are triggered, then this is a
13435
// simple const assignment.
13436
if (DiagID == 0) {
13437
DiagnoseConstAssignment(S, E, Loc);
13438
return true;
13439
}
13440
13441
break;
13442
case Expr::MLV_ConstAddrSpace:
13443
DiagnoseConstAssignment(S, E, Loc);
13444
return true;
13445
case Expr::MLV_ConstQualifiedField:
13446
DiagnoseRecursiveConstFields(S, E, Loc);
13447
return true;
13448
case Expr::MLV_ArrayType:
13449
case Expr::MLV_ArrayTemporary:
13450
DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13451
NeedType = true;
13452
break;
13453
case Expr::MLV_NotObjectType:
13454
DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13455
NeedType = true;
13456
break;
13457
case Expr::MLV_LValueCast:
13458
DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13459
break;
13460
case Expr::MLV_Valid:
13461
llvm_unreachable("did not take early return for MLV_Valid");
13462
case Expr::MLV_InvalidExpression:
13463
case Expr::MLV_MemberFunction:
13464
case Expr::MLV_ClassTemporary:
13465
DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13466
break;
13467
case Expr::MLV_IncompleteType:
13468
case Expr::MLV_IncompleteVoidType:
13469
return S.RequireCompleteType(Loc, E->getType(),
13470
diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13471
case Expr::MLV_DuplicateVectorComponents:
13472
DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13473
break;
13474
case Expr::MLV_NoSetterProperty:
13475
llvm_unreachable("readonly properties should be processed differently");
13476
case Expr::MLV_InvalidMessageExpression:
13477
DiagID = diag::err_readonly_message_assignment;
13478
break;
13479
case Expr::MLV_SubObjCPropertySetting:
13480
DiagID = diag::err_no_subobject_property_setting;
13481
break;
13482
}
13483
13484
SourceRange Assign;
13485
if (Loc != OrigLoc)
13486
Assign = SourceRange(OrigLoc, OrigLoc);
13487
if (NeedType)
13488
S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13489
else
13490
S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13491
return true;
13492
}
13493
13494
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13495
SourceLocation Loc,
13496
Sema &Sema) {
13497
if (Sema.inTemplateInstantiation())
13498
return;
13499
if (Sema.isUnevaluatedContext())
13500
return;
13501
if (Loc.isInvalid() || Loc.isMacroID())
13502
return;
13503
if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13504
return;
13505
13506
// C / C++ fields
13507
MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13508
MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13509
if (ML && MR) {
13510
if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13511
return;
13512
const ValueDecl *LHSDecl =
13513
cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13514
const ValueDecl *RHSDecl =
13515
cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13516
if (LHSDecl != RHSDecl)
13517
return;
13518
if (LHSDecl->getType().isVolatileQualified())
13519
return;
13520
if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13521
if (RefTy->getPointeeType().isVolatileQualified())
13522
return;
13523
13524
Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13525
}
13526
13527
// Objective-C instance variables
13528
ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13529
ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13530
if (OL && OR && OL->getDecl() == OR->getDecl()) {
13531
DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13532
DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13533
if (RL && RR && RL->getDecl() == RR->getDecl())
13534
Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13535
}
13536
}
13537
13538
// C99 6.5.16.1
13539
QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13540
SourceLocation Loc,
13541
QualType CompoundType,
13542
BinaryOperatorKind Opc) {
13543
assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13544
13545
// Verify that LHS is a modifiable lvalue, and emit error if not.
13546
if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13547
return QualType();
13548
13549
QualType LHSType = LHSExpr->getType();
13550
QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13551
CompoundType;
13552
// OpenCL v1.2 s6.1.1.1 p2:
13553
// The half data type can only be used to declare a pointer to a buffer that
13554
// contains half values
13555
if (getLangOpts().OpenCL &&
13556
!getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13557
LHSType->isHalfType()) {
13558
Diag(Loc, diag::err_opencl_half_load_store) << 1
13559
<< LHSType.getUnqualifiedType();
13560
return QualType();
13561
}
13562
13563
// WebAssembly tables can't be used on RHS of an assignment expression.
13564
if (RHSType->isWebAssemblyTableType()) {
13565
Diag(Loc, diag::err_wasm_table_art) << 0;
13566
return QualType();
13567
}
13568
13569
AssignConvertType ConvTy;
13570
if (CompoundType.isNull()) {
13571
Expr *RHSCheck = RHS.get();
13572
13573
CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13574
13575
QualType LHSTy(LHSType);
13576
ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13577
if (RHS.isInvalid())
13578
return QualType();
13579
// Special case of NSObject attributes on c-style pointer types.
13580
if (ConvTy == IncompatiblePointer &&
13581
((Context.isObjCNSObjectType(LHSType) &&
13582
RHSType->isObjCObjectPointerType()) ||
13583
(Context.isObjCNSObjectType(RHSType) &&
13584
LHSType->isObjCObjectPointerType())))
13585
ConvTy = Compatible;
13586
13587
if (ConvTy == Compatible &&
13588
LHSType->isObjCObjectType())
13589
Diag(Loc, diag::err_objc_object_assignment)
13590
<< LHSType;
13591
13592
// If the RHS is a unary plus or minus, check to see if they = and + are
13593
// right next to each other. If so, the user may have typo'd "x =+ 4"
13594
// instead of "x += 4".
13595
if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13596
RHSCheck = ICE->getSubExpr();
13597
if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13598
if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13599
Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13600
// Only if the two operators are exactly adjacent.
13601
Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13602
// And there is a space or other character before the subexpr of the
13603
// unary +/-. We don't want to warn on "x=-1".
13604
Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13605
UO->getSubExpr()->getBeginLoc().isFileID()) {
13606
Diag(Loc, diag::warn_not_compound_assign)
13607
<< (UO->getOpcode() == UO_Plus ? "+" : "-")
13608
<< SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13609
}
13610
}
13611
13612
if (ConvTy == Compatible) {
13613
if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13614
// Warn about retain cycles where a block captures the LHS, but
13615
// not if the LHS is a simple variable into which the block is
13616
// being stored...unless that variable can be captured by reference!
13617
const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13618
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13619
if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13620
ObjC().checkRetainCycles(LHSExpr, RHS.get());
13621
}
13622
13623
if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13624
LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13625
// It is safe to assign a weak reference into a strong variable.
13626
// Although this code can still have problems:
13627
// id x = self.weakProp;
13628
// id y = self.weakProp;
13629
// we do not warn to warn spuriously when 'x' and 'y' are on separate
13630
// paths through the function. This should be revisited if
13631
// -Wrepeated-use-of-weak is made flow-sensitive.
13632
// For ObjCWeak only, we do not warn if the assign is to a non-weak
13633
// variable, which will be valid for the current autorelease scope.
13634
if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13635
RHS.get()->getBeginLoc()))
13636
getCurFunction()->markSafeWeakUse(RHS.get());
13637
13638
} else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13639
checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13640
}
13641
}
13642
} else {
13643
// Compound assignment "x += y"
13644
ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13645
}
13646
13647
if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13648
RHS.get(), AA_Assigning))
13649
return QualType();
13650
13651
CheckForNullPointerDereference(*this, LHSExpr);
13652
13653
AssignedEntity AE{LHSExpr};
13654
checkExprLifetime(*this, AE, RHS.get());
13655
13656
if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13657
if (CompoundType.isNull()) {
13658
// C++2a [expr.ass]p5:
13659
// A simple-assignment whose left operand is of a volatile-qualified
13660
// type is deprecated unless the assignment is either a discarded-value
13661
// expression or an unevaluated operand
13662
ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13663
}
13664
}
13665
13666
// C11 6.5.16p3: The type of an assignment expression is the type of the
13667
// left operand would have after lvalue conversion.
13668
// C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13669
// qualified type, the value has the unqualified version of the type of the
13670
// lvalue; additionally, if the lvalue has atomic type, the value has the
13671
// non-atomic version of the type of the lvalue.
13672
// C++ 5.17p1: the type of the assignment expression is that of its left
13673
// operand.
13674
return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13675
}
13676
13677
// Scenarios to ignore if expression E is:
13678
// 1. an explicit cast expression into void
13679
// 2. a function call expression that returns void
13680
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13681
E = E->IgnoreParens();
13682
13683
if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13684
if (CE->getCastKind() == CK_ToVoid) {
13685
return true;
13686
}
13687
13688
// static_cast<void> on a dependent type will not show up as CK_ToVoid.
13689
if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13690
CE->getSubExpr()->getType()->isDependentType()) {
13691
return true;
13692
}
13693
}
13694
13695
if (const auto *CE = dyn_cast<CallExpr>(E))
13696
return CE->getCallReturnType(Context)->isVoidType();
13697
return false;
13698
}
13699
13700
void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13701
// No warnings in macros
13702
if (Loc.isMacroID())
13703
return;
13704
13705
// Don't warn in template instantiations.
13706
if (inTemplateInstantiation())
13707
return;
13708
13709
// Scope isn't fine-grained enough to explicitly list the specific cases, so
13710
// instead, skip more than needed, then call back into here with the
13711
// CommaVisitor in SemaStmt.cpp.
13712
// The listed locations are the initialization and increment portions
13713
// of a for loop. The additional checks are on the condition of
13714
// if statements, do/while loops, and for loops.
13715
// Differences in scope flags for C89 mode requires the extra logic.
13716
const unsigned ForIncrementFlags =
13717
getLangOpts().C99 || getLangOpts().CPlusPlus
13718
? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13719
: Scope::ContinueScope | Scope::BreakScope;
13720
const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13721
const unsigned ScopeFlags = getCurScope()->getFlags();
13722
if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13723
(ScopeFlags & ForInitFlags) == ForInitFlags)
13724
return;
13725
13726
// If there are multiple comma operators used together, get the RHS of the
13727
// of the comma operator as the LHS.
13728
while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13729
if (BO->getOpcode() != BO_Comma)
13730
break;
13731
LHS = BO->getRHS();
13732
}
13733
13734
// Only allow some expressions on LHS to not warn.
13735
if (IgnoreCommaOperand(LHS, Context))
13736
return;
13737
13738
Diag(Loc, diag::warn_comma_operator);
13739
Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13740
<< LHS->getSourceRange()
13741
<< FixItHint::CreateInsertion(LHS->getBeginLoc(),
13742
LangOpts.CPlusPlus ? "static_cast<void>("
13743
: "(void)(")
13744
<< FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13745
")");
13746
}
13747
13748
// C99 6.5.17
13749
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13750
SourceLocation Loc) {
13751
LHS = S.CheckPlaceholderExpr(LHS.get());
13752
RHS = S.CheckPlaceholderExpr(RHS.get());
13753
if (LHS.isInvalid() || RHS.isInvalid())
13754
return QualType();
13755
13756
// C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13757
// operands, but not unary promotions.
13758
// C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13759
13760
// So we treat the LHS as a ignored value, and in C++ we allow the
13761
// containing site to determine what should be done with the RHS.
13762
LHS = S.IgnoredValueConversions(LHS.get());
13763
if (LHS.isInvalid())
13764
return QualType();
13765
13766
S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13767
13768
if (!S.getLangOpts().CPlusPlus) {
13769
RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13770
if (RHS.isInvalid())
13771
return QualType();
13772
if (!RHS.get()->getType()->isVoidType())
13773
S.RequireCompleteType(Loc, RHS.get()->getType(),
13774
diag::err_incomplete_type);
13775
}
13776
13777
if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13778
S.DiagnoseCommaOperator(LHS.get(), Loc);
13779
13780
return RHS.get()->getType();
13781
}
13782
13783
/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13784
/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13785
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13786
ExprValueKind &VK,
13787
ExprObjectKind &OK,
13788
SourceLocation OpLoc, bool IsInc,
13789
bool IsPrefix) {
13790
QualType ResType = Op->getType();
13791
// Atomic types can be used for increment / decrement where the non-atomic
13792
// versions can, so ignore the _Atomic() specifier for the purpose of
13793
// checking.
13794
if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13795
ResType = ResAtomicType->getValueType();
13796
13797
assert(!ResType.isNull() && "no type for increment/decrement expression");
13798
13799
if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13800
// Decrement of bool is not allowed.
13801
if (!IsInc) {
13802
S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13803
return QualType();
13804
}
13805
// Increment of bool sets it to true, but is deprecated.
13806
S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13807
: diag::warn_increment_bool)
13808
<< Op->getSourceRange();
13809
} else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13810
// Error on enum increments and decrements in C++ mode
13811
S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13812
return QualType();
13813
} else if (ResType->isRealType()) {
13814
// OK!
13815
} else if (ResType->isPointerType()) {
13816
// C99 6.5.2.4p2, 6.5.6p2
13817
if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13818
return QualType();
13819
} else if (ResType->isObjCObjectPointerType()) {
13820
// On modern runtimes, ObjC pointer arithmetic is forbidden.
13821
// Otherwise, we just need a complete type.
13822
if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13823
checkArithmeticOnObjCPointer(S, OpLoc, Op))
13824
return QualType();
13825
} else if (ResType->isAnyComplexType()) {
13826
// C99 does not support ++/-- on complex types, we allow as an extension.
13827
S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
13828
: diag::ext_c2y_increment_complex)
13829
<< IsInc << Op->getSourceRange();
13830
} else if (ResType->isPlaceholderType()) {
13831
ExprResult PR = S.CheckPlaceholderExpr(Op);
13832
if (PR.isInvalid()) return QualType();
13833
return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13834
IsInc, IsPrefix);
13835
} else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13836
// OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13837
} else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13838
(ResType->castAs<VectorType>()->getVectorKind() !=
13839
VectorKind::AltiVecBool)) {
13840
// The z vector extensions allow ++ and -- for non-bool vectors.
13841
} else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
13842
ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13843
// OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13844
} else {
13845
S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13846
<< ResType << int(IsInc) << Op->getSourceRange();
13847
return QualType();
13848
}
13849
// At this point, we know we have a real, complex or pointer type.
13850
// Now make sure the operand is a modifiable lvalue.
13851
if (CheckForModifiableLvalue(Op, OpLoc, S))
13852
return QualType();
13853
if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13854
// C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13855
// An operand with volatile-qualified type is deprecated
13856
S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13857
<< IsInc << ResType;
13858
}
13859
// In C++, a prefix increment is the same type as the operand. Otherwise
13860
// (in C or with postfix), the increment is the unqualified type of the
13861
// operand.
13862
if (IsPrefix && S.getLangOpts().CPlusPlus) {
13863
VK = VK_LValue;
13864
OK = Op->getObjectKind();
13865
return ResType;
13866
} else {
13867
VK = VK_PRValue;
13868
return ResType.getUnqualifiedType();
13869
}
13870
}
13871
13872
/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13873
/// This routine allows us to typecheck complex/recursive expressions
13874
/// where the declaration is needed for type checking. We only need to
13875
/// handle cases when the expression references a function designator
13876
/// or is an lvalue. Here are some examples:
13877
/// - &(x) => x
13878
/// - &*****f => f for f a function designator.
13879
/// - &s.xx => s
13880
/// - &s.zz[1].yy -> s, if zz is an array
13881
/// - *(x + 1) -> x, if x is an array
13882
/// - &"123"[2] -> 0
13883
/// - & __real__ x -> x
13884
///
13885
/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13886
/// members.
13887
static ValueDecl *getPrimaryDecl(Expr *E) {
13888
switch (E->getStmtClass()) {
13889
case Stmt::DeclRefExprClass:
13890
return cast<DeclRefExpr>(E)->getDecl();
13891
case Stmt::MemberExprClass:
13892
// If this is an arrow operator, the address is an offset from
13893
// the base's value, so the object the base refers to is
13894
// irrelevant.
13895
if (cast<MemberExpr>(E)->isArrow())
13896
return nullptr;
13897
// Otherwise, the expression refers to a part of the base
13898
return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13899
case Stmt::ArraySubscriptExprClass: {
13900
// FIXME: This code shouldn't be necessary! We should catch the implicit
13901
// promotion of register arrays earlier.
13902
Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13903
if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13904
if (ICE->getSubExpr()->getType()->isArrayType())
13905
return getPrimaryDecl(ICE->getSubExpr());
13906
}
13907
return nullptr;
13908
}
13909
case Stmt::UnaryOperatorClass: {
13910
UnaryOperator *UO = cast<UnaryOperator>(E);
13911
13912
switch(UO->getOpcode()) {
13913
case UO_Real:
13914
case UO_Imag:
13915
case UO_Extension:
13916
return getPrimaryDecl(UO->getSubExpr());
13917
default:
13918
return nullptr;
13919
}
13920
}
13921
case Stmt::ParenExprClass:
13922
return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13923
case Stmt::ImplicitCastExprClass:
13924
// If the result of an implicit cast is an l-value, we care about
13925
// the sub-expression; otherwise, the result here doesn't matter.
13926
return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13927
case Stmt::CXXUuidofExprClass:
13928
return cast<CXXUuidofExpr>(E)->getGuidDecl();
13929
default:
13930
return nullptr;
13931
}
13932
}
13933
13934
namespace {
13935
enum {
13936
AO_Bit_Field = 0,
13937
AO_Vector_Element = 1,
13938
AO_Property_Expansion = 2,
13939
AO_Register_Variable = 3,
13940
AO_Matrix_Element = 4,
13941
AO_No_Error = 5
13942
};
13943
}
13944
/// Diagnose invalid operand for address of operations.
13945
///
13946
/// \param Type The type of operand which cannot have its address taken.
13947
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13948
Expr *E, unsigned Type) {
13949
S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13950
}
13951
13952
bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
13953
const Expr *Op,
13954
const CXXMethodDecl *MD) {
13955
const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
13956
13957
if (Op != DRE)
13958
return Diag(OpLoc, diag::err_parens_pointer_member_function)
13959
<< Op->getSourceRange();
13960
13961
// Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13962
if (isa<CXXDestructorDecl>(MD))
13963
return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
13964
<< DRE->getSourceRange();
13965
13966
if (DRE->getQualifier())
13967
return false;
13968
13969
if (MD->getParent()->getName().empty())
13970
return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13971
<< DRE->getSourceRange();
13972
13973
SmallString<32> Str;
13974
StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13975
return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13976
<< DRE->getSourceRange()
13977
<< FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
13978
}
13979
13980
QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13981
if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13982
if (PTy->getKind() == BuiltinType::Overload) {
13983
Expr *E = OrigOp.get()->IgnoreParens();
13984
if (!isa<OverloadExpr>(E)) {
13985
assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13986
Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13987
<< OrigOp.get()->getSourceRange();
13988
return QualType();
13989
}
13990
13991
OverloadExpr *Ovl = cast<OverloadExpr>(E);
13992
if (isa<UnresolvedMemberExpr>(Ovl))
13993
if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13994
Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13995
<< OrigOp.get()->getSourceRange();
13996
return QualType();
13997
}
13998
13999
return Context.OverloadTy;
14000
}
14001
14002
if (PTy->getKind() == BuiltinType::UnknownAny)
14003
return Context.UnknownAnyTy;
14004
14005
if (PTy->getKind() == BuiltinType::BoundMember) {
14006
Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14007
<< OrigOp.get()->getSourceRange();
14008
return QualType();
14009
}
14010
14011
OrigOp = CheckPlaceholderExpr(OrigOp.get());
14012
if (OrigOp.isInvalid()) return QualType();
14013
}
14014
14015
if (OrigOp.get()->isTypeDependent())
14016
return Context.DependentTy;
14017
14018
assert(!OrigOp.get()->hasPlaceholderType());
14019
14020
// Make sure to ignore parentheses in subsequent checks
14021
Expr *op = OrigOp.get()->IgnoreParens();
14022
14023
// In OpenCL captures for blocks called as lambda functions
14024
// are located in the private address space. Blocks used in
14025
// enqueue_kernel can be located in a different address space
14026
// depending on a vendor implementation. Thus preventing
14027
// taking an address of the capture to avoid invalid AS casts.
14028
if (LangOpts.OpenCL) {
14029
auto* VarRef = dyn_cast<DeclRefExpr>(op);
14030
if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14031
Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14032
return QualType();
14033
}
14034
}
14035
14036
if (getLangOpts().C99) {
14037
// Implement C99-only parts of addressof rules.
14038
if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14039
if (uOp->getOpcode() == UO_Deref)
14040
// Per C99 6.5.3.2, the address of a deref always returns a valid result
14041
// (assuming the deref expression is valid).
14042
return uOp->getSubExpr()->getType();
14043
}
14044
// Technically, there should be a check for array subscript
14045
// expressions here, but the result of one is always an lvalue anyway.
14046
}
14047
ValueDecl *dcl = getPrimaryDecl(op);
14048
14049
if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14050
if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14051
op->getBeginLoc()))
14052
return QualType();
14053
14054
Expr::LValueClassification lval = op->ClassifyLValue(Context);
14055
unsigned AddressOfError = AO_No_Error;
14056
14057
if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14058
bool sfinae = (bool)isSFINAEContext();
14059
Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14060
: diag::ext_typecheck_addrof_temporary)
14061
<< op->getType() << op->getSourceRange();
14062
if (sfinae)
14063
return QualType();
14064
// Materialize the temporary as an lvalue so that we can take its address.
14065
OrigOp = op =
14066
CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14067
} else if (isa<ObjCSelectorExpr>(op)) {
14068
return Context.getPointerType(op->getType());
14069
} else if (lval == Expr::LV_MemberFunction) {
14070
// If it's an instance method, make a member pointer.
14071
// The expression must have exactly the form &A::foo.
14072
14073
// If the underlying expression isn't a decl ref, give up.
14074
if (!isa<DeclRefExpr>(op)) {
14075
Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14076
<< OrigOp.get()->getSourceRange();
14077
return QualType();
14078
}
14079
DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14080
CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14081
14082
CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14083
14084
QualType MPTy = Context.getMemberPointerType(
14085
op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14086
14087
if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14088
!isUnevaluatedContext() && !MPTy->isDependentType()) {
14089
// When pointer authentication is enabled, argument and return types of
14090
// vitual member functions must be complete. This is because vitrual
14091
// member function pointers are implemented using virtual dispatch
14092
// thunks and the thunks cannot be emitted if the argument or return
14093
// types are incomplete.
14094
auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14095
SourceLocation DeclRefLoc,
14096
SourceLocation RetArgTypeLoc) {
14097
if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14098
Diag(DeclRefLoc,
14099
diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14100
Diag(RetArgTypeLoc,
14101
diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14102
<< T;
14103
return true;
14104
}
14105
return false;
14106
};
14107
QualType RetTy = MD->getReturnType();
14108
bool IsIncomplete =
14109
!RetTy->isVoidType() &&
14110
ReturnOrParamTypeIsIncomplete(
14111
RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14112
for (auto *PVD : MD->parameters())
14113
IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14114
PVD->getBeginLoc());
14115
if (IsIncomplete)
14116
return QualType();
14117
}
14118
14119
// Under the MS ABI, lock down the inheritance model now.
14120
if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14121
(void)isCompleteType(OpLoc, MPTy);
14122
return MPTy;
14123
} else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14124
// C99 6.5.3.2p1
14125
// The operand must be either an l-value or a function designator
14126
if (!op->getType()->isFunctionType()) {
14127
// Use a special diagnostic for loads from property references.
14128
if (isa<PseudoObjectExpr>(op)) {
14129
AddressOfError = AO_Property_Expansion;
14130
} else {
14131
Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14132
<< op->getType() << op->getSourceRange();
14133
return QualType();
14134
}
14135
} else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14136
if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14137
CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14138
}
14139
14140
} else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14141
// The operand cannot be a bit-field
14142
AddressOfError = AO_Bit_Field;
14143
} else if (op->getObjectKind() == OK_VectorComponent) {
14144
// The operand cannot be an element of a vector
14145
AddressOfError = AO_Vector_Element;
14146
} else if (op->getObjectKind() == OK_MatrixComponent) {
14147
// The operand cannot be an element of a matrix.
14148
AddressOfError = AO_Matrix_Element;
14149
} else if (dcl) { // C99 6.5.3.2p1
14150
// We have an lvalue with a decl. Make sure the decl is not declared
14151
// with the register storage-class specifier.
14152
if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14153
// in C++ it is not error to take address of a register
14154
// variable (c++03 7.1.1P3)
14155
if (vd->getStorageClass() == SC_Register &&
14156
!getLangOpts().CPlusPlus) {
14157
AddressOfError = AO_Register_Variable;
14158
}
14159
} else if (isa<MSPropertyDecl>(dcl)) {
14160
AddressOfError = AO_Property_Expansion;
14161
} else if (isa<FunctionTemplateDecl>(dcl)) {
14162
return Context.OverloadTy;
14163
} else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14164
// Okay: we can take the address of a field.
14165
// Could be a pointer to member, though, if there is an explicit
14166
// scope qualifier for the class.
14167
14168
// [C++26] [expr.prim.id.general]
14169
// If an id-expression E denotes a non-static non-type member
14170
// of some class C [...] and if E is a qualified-id, E is
14171
// not the un-parenthesized operand of the unary & operator [...]
14172
// the id-expression is transformed into a class member access expression.
14173
if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
14174
!isa<ParenExpr>(OrigOp.get())) {
14175
DeclContext *Ctx = dcl->getDeclContext();
14176
if (Ctx && Ctx->isRecord()) {
14177
if (dcl->getType()->isReferenceType()) {
14178
Diag(OpLoc,
14179
diag::err_cannot_form_pointer_to_member_of_reference_type)
14180
<< dcl->getDeclName() << dcl->getType();
14181
return QualType();
14182
}
14183
14184
while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14185
Ctx = Ctx->getParent();
14186
14187
QualType MPTy = Context.getMemberPointerType(
14188
op->getType(),
14189
Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14190
// Under the MS ABI, lock down the inheritance model now.
14191
if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14192
(void)isCompleteType(OpLoc, MPTy);
14193
return MPTy;
14194
}
14195
}
14196
} else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14197
MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14198
llvm_unreachable("Unknown/unexpected decl type");
14199
}
14200
14201
if (AddressOfError != AO_No_Error) {
14202
diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14203
return QualType();
14204
}
14205
14206
if (lval == Expr::LV_IncompleteVoidType) {
14207
// Taking the address of a void variable is technically illegal, but we
14208
// allow it in cases which are otherwise valid.
14209
// Example: "extern void x; void* y = &x;".
14210
Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14211
}
14212
14213
// If the operand has type "type", the result has type "pointer to type".
14214
if (op->getType()->isObjCObjectType())
14215
return Context.getObjCObjectPointerType(op->getType());
14216
14217
// Cannot take the address of WebAssembly references or tables.
14218
if (Context.getTargetInfo().getTriple().isWasm()) {
14219
QualType OpTy = op->getType();
14220
if (OpTy.isWebAssemblyReferenceType()) {
14221
Diag(OpLoc, diag::err_wasm_ca_reference)
14222
<< 1 << OrigOp.get()->getSourceRange();
14223
return QualType();
14224
}
14225
if (OpTy->isWebAssemblyTableType()) {
14226
Diag(OpLoc, diag::err_wasm_table_pr)
14227
<< 1 << OrigOp.get()->getSourceRange();
14228
return QualType();
14229
}
14230
}
14231
14232
CheckAddressOfPackedMember(op);
14233
14234
return Context.getPointerType(op->getType());
14235
}
14236
14237
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14238
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14239
if (!DRE)
14240
return;
14241
const Decl *D = DRE->getDecl();
14242
if (!D)
14243
return;
14244
const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14245
if (!Param)
14246
return;
14247
if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14248
if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14249
return;
14250
if (FunctionScopeInfo *FD = S.getCurFunction())
14251
FD->ModifiedNonNullParams.insert(Param);
14252
}
14253
14254
/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14255
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14256
SourceLocation OpLoc,
14257
bool IsAfterAmp = false) {
14258
ExprResult ConvResult = S.UsualUnaryConversions(Op);
14259
if (ConvResult.isInvalid())
14260
return QualType();
14261
Op = ConvResult.get();
14262
QualType OpTy = Op->getType();
14263
QualType Result;
14264
14265
if (isa<CXXReinterpretCastExpr>(Op)) {
14266
QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14267
S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14268
Op->getSourceRange());
14269
}
14270
14271
if (const PointerType *PT = OpTy->getAs<PointerType>())
14272
{
14273
Result = PT->getPointeeType();
14274
}
14275
else if (const ObjCObjectPointerType *OPT =
14276
OpTy->getAs<ObjCObjectPointerType>())
14277
Result = OPT->getPointeeType();
14278
else {
14279
ExprResult PR = S.CheckPlaceholderExpr(Op);
14280
if (PR.isInvalid()) return QualType();
14281
if (PR.get() != Op)
14282
return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14283
}
14284
14285
if (Result.isNull()) {
14286
S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14287
<< OpTy << Op->getSourceRange();
14288
return QualType();
14289
}
14290
14291
if (Result->isVoidType()) {
14292
// C++ [expr.unary.op]p1:
14293
// [...] the expression to which [the unary * operator] is applied shall
14294
// be a pointer to an object type, or a pointer to a function type
14295
LangOptions LO = S.getLangOpts();
14296
if (LO.CPlusPlus)
14297
S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14298
<< OpTy << Op->getSourceRange();
14299
else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14300
S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14301
<< OpTy << Op->getSourceRange();
14302
}
14303
14304
// Dereferences are usually l-values...
14305
VK = VK_LValue;
14306
14307
// ...except that certain expressions are never l-values in C.
14308
if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14309
VK = VK_PRValue;
14310
14311
return Result;
14312
}
14313
14314
BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14315
BinaryOperatorKind Opc;
14316
switch (Kind) {
14317
default: llvm_unreachable("Unknown binop!");
14318
case tok::periodstar: Opc = BO_PtrMemD; break;
14319
case tok::arrowstar: Opc = BO_PtrMemI; break;
14320
case tok::star: Opc = BO_Mul; break;
14321
case tok::slash: Opc = BO_Div; break;
14322
case tok::percent: Opc = BO_Rem; break;
14323
case tok::plus: Opc = BO_Add; break;
14324
case tok::minus: Opc = BO_Sub; break;
14325
case tok::lessless: Opc = BO_Shl; break;
14326
case tok::greatergreater: Opc = BO_Shr; break;
14327
case tok::lessequal: Opc = BO_LE; break;
14328
case tok::less: Opc = BO_LT; break;
14329
case tok::greaterequal: Opc = BO_GE; break;
14330
case tok::greater: Opc = BO_GT; break;
14331
case tok::exclaimequal: Opc = BO_NE; break;
14332
case tok::equalequal: Opc = BO_EQ; break;
14333
case tok::spaceship: Opc = BO_Cmp; break;
14334
case tok::amp: Opc = BO_And; break;
14335
case tok::caret: Opc = BO_Xor; break;
14336
case tok::pipe: Opc = BO_Or; break;
14337
case tok::ampamp: Opc = BO_LAnd; break;
14338
case tok::pipepipe: Opc = BO_LOr; break;
14339
case tok::equal: Opc = BO_Assign; break;
14340
case tok::starequal: Opc = BO_MulAssign; break;
14341
case tok::slashequal: Opc = BO_DivAssign; break;
14342
case tok::percentequal: Opc = BO_RemAssign; break;
14343
case tok::plusequal: Opc = BO_AddAssign; break;
14344
case tok::minusequal: Opc = BO_SubAssign; break;
14345
case tok::lesslessequal: Opc = BO_ShlAssign; break;
14346
case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14347
case tok::ampequal: Opc = BO_AndAssign; break;
14348
case tok::caretequal: Opc = BO_XorAssign; break;
14349
case tok::pipeequal: Opc = BO_OrAssign; break;
14350
case tok::comma: Opc = BO_Comma; break;
14351
}
14352
return Opc;
14353
}
14354
14355
static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14356
tok::TokenKind Kind) {
14357
UnaryOperatorKind Opc;
14358
switch (Kind) {
14359
default: llvm_unreachable("Unknown unary op!");
14360
case tok::plusplus: Opc = UO_PreInc; break;
14361
case tok::minusminus: Opc = UO_PreDec; break;
14362
case tok::amp: Opc = UO_AddrOf; break;
14363
case tok::star: Opc = UO_Deref; break;
14364
case tok::plus: Opc = UO_Plus; break;
14365
case tok::minus: Opc = UO_Minus; break;
14366
case tok::tilde: Opc = UO_Not; break;
14367
case tok::exclaim: Opc = UO_LNot; break;
14368
case tok::kw___real: Opc = UO_Real; break;
14369
case tok::kw___imag: Opc = UO_Imag; break;
14370
case tok::kw___extension__: Opc = UO_Extension; break;
14371
}
14372
return Opc;
14373
}
14374
14375
const FieldDecl *
14376
Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
14377
// Explore the case for adding 'this->' to the LHS of a self assignment, very
14378
// common for setters.
14379
// struct A {
14380
// int X;
14381
// -void setX(int X) { X = X; }
14382
// +void setX(int X) { this->X = X; }
14383
// };
14384
14385
// Only consider parameters for self assignment fixes.
14386
if (!isa<ParmVarDecl>(SelfAssigned))
14387
return nullptr;
14388
const auto *Method =
14389
dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14390
if (!Method)
14391
return nullptr;
14392
14393
const CXXRecordDecl *Parent = Method->getParent();
14394
// In theory this is fixable if the lambda explicitly captures this, but
14395
// that's added complexity that's rarely going to be used.
14396
if (Parent->isLambda())
14397
return nullptr;
14398
14399
// FIXME: Use an actual Lookup operation instead of just traversing fields
14400
// in order to get base class fields.
14401
auto Field =
14402
llvm::find_if(Parent->fields(),
14403
[Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14404
return F->getDeclName() == Name;
14405
});
14406
return (Field != Parent->field_end()) ? *Field : nullptr;
14407
}
14408
14409
/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14410
/// This warning suppressed in the event of macro expansions.
14411
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14412
SourceLocation OpLoc, bool IsBuiltin) {
14413
if (S.inTemplateInstantiation())
14414
return;
14415
if (S.isUnevaluatedContext())
14416
return;
14417
if (OpLoc.isInvalid() || OpLoc.isMacroID())
14418
return;
14419
LHSExpr = LHSExpr->IgnoreParenImpCasts();
14420
RHSExpr = RHSExpr->IgnoreParenImpCasts();
14421
const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14422
const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14423
if (!LHSDeclRef || !RHSDeclRef ||
14424
LHSDeclRef->getLocation().isMacroID() ||
14425
RHSDeclRef->getLocation().isMacroID())
14426
return;
14427
const ValueDecl *LHSDecl =
14428
cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14429
const ValueDecl *RHSDecl =
14430
cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14431
if (LHSDecl != RHSDecl)
14432
return;
14433
if (LHSDecl->getType().isVolatileQualified())
14434
return;
14435
if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14436
if (RefTy->getPointeeType().isVolatileQualified())
14437
return;
14438
14439
auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14440
: diag::warn_self_assignment_overloaded)
14441
<< LHSDeclRef->getType() << LHSExpr->getSourceRange()
14442
<< RHSExpr->getSourceRange();
14443
if (const FieldDecl *SelfAssignField =
14444
S.getSelfAssignmentClassMemberCandidate(RHSDecl))
14445
Diag << 1 << SelfAssignField
14446
<< FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14447
else
14448
Diag << 0;
14449
}
14450
14451
/// Check if a bitwise-& is performed on an Objective-C pointer. This
14452
/// is usually indicative of introspection within the Objective-C pointer.
14453
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14454
SourceLocation OpLoc) {
14455
if (!S.getLangOpts().ObjC)
14456
return;
14457
14458
const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14459
const Expr *LHS = L.get();
14460
const Expr *RHS = R.get();
14461
14462
if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14463
ObjCPointerExpr = LHS;
14464
OtherExpr = RHS;
14465
}
14466
else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14467
ObjCPointerExpr = RHS;
14468
OtherExpr = LHS;
14469
}
14470
14471
// This warning is deliberately made very specific to reduce false
14472
// positives with logic that uses '&' for hashing. This logic mainly
14473
// looks for code trying to introspect into tagged pointers, which
14474
// code should generally never do.
14475
if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14476
unsigned Diag = diag::warn_objc_pointer_masking;
14477
// Determine if we are introspecting the result of performSelectorXXX.
14478
const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14479
// Special case messages to -performSelector and friends, which
14480
// can return non-pointer values boxed in a pointer value.
14481
// Some clients may wish to silence warnings in this subcase.
14482
if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14483
Selector S = ME->getSelector();
14484
StringRef SelArg0 = S.getNameForSlot(0);
14485
if (SelArg0.starts_with("performSelector"))
14486
Diag = diag::warn_objc_pointer_masking_performSelector;
14487
}
14488
14489
S.Diag(OpLoc, Diag)
14490
<< ObjCPointerExpr->getSourceRange();
14491
}
14492
}
14493
14494
static NamedDecl *getDeclFromExpr(Expr *E) {
14495
if (!E)
14496
return nullptr;
14497
if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14498
return DRE->getDecl();
14499
if (auto *ME = dyn_cast<MemberExpr>(E))
14500
return ME->getMemberDecl();
14501
if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14502
return IRE->getDecl();
14503
return nullptr;
14504
}
14505
14506
// This helper function promotes a binary operator's operands (which are of a
14507
// half vector type) to a vector of floats and then truncates the result to
14508
// a vector of either half or short.
14509
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14510
BinaryOperatorKind Opc, QualType ResultTy,
14511
ExprValueKind VK, ExprObjectKind OK,
14512
bool IsCompAssign, SourceLocation OpLoc,
14513
FPOptionsOverride FPFeatures) {
14514
auto &Context = S.getASTContext();
14515
assert((isVector(ResultTy, Context.HalfTy) ||
14516
isVector(ResultTy, Context.ShortTy)) &&
14517
"Result must be a vector of half or short");
14518
assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14519
isVector(RHS.get()->getType(), Context.HalfTy) &&
14520
"both operands expected to be a half vector");
14521
14522
RHS = convertVector(RHS.get(), Context.FloatTy, S);
14523
QualType BinOpResTy = RHS.get()->getType();
14524
14525
// If Opc is a comparison, ResultType is a vector of shorts. In that case,
14526
// change BinOpResTy to a vector of ints.
14527
if (isVector(ResultTy, Context.ShortTy))
14528
BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14529
14530
if (IsCompAssign)
14531
return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14532
ResultTy, VK, OK, OpLoc, FPFeatures,
14533
BinOpResTy, BinOpResTy);
14534
14535
LHS = convertVector(LHS.get(), Context.FloatTy, S);
14536
auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14537
BinOpResTy, VK, OK, OpLoc, FPFeatures);
14538
return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14539
}
14540
14541
static std::pair<ExprResult, ExprResult>
14542
CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14543
Expr *RHSExpr) {
14544
ExprResult LHS = LHSExpr, RHS = RHSExpr;
14545
if (!S.Context.isDependenceAllowed()) {
14546
// C cannot handle TypoExpr nodes on either side of a binop because it
14547
// doesn't handle dependent types properly, so make sure any TypoExprs have
14548
// been dealt with before checking the operands.
14549
LHS = S.CorrectDelayedTyposInExpr(LHS);
14550
RHS = S.CorrectDelayedTyposInExpr(
14551
RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14552
[Opc, LHS](Expr *E) {
14553
if (Opc != BO_Assign)
14554
return ExprResult(E);
14555
// Avoid correcting the RHS to the same Expr as the LHS.
14556
Decl *D = getDeclFromExpr(E);
14557
return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14558
});
14559
}
14560
return std::make_pair(LHS, RHS);
14561
}
14562
14563
/// Returns true if conversion between vectors of halfs and vectors of floats
14564
/// is needed.
14565
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14566
Expr *E0, Expr *E1 = nullptr) {
14567
if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14568
Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14569
return false;
14570
14571
auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14572
QualType Ty = E->IgnoreImplicit()->getType();
14573
14574
// Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14575
// to vectors of floats. Although the element type of the vectors is __fp16,
14576
// the vectors shouldn't be treated as storage-only types. See the
14577
// discussion here: https://reviews.llvm.org/rG825235c140e7
14578
if (const VectorType *VT = Ty->getAs<VectorType>()) {
14579
if (VT->getVectorKind() == VectorKind::Neon)
14580
return false;
14581
return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14582
}
14583
return false;
14584
};
14585
14586
return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14587
}
14588
14589
ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14590
BinaryOperatorKind Opc,
14591
Expr *LHSExpr, Expr *RHSExpr) {
14592
if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14593
// The syntax only allows initializer lists on the RHS of assignment,
14594
// so we don't need to worry about accepting invalid code for
14595
// non-assignment operators.
14596
// C++11 5.17p9:
14597
// The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14598
// of x = {} is x = T().
14599
InitializationKind Kind = InitializationKind::CreateDirectList(
14600
RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14601
InitializedEntity Entity =
14602
InitializedEntity::InitializeTemporary(LHSExpr->getType());
14603
InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14604
ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14605
if (Init.isInvalid())
14606
return Init;
14607
RHSExpr = Init.get();
14608
}
14609
14610
ExprResult LHS = LHSExpr, RHS = RHSExpr;
14611
QualType ResultTy; // Result type of the binary operator.
14612
// The following two variables are used for compound assignment operators
14613
QualType CompLHSTy; // Type of LHS after promotions for computation
14614
QualType CompResultTy; // Type of computation result
14615
ExprValueKind VK = VK_PRValue;
14616
ExprObjectKind OK = OK_Ordinary;
14617
bool ConvertHalfVec = false;
14618
14619
std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14620
if (!LHS.isUsable() || !RHS.isUsable())
14621
return ExprError();
14622
14623
if (getLangOpts().OpenCL) {
14624
QualType LHSTy = LHSExpr->getType();
14625
QualType RHSTy = RHSExpr->getType();
14626
// OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14627
// the ATOMIC_VAR_INIT macro.
14628
if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14629
SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14630
if (BO_Assign == Opc)
14631
Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14632
else
14633
ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14634
return ExprError();
14635
}
14636
14637
// OpenCL special types - image, sampler, pipe, and blocks are to be used
14638
// only with a builtin functions and therefore should be disallowed here.
14639
if (LHSTy->isImageType() || RHSTy->isImageType() ||
14640
LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14641
LHSTy->isPipeType() || RHSTy->isPipeType() ||
14642
LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14643
ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14644
return ExprError();
14645
}
14646
}
14647
14648
checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14649
checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14650
14651
switch (Opc) {
14652
case BO_Assign:
14653
ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14654
if (getLangOpts().CPlusPlus &&
14655
LHS.get()->getObjectKind() != OK_ObjCProperty) {
14656
VK = LHS.get()->getValueKind();
14657
OK = LHS.get()->getObjectKind();
14658
}
14659
if (!ResultTy.isNull()) {
14660
DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14661
DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14662
14663
// Avoid copying a block to the heap if the block is assigned to a local
14664
// auto variable that is declared in the same scope as the block. This
14665
// optimization is unsafe if the local variable is declared in an outer
14666
// scope. For example:
14667
//
14668
// BlockTy b;
14669
// {
14670
// b = ^{...};
14671
// }
14672
// // It is unsafe to invoke the block here if it wasn't copied to the
14673
// // heap.
14674
// b();
14675
14676
if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14677
if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14678
if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14679
if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14680
BE->getBlockDecl()->setCanAvoidCopyToHeap();
14681
14682
if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14683
checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14684
NTCUC_Assignment, NTCUK_Copy);
14685
}
14686
RecordModifiableNonNullParam(*this, LHS.get());
14687
break;
14688
case BO_PtrMemD:
14689
case BO_PtrMemI:
14690
ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14691
Opc == BO_PtrMemI);
14692
break;
14693
case BO_Mul:
14694
case BO_Div:
14695
ConvertHalfVec = true;
14696
ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14697
Opc == BO_Div);
14698
break;
14699
case BO_Rem:
14700
ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14701
break;
14702
case BO_Add:
14703
ConvertHalfVec = true;
14704
ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14705
break;
14706
case BO_Sub:
14707
ConvertHalfVec = true;
14708
ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14709
break;
14710
case BO_Shl:
14711
case BO_Shr:
14712
ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14713
break;
14714
case BO_LE:
14715
case BO_LT:
14716
case BO_GE:
14717
case BO_GT:
14718
ConvertHalfVec = true;
14719
ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14720
14721
if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14722
BI && BI->isComparisonOp())
14723
Diag(OpLoc, diag::warn_consecutive_comparison);
14724
14725
break;
14726
case BO_EQ:
14727
case BO_NE:
14728
ConvertHalfVec = true;
14729
ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14730
break;
14731
case BO_Cmp:
14732
ConvertHalfVec = true;
14733
ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14734
assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14735
break;
14736
case BO_And:
14737
checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14738
[[fallthrough]];
14739
case BO_Xor:
14740
case BO_Or:
14741
ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14742
break;
14743
case BO_LAnd:
14744
case BO_LOr:
14745
ConvertHalfVec = true;
14746
ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14747
break;
14748
case BO_MulAssign:
14749
case BO_DivAssign:
14750
ConvertHalfVec = true;
14751
CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14752
Opc == BO_DivAssign);
14753
CompLHSTy = CompResultTy;
14754
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14755
ResultTy =
14756
CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14757
break;
14758
case BO_RemAssign:
14759
CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14760
CompLHSTy = CompResultTy;
14761
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14762
ResultTy =
14763
CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14764
break;
14765
case BO_AddAssign:
14766
ConvertHalfVec = true;
14767
CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14768
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14769
ResultTy =
14770
CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14771
break;
14772
case BO_SubAssign:
14773
ConvertHalfVec = true;
14774
CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14775
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14776
ResultTy =
14777
CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14778
break;
14779
case BO_ShlAssign:
14780
case BO_ShrAssign:
14781
CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14782
CompLHSTy = CompResultTy;
14783
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14784
ResultTy =
14785
CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14786
break;
14787
case BO_AndAssign:
14788
case BO_OrAssign: // fallthrough
14789
DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14790
[[fallthrough]];
14791
case BO_XorAssign:
14792
CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14793
CompLHSTy = CompResultTy;
14794
if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14795
ResultTy =
14796
CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14797
break;
14798
case BO_Comma:
14799
ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14800
if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14801
VK = RHS.get()->getValueKind();
14802
OK = RHS.get()->getObjectKind();
14803
}
14804
break;
14805
}
14806
if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14807
return ExprError();
14808
14809
// Some of the binary operations require promoting operands of half vector to
14810
// float vectors and truncating the result back to half vector. For now, we do
14811
// this only when HalfArgsAndReturn is set (that is, when the target is arm or
14812
// arm64).
14813
assert(
14814
(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14815
isVector(LHS.get()->getType(), Context.HalfTy)) &&
14816
"both sides are half vectors or neither sides are");
14817
ConvertHalfVec =
14818
needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14819
14820
// Check for array bounds violations for both sides of the BinaryOperator
14821
CheckArrayAccess(LHS.get());
14822
CheckArrayAccess(RHS.get());
14823
14824
if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14825
NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14826
&Context.Idents.get("object_setClass"),
14827
SourceLocation(), LookupOrdinaryName);
14828
if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14829
SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14830
Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14831
<< FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14832
"object_setClass(")
14833
<< FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14834
",")
14835
<< FixItHint::CreateInsertion(RHSLocEnd, ")");
14836
}
14837
else
14838
Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14839
}
14840
else if (const ObjCIvarRefExpr *OIRE =
14841
dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14842
DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14843
14844
// Opc is not a compound assignment if CompResultTy is null.
14845
if (CompResultTy.isNull()) {
14846
if (ConvertHalfVec)
14847
return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14848
OpLoc, CurFPFeatureOverrides());
14849
return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14850
VK, OK, OpLoc, CurFPFeatureOverrides());
14851
}
14852
14853
// Handle compound assignments.
14854
if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14855
OK_ObjCProperty) {
14856
VK = VK_LValue;
14857
OK = LHS.get()->getObjectKind();
14858
}
14859
14860
// The LHS is not converted to the result type for fixed-point compound
14861
// assignment as the common type is computed on demand. Reset the CompLHSTy
14862
// to the LHS type we would have gotten after unary conversions.
14863
if (CompResultTy->isFixedPointType())
14864
CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14865
14866
if (ConvertHalfVec)
14867
return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14868
OpLoc, CurFPFeatureOverrides());
14869
14870
return CompoundAssignOperator::Create(
14871
Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14872
CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14873
}
14874
14875
/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14876
/// operators are mixed in a way that suggests that the programmer forgot that
14877
/// comparison operators have higher precedence. The most typical example of
14878
/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14879
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14880
SourceLocation OpLoc, Expr *LHSExpr,
14881
Expr *RHSExpr) {
14882
BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14883
BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14884
14885
// Check that one of the sides is a comparison operator and the other isn't.
14886
bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14887
bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14888
if (isLeftComp == isRightComp)
14889
return;
14890
14891
// Bitwise operations are sometimes used as eager logical ops.
14892
// Don't diagnose this.
14893
bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14894
bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14895
if (isLeftBitwise || isRightBitwise)
14896
return;
14897
14898
SourceRange DiagRange = isLeftComp
14899
? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14900
: SourceRange(OpLoc, RHSExpr->getEndLoc());
14901
StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14902
SourceRange ParensRange =
14903
isLeftComp
14904
? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14905
: SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14906
14907
Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14908
<< DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14909
SuggestParentheses(Self, OpLoc,
14910
Self.PDiag(diag::note_precedence_silence) << OpStr,
14911
(isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14912
SuggestParentheses(Self, OpLoc,
14913
Self.PDiag(diag::note_precedence_bitwise_first)
14914
<< BinaryOperator::getOpcodeStr(Opc),
14915
ParensRange);
14916
}
14917
14918
/// It accepts a '&&' expr that is inside a '||' one.
14919
/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14920
/// in parentheses.
14921
static void
14922
EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14923
BinaryOperator *Bop) {
14924
assert(Bop->getOpcode() == BO_LAnd);
14925
Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14926
<< Bop->getSourceRange() << OpLoc;
14927
SuggestParentheses(Self, Bop->getOperatorLoc(),
14928
Self.PDiag(diag::note_precedence_silence)
14929
<< Bop->getOpcodeStr(),
14930
Bop->getSourceRange());
14931
}
14932
14933
/// Look for '&&' in the left hand of a '||' expr.
14934
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14935
Expr *LHSExpr, Expr *RHSExpr) {
14936
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14937
if (Bop->getOpcode() == BO_LAnd) {
14938
// If it's "string_literal && a || b" don't warn since the precedence
14939
// doesn't matter.
14940
if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
14941
return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14942
} else if (Bop->getOpcode() == BO_LOr) {
14943
if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14944
// If it's "a || b && string_literal || c" we didn't warn earlier for
14945
// "a || b && string_literal", but warn now.
14946
if (RBop->getOpcode() == BO_LAnd &&
14947
isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
14948
return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14949
}
14950
}
14951
}
14952
}
14953
14954
/// Look for '&&' in the right hand of a '||' expr.
14955
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14956
Expr *LHSExpr, Expr *RHSExpr) {
14957
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14958
if (Bop->getOpcode() == BO_LAnd) {
14959
// If it's "a || b && string_literal" don't warn since the precedence
14960
// doesn't matter.
14961
if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
14962
return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14963
}
14964
}
14965
}
14966
14967
/// Look for bitwise op in the left or right hand of a bitwise op with
14968
/// lower precedence and emit a diagnostic together with a fixit hint that wraps
14969
/// the '&' expression in parentheses.
14970
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14971
SourceLocation OpLoc, Expr *SubExpr) {
14972
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14973
if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14974
S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14975
<< Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14976
<< Bop->getSourceRange() << OpLoc;
14977
SuggestParentheses(S, Bop->getOperatorLoc(),
14978
S.PDiag(diag::note_precedence_silence)
14979
<< Bop->getOpcodeStr(),
14980
Bop->getSourceRange());
14981
}
14982
}
14983
}
14984
14985
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14986
Expr *SubExpr, StringRef Shift) {
14987
if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14988
if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14989
StringRef Op = Bop->getOpcodeStr();
14990
S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14991
<< Bop->getSourceRange() << OpLoc << Shift << Op;
14992
SuggestParentheses(S, Bop->getOperatorLoc(),
14993
S.PDiag(diag::note_precedence_silence) << Op,
14994
Bop->getSourceRange());
14995
}
14996
}
14997
}
14998
14999
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15000
Expr *LHSExpr, Expr *RHSExpr) {
15001
CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15002
if (!OCE)
15003
return;
15004
15005
FunctionDecl *FD = OCE->getDirectCallee();
15006
if (!FD || !FD->isOverloadedOperator())
15007
return;
15008
15009
OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15010
if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15011
return;
15012
15013
S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15014
<< LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15015
<< (Kind == OO_LessLess);
15016
SuggestParentheses(S, OCE->getOperatorLoc(),
15017
S.PDiag(diag::note_precedence_silence)
15018
<< (Kind == OO_LessLess ? "<<" : ">>"),
15019
OCE->getSourceRange());
15020
SuggestParentheses(
15021
S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15022
SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15023
}
15024
15025
/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15026
/// precedence.
15027
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15028
SourceLocation OpLoc, Expr *LHSExpr,
15029
Expr *RHSExpr){
15030
// Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15031
if (BinaryOperator::isBitwiseOp(Opc))
15032
DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15033
15034
// Diagnose "arg1 & arg2 | arg3"
15035
if ((Opc == BO_Or || Opc == BO_Xor) &&
15036
!OpLoc.isMacroID()/* Don't warn in macros. */) {
15037
DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15038
DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15039
}
15040
15041
// Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15042
// We don't warn for 'assert(a || b && "bad")' since this is safe.
15043
if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15044
DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15045
DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15046
}
15047
15048
if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15049
|| Opc == BO_Shr) {
15050
StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15051
DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15052
DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15053
}
15054
15055
// Warn on overloaded shift operators and comparisons, such as:
15056
// cout << 5 == 4;
15057
if (BinaryOperator::isComparisonOp(Opc))
15058
DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15059
}
15060
15061
ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15062
tok::TokenKind Kind,
15063
Expr *LHSExpr, Expr *RHSExpr) {
15064
BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15065
assert(LHSExpr && "ActOnBinOp(): missing left expression");
15066
assert(RHSExpr && "ActOnBinOp(): missing right expression");
15067
15068
// Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15069
DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15070
15071
return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15072
}
15073
15074
void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15075
UnresolvedSetImpl &Functions) {
15076
OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15077
if (OverOp != OO_None && OverOp != OO_Equal)
15078
LookupOverloadedOperatorName(OverOp, S, Functions);
15079
15080
// In C++20 onwards, we may have a second operator to look up.
15081
if (getLangOpts().CPlusPlus20) {
15082
if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15083
LookupOverloadedOperatorName(ExtraOp, S, Functions);
15084
}
15085
}
15086
15087
/// Build an overloaded binary operator expression in the given scope.
15088
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15089
BinaryOperatorKind Opc,
15090
Expr *LHS, Expr *RHS) {
15091
switch (Opc) {
15092
case BO_Assign:
15093
// In the non-overloaded case, we warn about self-assignment (x = x) for
15094
// both simple assignment and certain compound assignments where algebra
15095
// tells us the operation yields a constant result. When the operator is
15096
// overloaded, we can't do the latter because we don't want to assume that
15097
// those algebraic identities still apply; for example, a path-building
15098
// library might use operator/= to append paths. But it's still reasonable
15099
// to assume that simple assignment is just moving/copying values around
15100
// and so self-assignment is likely a bug.
15101
DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15102
[[fallthrough]];
15103
case BO_DivAssign:
15104
case BO_RemAssign:
15105
case BO_SubAssign:
15106
case BO_AndAssign:
15107
case BO_OrAssign:
15108
case BO_XorAssign:
15109
CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15110
break;
15111
default:
15112
break;
15113
}
15114
15115
// Find all of the overloaded operators visible from this point.
15116
UnresolvedSet<16> Functions;
15117
S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15118
15119
// Build the (potentially-overloaded, potentially-dependent)
15120
// binary operation.
15121
return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15122
}
15123
15124
ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15125
BinaryOperatorKind Opc,
15126
Expr *LHSExpr, Expr *RHSExpr) {
15127
ExprResult LHS, RHS;
15128
std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15129
if (!LHS.isUsable() || !RHS.isUsable())
15130
return ExprError();
15131
LHSExpr = LHS.get();
15132
RHSExpr = RHS.get();
15133
15134
// We want to end up calling one of SemaPseudoObject::checkAssignment
15135
// (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15136
// both expressions are overloadable or either is type-dependent),
15137
// or CreateBuiltinBinOp (in any other case). We also want to get
15138
// any placeholder types out of the way.
15139
15140
// Handle pseudo-objects in the LHS.
15141
if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15142
// Assignments with a pseudo-object l-value need special analysis.
15143
if (pty->getKind() == BuiltinType::PseudoObject &&
15144
BinaryOperator::isAssignmentOp(Opc))
15145
return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15146
15147
// Don't resolve overloads if the other type is overloadable.
15148
if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15149
// We can't actually test that if we still have a placeholder,
15150
// though. Fortunately, none of the exceptions we see in that
15151
// code below are valid when the LHS is an overload set. Note
15152
// that an overload set can be dependently-typed, but it never
15153
// instantiates to having an overloadable type.
15154
ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15155
if (resolvedRHS.isInvalid()) return ExprError();
15156
RHSExpr = resolvedRHS.get();
15157
15158
if (RHSExpr->isTypeDependent() ||
15159
RHSExpr->getType()->isOverloadableType())
15160
return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15161
}
15162
15163
// If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15164
// template, diagnose the missing 'template' keyword instead of diagnosing
15165
// an invalid use of a bound member function.
15166
//
15167
// Note that "A::x < b" might be valid if 'b' has an overloadable type due
15168
// to C++1z [over.over]/1.4, but we already checked for that case above.
15169
if (Opc == BO_LT && inTemplateInstantiation() &&
15170
(pty->getKind() == BuiltinType::BoundMember ||
15171
pty->getKind() == BuiltinType::Overload)) {
15172
auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15173
if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15174
llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15175
return isa<FunctionTemplateDecl>(ND);
15176
})) {
15177
Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15178
: OE->getNameLoc(),
15179
diag::err_template_kw_missing)
15180
<< OE->getName().getAsString() << "";
15181
return ExprError();
15182
}
15183
}
15184
15185
ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15186
if (LHS.isInvalid()) return ExprError();
15187
LHSExpr = LHS.get();
15188
}
15189
15190
// Handle pseudo-objects in the RHS.
15191
if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15192
// An overload in the RHS can potentially be resolved by the type
15193
// being assigned to.
15194
if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15195
if (getLangOpts().CPlusPlus &&
15196
(LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15197
LHSExpr->getType()->isOverloadableType()))
15198
return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15199
15200
return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15201
}
15202
15203
// Don't resolve overloads if the other type is overloadable.
15204
if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15205
LHSExpr->getType()->isOverloadableType())
15206
return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15207
15208
ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15209
if (!resolvedRHS.isUsable()) return ExprError();
15210
RHSExpr = resolvedRHS.get();
15211
}
15212
15213
if (getLangOpts().CPlusPlus) {
15214
// Otherwise, build an overloaded op if either expression is type-dependent
15215
// or has an overloadable type.
15216
if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15217
LHSExpr->getType()->isOverloadableType() ||
15218
RHSExpr->getType()->isOverloadableType())
15219
return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15220
}
15221
15222
if (getLangOpts().RecoveryAST &&
15223
(LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15224
assert(!getLangOpts().CPlusPlus);
15225
assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15226
"Should only occur in error-recovery path.");
15227
if (BinaryOperator::isCompoundAssignmentOp(Opc))
15228
// C [6.15.16] p3:
15229
// An assignment expression has the value of the left operand after the
15230
// assignment, but is not an lvalue.
15231
return CompoundAssignOperator::Create(
15232
Context, LHSExpr, RHSExpr, Opc,
15233
LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15234
OpLoc, CurFPFeatureOverrides());
15235
QualType ResultType;
15236
switch (Opc) {
15237
case BO_Assign:
15238
ResultType = LHSExpr->getType().getUnqualifiedType();
15239
break;
15240
case BO_LT:
15241
case BO_GT:
15242
case BO_LE:
15243
case BO_GE:
15244
case BO_EQ:
15245
case BO_NE:
15246
case BO_LAnd:
15247
case BO_LOr:
15248
// These operators have a fixed result type regardless of operands.
15249
ResultType = Context.IntTy;
15250
break;
15251
case BO_Comma:
15252
ResultType = RHSExpr->getType();
15253
break;
15254
default:
15255
ResultType = Context.DependentTy;
15256
break;
15257
}
15258
return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15259
VK_PRValue, OK_Ordinary, OpLoc,
15260
CurFPFeatureOverrides());
15261
}
15262
15263
// Build a built-in binary operation.
15264
return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15265
}
15266
15267
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15268
if (T.isNull() || T->isDependentType())
15269
return false;
15270
15271
if (!Ctx.isPromotableIntegerType(T))
15272
return true;
15273
15274
return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15275
}
15276
15277
ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15278
UnaryOperatorKind Opc, Expr *InputExpr,
15279
bool IsAfterAmp) {
15280
ExprResult Input = InputExpr;
15281
ExprValueKind VK = VK_PRValue;
15282
ExprObjectKind OK = OK_Ordinary;
15283
QualType resultType;
15284
bool CanOverflow = false;
15285
15286
bool ConvertHalfVec = false;
15287
if (getLangOpts().OpenCL) {
15288
QualType Ty = InputExpr->getType();
15289
// The only legal unary operation for atomics is '&'.
15290
if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15291
// OpenCL special types - image, sampler, pipe, and blocks are to be used
15292
// only with a builtin functions and therefore should be disallowed here.
15293
(Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15294
|| Ty->isBlockPointerType())) {
15295
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15296
<< InputExpr->getType()
15297
<< Input.get()->getSourceRange());
15298
}
15299
}
15300
15301
if (getLangOpts().HLSL && OpLoc.isValid()) {
15302
if (Opc == UO_AddrOf)
15303
return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15304
if (Opc == UO_Deref)
15305
return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15306
}
15307
15308
if (InputExpr->isTypeDependent() &&
15309
InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15310
resultType = Context.DependentTy;
15311
} else {
15312
switch (Opc) {
15313
case UO_PreInc:
15314
case UO_PreDec:
15315
case UO_PostInc:
15316
case UO_PostDec:
15317
resultType =
15318
CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15319
Opc == UO_PreInc || Opc == UO_PostInc,
15320
Opc == UO_PreInc || Opc == UO_PreDec);
15321
CanOverflow = isOverflowingIntegerType(Context, resultType);
15322
break;
15323
case UO_AddrOf:
15324
resultType = CheckAddressOfOperand(Input, OpLoc);
15325
CheckAddressOfNoDeref(InputExpr);
15326
RecordModifiableNonNullParam(*this, InputExpr);
15327
break;
15328
case UO_Deref: {
15329
Input = DefaultFunctionArrayLvalueConversion(Input.get());
15330
if (Input.isInvalid())
15331
return ExprError();
15332
resultType =
15333
CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15334
break;
15335
}
15336
case UO_Plus:
15337
case UO_Minus:
15338
CanOverflow = Opc == UO_Minus &&
15339
isOverflowingIntegerType(Context, Input.get()->getType());
15340
Input = UsualUnaryConversions(Input.get());
15341
if (Input.isInvalid())
15342
return ExprError();
15343
// Unary plus and minus require promoting an operand of half vector to a
15344
// float vector and truncating the result back to a half vector. For now,
15345
// we do this only when HalfArgsAndReturns is set (that is, when the
15346
// target is arm or arm64).
15347
ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15348
15349
// If the operand is a half vector, promote it to a float vector.
15350
if (ConvertHalfVec)
15351
Input = convertVector(Input.get(), Context.FloatTy, *this);
15352
resultType = Input.get()->getType();
15353
if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15354
break;
15355
else if (resultType->isVectorType() &&
15356
// The z vector extensions don't allow + or - with bool vectors.
15357
(!Context.getLangOpts().ZVector ||
15358
resultType->castAs<VectorType>()->getVectorKind() !=
15359
VectorKind::AltiVecBool))
15360
break;
15361
else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15362
break;
15363
else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15364
Opc == UO_Plus && resultType->isPointerType())
15365
break;
15366
15367
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15368
<< resultType << Input.get()->getSourceRange());
15369
15370
case UO_Not: // bitwise complement
15371
Input = UsualUnaryConversions(Input.get());
15372
if (Input.isInvalid())
15373
return ExprError();
15374
resultType = Input.get()->getType();
15375
// C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15376
if (resultType->isComplexType() || resultType->isComplexIntegerType())
15377
// C99 does not support '~' for complex conjugation.
15378
Diag(OpLoc, diag::ext_integer_complement_complex)
15379
<< resultType << Input.get()->getSourceRange();
15380
else if (resultType->hasIntegerRepresentation())
15381
break;
15382
else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15383
// OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15384
// on vector float types.
15385
QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15386
if (!T->isIntegerType())
15387
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15388
<< resultType << Input.get()->getSourceRange());
15389
} else {
15390
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15391
<< resultType << Input.get()->getSourceRange());
15392
}
15393
break;
15394
15395
case UO_LNot: // logical negation
15396
// Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15397
Input = DefaultFunctionArrayLvalueConversion(Input.get());
15398
if (Input.isInvalid())
15399
return ExprError();
15400
resultType = Input.get()->getType();
15401
15402
// Though we still have to promote half FP to float...
15403
if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15404
Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15405
.get();
15406
resultType = Context.FloatTy;
15407
}
15408
15409
// WebAsembly tables can't be used in unary expressions.
15410
if (resultType->isPointerType() &&
15411
resultType->getPointeeType().isWebAssemblyReferenceType()) {
15412
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15413
<< resultType << Input.get()->getSourceRange());
15414
}
15415
15416
if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15417
// C99 6.5.3.3p1: ok, fallthrough;
15418
if (Context.getLangOpts().CPlusPlus) {
15419
// C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15420
// operand contextually converted to bool.
15421
Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15422
ScalarTypeToBooleanCastKind(resultType));
15423
} else if (Context.getLangOpts().OpenCL &&
15424
Context.getLangOpts().OpenCLVersion < 120) {
15425
// OpenCL v1.1 6.3.h: The logical operator not (!) does not
15426
// operate on scalar float types.
15427
if (!resultType->isIntegerType() && !resultType->isPointerType())
15428
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15429
<< resultType << Input.get()->getSourceRange());
15430
}
15431
} else if (resultType->isExtVectorType()) {
15432
if (Context.getLangOpts().OpenCL &&
15433
Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15434
// OpenCL v1.1 6.3.h: The logical operator not (!) does not
15435
// operate on vector float types.
15436
QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15437
if (!T->isIntegerType())
15438
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15439
<< resultType << Input.get()->getSourceRange());
15440
}
15441
// Vector logical not returns the signed variant of the operand type.
15442
resultType = GetSignedVectorType(resultType);
15443
break;
15444
} else if (Context.getLangOpts().CPlusPlus &&
15445
resultType->isVectorType()) {
15446
const VectorType *VTy = resultType->castAs<VectorType>();
15447
if (VTy->getVectorKind() != VectorKind::Generic)
15448
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15449
<< resultType << Input.get()->getSourceRange());
15450
15451
// Vector logical not returns the signed variant of the operand type.
15452
resultType = GetSignedVectorType(resultType);
15453
break;
15454
} else {
15455
return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15456
<< resultType << Input.get()->getSourceRange());
15457
}
15458
15459
// LNot always has type int. C99 6.5.3.3p5.
15460
// In C++, it's bool. C++ 5.3.1p8
15461
resultType = Context.getLogicalOperationType();
15462
break;
15463
case UO_Real:
15464
case UO_Imag:
15465
resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15466
// _Real maps ordinary l-values into ordinary l-values. _Imag maps
15467
// ordinary complex l-values to ordinary l-values and all other values to
15468
// r-values.
15469
if (Input.isInvalid())
15470
return ExprError();
15471
if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15472
if (Input.get()->isGLValue() &&
15473
Input.get()->getObjectKind() == OK_Ordinary)
15474
VK = Input.get()->getValueKind();
15475
} else if (!getLangOpts().CPlusPlus) {
15476
// In C, a volatile scalar is read by __imag. In C++, it is not.
15477
Input = DefaultLvalueConversion(Input.get());
15478
}
15479
break;
15480
case UO_Extension:
15481
resultType = Input.get()->getType();
15482
VK = Input.get()->getValueKind();
15483
OK = Input.get()->getObjectKind();
15484
break;
15485
case UO_Coawait:
15486
// It's unnecessary to represent the pass-through operator co_await in the
15487
// AST; just return the input expression instead.
15488
assert(!Input.get()->getType()->isDependentType() &&
15489
"the co_await expression must be non-dependant before "
15490
"building operator co_await");
15491
return Input;
15492
}
15493
}
15494
if (resultType.isNull() || Input.isInvalid())
15495
return ExprError();
15496
15497
// Check for array bounds violations in the operand of the UnaryOperator,
15498
// except for the '*' and '&' operators that have to be handled specially
15499
// by CheckArrayAccess (as there are special cases like &array[arraysize]
15500
// that are explicitly defined as valid by the standard).
15501
if (Opc != UO_AddrOf && Opc != UO_Deref)
15502
CheckArrayAccess(Input.get());
15503
15504
auto *UO =
15505
UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15506
OpLoc, CanOverflow, CurFPFeatureOverrides());
15507
15508
if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15509
!isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15510
!isUnevaluatedContext())
15511
ExprEvalContexts.back().PossibleDerefs.insert(UO);
15512
15513
// Convert the result back to a half vector.
15514
if (ConvertHalfVec)
15515
return convertVector(UO, Context.HalfTy, *this);
15516
return UO;
15517
}
15518
15519
bool Sema::isQualifiedMemberAccess(Expr *E) {
15520
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15521
if (!DRE->getQualifier())
15522
return false;
15523
15524
ValueDecl *VD = DRE->getDecl();
15525
if (!VD->isCXXClassMember())
15526
return false;
15527
15528
if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15529
return true;
15530
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15531
return Method->isImplicitObjectMemberFunction();
15532
15533
return false;
15534
}
15535
15536
if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15537
if (!ULE->getQualifier())
15538
return false;
15539
15540
for (NamedDecl *D : ULE->decls()) {
15541
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15542
if (Method->isImplicitObjectMemberFunction())
15543
return true;
15544
} else {
15545
// Overload set does not contain methods.
15546
break;
15547
}
15548
}
15549
15550
return false;
15551
}
15552
15553
return false;
15554
}
15555
15556
ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15557
UnaryOperatorKind Opc, Expr *Input,
15558
bool IsAfterAmp) {
15559
// First things first: handle placeholders so that the
15560
// overloaded-operator check considers the right type.
15561
if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15562
// Increment and decrement of pseudo-object references.
15563
if (pty->getKind() == BuiltinType::PseudoObject &&
15564
UnaryOperator::isIncrementDecrementOp(Opc))
15565
return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
15566
15567
// extension is always a builtin operator.
15568
if (Opc == UO_Extension)
15569
return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15570
15571
// & gets special logic for several kinds of placeholder.
15572
// The builtin code knows what to do.
15573
if (Opc == UO_AddrOf &&
15574
(pty->getKind() == BuiltinType::Overload ||
15575
pty->getKind() == BuiltinType::UnknownAny ||
15576
pty->getKind() == BuiltinType::BoundMember))
15577
return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15578
15579
// Anything else needs to be handled now.
15580
ExprResult Result = CheckPlaceholderExpr(Input);
15581
if (Result.isInvalid()) return ExprError();
15582
Input = Result.get();
15583
}
15584
15585
if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15586
UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15587
!(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15588
// Find all of the overloaded operators visible from this point.
15589
UnresolvedSet<16> Functions;
15590
OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15591
if (S && OverOp != OO_None)
15592
LookupOverloadedOperatorName(OverOp, S, Functions);
15593
15594
return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15595
}
15596
15597
return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15598
}
15599
15600
ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
15601
Expr *Input, bool IsAfterAmp) {
15602
return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15603
IsAfterAmp);
15604
}
15605
15606
ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15607
LabelDecl *TheDecl) {
15608
TheDecl->markUsed(Context);
15609
// Create the AST node. The address of a label always has type 'void*'.
15610
auto *Res = new (Context) AddrLabelExpr(
15611
OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15612
15613
if (getCurFunction())
15614
getCurFunction()->AddrLabels.push_back(Res);
15615
15616
return Res;
15617
}
15618
15619
void Sema::ActOnStartStmtExpr() {
15620
PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15621
// Make sure we diagnose jumping into a statement expression.
15622
setFunctionHasBranchProtectedScope();
15623
}
15624
15625
void Sema::ActOnStmtExprError() {
15626
// Note that function is also called by TreeTransform when leaving a
15627
// StmtExpr scope without rebuilding anything.
15628
15629
DiscardCleanupsInEvaluationContext();
15630
PopExpressionEvaluationContext();
15631
}
15632
15633
ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15634
SourceLocation RPLoc) {
15635
return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15636
}
15637
15638
ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15639
SourceLocation RPLoc, unsigned TemplateDepth) {
15640
assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15641
CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15642
15643
if (hasAnyUnrecoverableErrorsInThisFunction())
15644
DiscardCleanupsInEvaluationContext();
15645
assert(!Cleanup.exprNeedsCleanups() &&
15646
"cleanups within StmtExpr not correctly bound!");
15647
PopExpressionEvaluationContext();
15648
15649
// FIXME: there are a variety of strange constraints to enforce here, for
15650
// example, it is not possible to goto into a stmt expression apparently.
15651
// More semantic analysis is needed.
15652
15653
// If there are sub-stmts in the compound stmt, take the type of the last one
15654
// as the type of the stmtexpr.
15655
QualType Ty = Context.VoidTy;
15656
bool StmtExprMayBindToTemp = false;
15657
if (!Compound->body_empty()) {
15658
// For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15659
if (const auto *LastStmt =
15660
dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15661
if (const Expr *Value = LastStmt->getExprStmt()) {
15662
StmtExprMayBindToTemp = true;
15663
Ty = Value->getType();
15664
}
15665
}
15666
}
15667
15668
// FIXME: Check that expression type is complete/non-abstract; statement
15669
// expressions are not lvalues.
15670
Expr *ResStmtExpr =
15671
new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15672
if (StmtExprMayBindToTemp)
15673
return MaybeBindToTemporary(ResStmtExpr);
15674
return ResStmtExpr;
15675
}
15676
15677
ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15678
if (ER.isInvalid())
15679
return ExprError();
15680
15681
// Do function/array conversion on the last expression, but not
15682
// lvalue-to-rvalue. However, initialize an unqualified type.
15683
ER = DefaultFunctionArrayConversion(ER.get());
15684
if (ER.isInvalid())
15685
return ExprError();
15686
Expr *E = ER.get();
15687
15688
if (E->isTypeDependent())
15689
return E;
15690
15691
// In ARC, if the final expression ends in a consume, splice
15692
// the consume out and bind it later. In the alternate case
15693
// (when dealing with a retainable type), the result
15694
// initialization will create a produce. In both cases the
15695
// result will be +1, and we'll need to balance that out with
15696
// a bind.
15697
auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15698
if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15699
return Cast->getSubExpr();
15700
15701
// FIXME: Provide a better location for the initialization.
15702
return PerformCopyInitialization(
15703
InitializedEntity::InitializeStmtExprResult(
15704
E->getBeginLoc(), E->getType().getUnqualifiedType()),
15705
SourceLocation(), E);
15706
}
15707
15708
ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15709
TypeSourceInfo *TInfo,
15710
ArrayRef<OffsetOfComponent> Components,
15711
SourceLocation RParenLoc) {
15712
QualType ArgTy = TInfo->getType();
15713
bool Dependent = ArgTy->isDependentType();
15714
SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15715
15716
// We must have at least one component that refers to the type, and the first
15717
// one is known to be a field designator. Verify that the ArgTy represents
15718
// a struct/union/class.
15719
if (!Dependent && !ArgTy->isRecordType())
15720
return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15721
<< ArgTy << TypeRange);
15722
15723
// Type must be complete per C99 7.17p3 because a declaring a variable
15724
// with an incomplete type would be ill-formed.
15725
if (!Dependent
15726
&& RequireCompleteType(BuiltinLoc, ArgTy,
15727
diag::err_offsetof_incomplete_type, TypeRange))
15728
return ExprError();
15729
15730
bool DidWarnAboutNonPOD = false;
15731
QualType CurrentType = ArgTy;
15732
SmallVector<OffsetOfNode, 4> Comps;
15733
SmallVector<Expr*, 4> Exprs;
15734
for (const OffsetOfComponent &OC : Components) {
15735
if (OC.isBrackets) {
15736
// Offset of an array sub-field. TODO: Should we allow vector elements?
15737
if (!CurrentType->isDependentType()) {
15738
const ArrayType *AT = Context.getAsArrayType(CurrentType);
15739
if(!AT)
15740
return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15741
<< CurrentType);
15742
CurrentType = AT->getElementType();
15743
} else
15744
CurrentType = Context.DependentTy;
15745
15746
ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15747
if (IdxRval.isInvalid())
15748
return ExprError();
15749
Expr *Idx = IdxRval.get();
15750
15751
// The expression must be an integral expression.
15752
// FIXME: An integral constant expression?
15753
if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15754
!Idx->getType()->isIntegerType())
15755
return ExprError(
15756
Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15757
<< Idx->getSourceRange());
15758
15759
// Record this array index.
15760
Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15761
Exprs.push_back(Idx);
15762
continue;
15763
}
15764
15765
// Offset of a field.
15766
if (CurrentType->isDependentType()) {
15767
// We have the offset of a field, but we can't look into the dependent
15768
// type. Just record the identifier of the field.
15769
Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15770
CurrentType = Context.DependentTy;
15771
continue;
15772
}
15773
15774
// We need to have a complete type to look into.
15775
if (RequireCompleteType(OC.LocStart, CurrentType,
15776
diag::err_offsetof_incomplete_type))
15777
return ExprError();
15778
15779
// Look for the designated field.
15780
const RecordType *RC = CurrentType->getAs<RecordType>();
15781
if (!RC)
15782
return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15783
<< CurrentType);
15784
RecordDecl *RD = RC->getDecl();
15785
15786
// C++ [lib.support.types]p5:
15787
// The macro offsetof accepts a restricted set of type arguments in this
15788
// International Standard. type shall be a POD structure or a POD union
15789
// (clause 9).
15790
// C++11 [support.types]p4:
15791
// If type is not a standard-layout class (Clause 9), the results are
15792
// undefined.
15793
if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15794
bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15795
unsigned DiagID =
15796
LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15797
: diag::ext_offsetof_non_pod_type;
15798
15799
if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
15800
Diag(BuiltinLoc, DiagID)
15801
<< SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
15802
DidWarnAboutNonPOD = true;
15803
}
15804
}
15805
15806
// Look for the field.
15807
LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15808
LookupQualifiedName(R, RD);
15809
FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15810
IndirectFieldDecl *IndirectMemberDecl = nullptr;
15811
if (!MemberDecl) {
15812
if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15813
MemberDecl = IndirectMemberDecl->getAnonField();
15814
}
15815
15816
if (!MemberDecl) {
15817
// Lookup could be ambiguous when looking up a placeholder variable
15818
// __builtin_offsetof(S, _).
15819
// In that case we would already have emitted a diagnostic
15820
if (!R.isAmbiguous())
15821
Diag(BuiltinLoc, diag::err_no_member)
15822
<< OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
15823
return ExprError();
15824
}
15825
15826
// C99 7.17p3:
15827
// (If the specified member is a bit-field, the behavior is undefined.)
15828
//
15829
// We diagnose this as an error.
15830
if (MemberDecl->isBitField()) {
15831
Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15832
<< MemberDecl->getDeclName()
15833
<< SourceRange(BuiltinLoc, RParenLoc);
15834
Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15835
return ExprError();
15836
}
15837
15838
RecordDecl *Parent = MemberDecl->getParent();
15839
if (IndirectMemberDecl)
15840
Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15841
15842
// If the member was found in a base class, introduce OffsetOfNodes for
15843
// the base class indirections.
15844
CXXBasePaths Paths;
15845
if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15846
Paths)) {
15847
if (Paths.getDetectedVirtual()) {
15848
Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15849
<< MemberDecl->getDeclName()
15850
<< SourceRange(BuiltinLoc, RParenLoc);
15851
return ExprError();
15852
}
15853
15854
CXXBasePath &Path = Paths.front();
15855
for (const CXXBasePathElement &B : Path)
15856
Comps.push_back(OffsetOfNode(B.Base));
15857
}
15858
15859
if (IndirectMemberDecl) {
15860
for (auto *FI : IndirectMemberDecl->chain()) {
15861
assert(isa<FieldDecl>(FI));
15862
Comps.push_back(OffsetOfNode(OC.LocStart,
15863
cast<FieldDecl>(FI), OC.LocEnd));
15864
}
15865
} else
15866
Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15867
15868
CurrentType = MemberDecl->getType().getNonReferenceType();
15869
}
15870
15871
return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15872
Comps, Exprs, RParenLoc);
15873
}
15874
15875
ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15876
SourceLocation BuiltinLoc,
15877
SourceLocation TypeLoc,
15878
ParsedType ParsedArgTy,
15879
ArrayRef<OffsetOfComponent> Components,
15880
SourceLocation RParenLoc) {
15881
15882
TypeSourceInfo *ArgTInfo;
15883
QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15884
if (ArgTy.isNull())
15885
return ExprError();
15886
15887
if (!ArgTInfo)
15888
ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15889
15890
return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15891
}
15892
15893
15894
ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15895
Expr *CondExpr,
15896
Expr *LHSExpr, Expr *RHSExpr,
15897
SourceLocation RPLoc) {
15898
assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15899
15900
ExprValueKind VK = VK_PRValue;
15901
ExprObjectKind OK = OK_Ordinary;
15902
QualType resType;
15903
bool CondIsTrue = false;
15904
if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15905
resType = Context.DependentTy;
15906
} else {
15907
// The conditional expression is required to be a constant expression.
15908
llvm::APSInt condEval(32);
15909
ExprResult CondICE = VerifyIntegerConstantExpression(
15910
CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15911
if (CondICE.isInvalid())
15912
return ExprError();
15913
CondExpr = CondICE.get();
15914
CondIsTrue = condEval.getZExtValue();
15915
15916
// If the condition is > zero, then the AST type is the same as the LHSExpr.
15917
Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15918
15919
resType = ActiveExpr->getType();
15920
VK = ActiveExpr->getValueKind();
15921
OK = ActiveExpr->getObjectKind();
15922
}
15923
15924
return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15925
resType, VK, OK, RPLoc, CondIsTrue);
15926
}
15927
15928
//===----------------------------------------------------------------------===//
15929
// Clang Extensions.
15930
//===----------------------------------------------------------------------===//
15931
15932
void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15933
BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15934
15935
if (LangOpts.CPlusPlus) {
15936
MangleNumberingContext *MCtx;
15937
Decl *ManglingContextDecl;
15938
std::tie(MCtx, ManglingContextDecl) =
15939
getCurrentMangleNumberContext(Block->getDeclContext());
15940
if (MCtx) {
15941
unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15942
Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15943
}
15944
}
15945
15946
PushBlockScope(CurScope, Block);
15947
CurContext->addDecl(Block);
15948
if (CurScope)
15949
PushDeclContext(CurScope, Block);
15950
else
15951
CurContext = Block;
15952
15953
getCurBlock()->HasImplicitReturnType = true;
15954
15955
// Enter a new evaluation context to insulate the block from any
15956
// cleanups from the enclosing full-expression.
15957
PushExpressionEvaluationContext(
15958
ExpressionEvaluationContext::PotentiallyEvaluated);
15959
}
15960
15961
void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15962
Scope *CurScope) {
15963
assert(ParamInfo.getIdentifier() == nullptr &&
15964
"block-id should have no identifier!");
15965
assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15966
BlockScopeInfo *CurBlock = getCurBlock();
15967
15968
TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
15969
QualType T = Sig->getType();
15970
15971
// FIXME: We should allow unexpanded parameter packs here, but that would,
15972
// in turn, make the block expression contain unexpanded parameter packs.
15973
if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15974
// Drop the parameters.
15975
FunctionProtoType::ExtProtoInfo EPI;
15976
EPI.HasTrailingReturn = false;
15977
EPI.TypeQuals.addConst();
15978
T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
15979
Sig = Context.getTrivialTypeSourceInfo(T);
15980
}
15981
15982
// GetTypeForDeclarator always produces a function type for a block
15983
// literal signature. Furthermore, it is always a FunctionProtoType
15984
// unless the function was written with a typedef.
15985
assert(T->isFunctionType() &&
15986
"GetTypeForDeclarator made a non-function block signature");
15987
15988
// Look for an explicit signature in that function type.
15989
FunctionProtoTypeLoc ExplicitSignature;
15990
15991
if ((ExplicitSignature = Sig->getTypeLoc()
15992
.getAsAdjusted<FunctionProtoTypeLoc>())) {
15993
15994
// Check whether that explicit signature was synthesized by
15995
// GetTypeForDeclarator. If so, don't save that as part of the
15996
// written signature.
15997
if (ExplicitSignature.getLocalRangeBegin() ==
15998
ExplicitSignature.getLocalRangeEnd()) {
15999
// This would be much cheaper if we stored TypeLocs instead of
16000
// TypeSourceInfos.
16001
TypeLoc Result = ExplicitSignature.getReturnLoc();
16002
unsigned Size = Result.getFullDataSize();
16003
Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16004
Sig->getTypeLoc().initializeFullCopy(Result, Size);
16005
16006
ExplicitSignature = FunctionProtoTypeLoc();
16007
}
16008
}
16009
16010
CurBlock->TheDecl->setSignatureAsWritten(Sig);
16011
CurBlock->FunctionType = T;
16012
16013
const auto *Fn = T->castAs<FunctionType>();
16014
QualType RetTy = Fn->getReturnType();
16015
bool isVariadic =
16016
(isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16017
16018
CurBlock->TheDecl->setIsVariadic(isVariadic);
16019
16020
// Context.DependentTy is used as a placeholder for a missing block
16021
// return type. TODO: what should we do with declarators like:
16022
// ^ * { ... }
16023
// If the answer is "apply template argument deduction"....
16024
if (RetTy != Context.DependentTy) {
16025
CurBlock->ReturnType = RetTy;
16026
CurBlock->TheDecl->setBlockMissingReturnType(false);
16027
CurBlock->HasImplicitReturnType = false;
16028
}
16029
16030
// Push block parameters from the declarator if we had them.
16031
SmallVector<ParmVarDecl*, 8> Params;
16032
if (ExplicitSignature) {
16033
for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16034
ParmVarDecl *Param = ExplicitSignature.getParam(I);
16035
if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16036
!Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16037
// Diagnose this as an extension in C17 and earlier.
16038
if (!getLangOpts().C23)
16039
Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16040
}
16041
Params.push_back(Param);
16042
}
16043
16044
// Fake up parameter variables if we have a typedef, like
16045
// ^ fntype { ... }
16046
} else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16047
for (const auto &I : Fn->param_types()) {
16048
ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16049
CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16050
Params.push_back(Param);
16051
}
16052
}
16053
16054
// Set the parameters on the block decl.
16055
if (!Params.empty()) {
16056
CurBlock->TheDecl->setParams(Params);
16057
CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16058
/*CheckParameterNames=*/false);
16059
}
16060
16061
// Finally we can process decl attributes.
16062
ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16063
16064
// Put the parameter variables in scope.
16065
for (auto *AI : CurBlock->TheDecl->parameters()) {
16066
AI->setOwningFunction(CurBlock->TheDecl);
16067
16068
// If this has an identifier, add it to the scope stack.
16069
if (AI->getIdentifier()) {
16070
CheckShadow(CurBlock->TheScope, AI);
16071
16072
PushOnScopeChains(AI, CurBlock->TheScope);
16073
}
16074
16075
if (AI->isInvalidDecl())
16076
CurBlock->TheDecl->setInvalidDecl();
16077
}
16078
}
16079
16080
void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16081
// Leave the expression-evaluation context.
16082
DiscardCleanupsInEvaluationContext();
16083
PopExpressionEvaluationContext();
16084
16085
// Pop off CurBlock, handle nested blocks.
16086
PopDeclContext();
16087
PopFunctionScopeInfo();
16088
}
16089
16090
ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16091
Stmt *Body, Scope *CurScope) {
16092
// If blocks are disabled, emit an error.
16093
if (!LangOpts.Blocks)
16094
Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16095
16096
// Leave the expression-evaluation context.
16097
if (hasAnyUnrecoverableErrorsInThisFunction())
16098
DiscardCleanupsInEvaluationContext();
16099
assert(!Cleanup.exprNeedsCleanups() &&
16100
"cleanups within block not correctly bound!");
16101
PopExpressionEvaluationContext();
16102
16103
BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16104
BlockDecl *BD = BSI->TheDecl;
16105
16106
if (BSI->HasImplicitReturnType)
16107
deduceClosureReturnType(*BSI);
16108
16109
QualType RetTy = Context.VoidTy;
16110
if (!BSI->ReturnType.isNull())
16111
RetTy = BSI->ReturnType;
16112
16113
bool NoReturn = BD->hasAttr<NoReturnAttr>();
16114
QualType BlockTy;
16115
16116
// If the user wrote a function type in some form, try to use that.
16117
if (!BSI->FunctionType.isNull()) {
16118
const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16119
16120
FunctionType::ExtInfo Ext = FTy->getExtInfo();
16121
if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16122
16123
// Turn protoless block types into nullary block types.
16124
if (isa<FunctionNoProtoType>(FTy)) {
16125
FunctionProtoType::ExtProtoInfo EPI;
16126
EPI.ExtInfo = Ext;
16127
BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16128
16129
// Otherwise, if we don't need to change anything about the function type,
16130
// preserve its sugar structure.
16131
} else if (FTy->getReturnType() == RetTy &&
16132
(!NoReturn || FTy->getNoReturnAttr())) {
16133
BlockTy = BSI->FunctionType;
16134
16135
// Otherwise, make the minimal modifications to the function type.
16136
} else {
16137
const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16138
FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16139
EPI.TypeQuals = Qualifiers();
16140
EPI.ExtInfo = Ext;
16141
BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16142
}
16143
16144
// If we don't have a function type, just build one from nothing.
16145
} else {
16146
FunctionProtoType::ExtProtoInfo EPI;
16147
EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16148
BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16149
}
16150
16151
DiagnoseUnusedParameters(BD->parameters());
16152
BlockTy = Context.getBlockPointerType(BlockTy);
16153
16154
// If needed, diagnose invalid gotos and switches in the block.
16155
if (getCurFunction()->NeedsScopeChecking() &&
16156
!PP.isCodeCompletionEnabled())
16157
DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16158
16159
BD->setBody(cast<CompoundStmt>(Body));
16160
16161
if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16162
DiagnoseUnguardedAvailabilityViolations(BD);
16163
16164
// Try to apply the named return value optimization. We have to check again
16165
// if we can do this, though, because blocks keep return statements around
16166
// to deduce an implicit return type.
16167
if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16168
!BD->isDependentContext())
16169
computeNRVO(Body, BSI);
16170
16171
if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16172
RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16173
checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16174
NTCUK_Destruct|NTCUK_Copy);
16175
16176
PopDeclContext();
16177
16178
// Set the captured variables on the block.
16179
SmallVector<BlockDecl::Capture, 4> Captures;
16180
for (Capture &Cap : BSI->Captures) {
16181
if (Cap.isInvalid() || Cap.isThisCapture())
16182
continue;
16183
// Cap.getVariable() is always a VarDecl because
16184
// blocks cannot capture structured bindings or other ValueDecl kinds.
16185
auto *Var = cast<VarDecl>(Cap.getVariable());
16186
Expr *CopyExpr = nullptr;
16187
if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16188
if (const RecordType *Record =
16189
Cap.getCaptureType()->getAs<RecordType>()) {
16190
// The capture logic needs the destructor, so make sure we mark it.
16191
// Usually this is unnecessary because most local variables have
16192
// their destructors marked at declaration time, but parameters are
16193
// an exception because it's technically only the call site that
16194
// actually requires the destructor.
16195
if (isa<ParmVarDecl>(Var))
16196
FinalizeVarWithDestructor(Var, Record);
16197
16198
// Enter a separate potentially-evaluated context while building block
16199
// initializers to isolate their cleanups from those of the block
16200
// itself.
16201
// FIXME: Is this appropriate even when the block itself occurs in an
16202
// unevaluated operand?
16203
EnterExpressionEvaluationContext EvalContext(
16204
*this, ExpressionEvaluationContext::PotentiallyEvaluated);
16205
16206
SourceLocation Loc = Cap.getLocation();
16207
16208
ExprResult Result = BuildDeclarationNameExpr(
16209
CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16210
16211
// According to the blocks spec, the capture of a variable from
16212
// the stack requires a const copy constructor. This is not true
16213
// of the copy/move done to move a __block variable to the heap.
16214
if (!Result.isInvalid() &&
16215
!Result.get()->getType().isConstQualified()) {
16216
Result = ImpCastExprToType(Result.get(),
16217
Result.get()->getType().withConst(),
16218
CK_NoOp, VK_LValue);
16219
}
16220
16221
if (!Result.isInvalid()) {
16222
Result = PerformCopyInitialization(
16223
InitializedEntity::InitializeBlock(Var->getLocation(),
16224
Cap.getCaptureType()),
16225
Loc, Result.get());
16226
}
16227
16228
// Build a full-expression copy expression if initialization
16229
// succeeded and used a non-trivial constructor. Recover from
16230
// errors by pretending that the copy isn't necessary.
16231
if (!Result.isInvalid() &&
16232
!cast<CXXConstructExpr>(Result.get())->getConstructor()
16233
->isTrivial()) {
16234
Result = MaybeCreateExprWithCleanups(Result);
16235
CopyExpr = Result.get();
16236
}
16237
}
16238
}
16239
16240
BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16241
CopyExpr);
16242
Captures.push_back(NewCap);
16243
}
16244
BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16245
16246
// Pop the block scope now but keep it alive to the end of this function.
16247
AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16248
PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16249
16250
BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16251
16252
// If the block isn't obviously global, i.e. it captures anything at
16253
// all, then we need to do a few things in the surrounding context:
16254
if (Result->getBlockDecl()->hasCaptures()) {
16255
// First, this expression has a new cleanup object.
16256
ExprCleanupObjects.push_back(Result->getBlockDecl());
16257
Cleanup.setExprNeedsCleanups(true);
16258
16259
// It also gets a branch-protected scope if any of the captured
16260
// variables needs destruction.
16261
for (const auto &CI : Result->getBlockDecl()->captures()) {
16262
const VarDecl *var = CI.getVariable();
16263
if (var->getType().isDestructedType() != QualType::DK_none) {
16264
setFunctionHasBranchProtectedScope();
16265
break;
16266
}
16267
}
16268
}
16269
16270
if (getCurFunction())
16271
getCurFunction()->addBlock(BD);
16272
16273
if (BD->isInvalidDecl())
16274
return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16275
{Result}, Result->getType());
16276
return Result;
16277
}
16278
16279
ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16280
SourceLocation RPLoc) {
16281
TypeSourceInfo *TInfo;
16282
GetTypeFromParser(Ty, &TInfo);
16283
return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16284
}
16285
16286
ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16287
Expr *E, TypeSourceInfo *TInfo,
16288
SourceLocation RPLoc) {
16289
Expr *OrigExpr = E;
16290
bool IsMS = false;
16291
16292
// CUDA device code does not support varargs.
16293
if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16294
if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16295
CUDAFunctionTarget T = CUDA().IdentifyTarget(F);
16296
if (T == CUDAFunctionTarget::Global || T == CUDAFunctionTarget::Device ||
16297
T == CUDAFunctionTarget::HostDevice)
16298
return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16299
}
16300
}
16301
16302
// NVPTX does not support va_arg expression.
16303
if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16304
Context.getTargetInfo().getTriple().isNVPTX())
16305
targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16306
16307
// It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16308
// as Microsoft ABI on an actual Microsoft platform, where
16309
// __builtin_ms_va_list and __builtin_va_list are the same.)
16310
if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16311
Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16312
QualType MSVaListType = Context.getBuiltinMSVaListType();
16313
if (Context.hasSameType(MSVaListType, E->getType())) {
16314
if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16315
return ExprError();
16316
IsMS = true;
16317
}
16318
}
16319
16320
// Get the va_list type
16321
QualType VaListType = Context.getBuiltinVaListType();
16322
if (!IsMS) {
16323
if (VaListType->isArrayType()) {
16324
// Deal with implicit array decay; for example, on x86-64,
16325
// va_list is an array, but it's supposed to decay to
16326
// a pointer for va_arg.
16327
VaListType = Context.getArrayDecayedType(VaListType);
16328
// Make sure the input expression also decays appropriately.
16329
ExprResult Result = UsualUnaryConversions(E);
16330
if (Result.isInvalid())
16331
return ExprError();
16332
E = Result.get();
16333
} else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16334
// If va_list is a record type and we are compiling in C++ mode,
16335
// check the argument using reference binding.
16336
InitializedEntity Entity = InitializedEntity::InitializeParameter(
16337
Context, Context.getLValueReferenceType(VaListType), false);
16338
ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16339
if (Init.isInvalid())
16340
return ExprError();
16341
E = Init.getAs<Expr>();
16342
} else {
16343
// Otherwise, the va_list argument must be an l-value because
16344
// it is modified by va_arg.
16345
if (!E->isTypeDependent() &&
16346
CheckForModifiableLvalue(E, BuiltinLoc, *this))
16347
return ExprError();
16348
}
16349
}
16350
16351
if (!IsMS && !E->isTypeDependent() &&
16352
!Context.hasSameType(VaListType, E->getType()))
16353
return ExprError(
16354
Diag(E->getBeginLoc(),
16355
diag::err_first_argument_to_va_arg_not_of_type_va_list)
16356
<< OrigExpr->getType() << E->getSourceRange());
16357
16358
if (!TInfo->getType()->isDependentType()) {
16359
if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16360
diag::err_second_parameter_to_va_arg_incomplete,
16361
TInfo->getTypeLoc()))
16362
return ExprError();
16363
16364
if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16365
TInfo->getType(),
16366
diag::err_second_parameter_to_va_arg_abstract,
16367
TInfo->getTypeLoc()))
16368
return ExprError();
16369
16370
if (!TInfo->getType().isPODType(Context)) {
16371
Diag(TInfo->getTypeLoc().getBeginLoc(),
16372
TInfo->getType()->isObjCLifetimeType()
16373
? diag::warn_second_parameter_to_va_arg_ownership_qualified
16374
: diag::warn_second_parameter_to_va_arg_not_pod)
16375
<< TInfo->getType()
16376
<< TInfo->getTypeLoc().getSourceRange();
16377
}
16378
16379
// Check for va_arg where arguments of the given type will be promoted
16380
// (i.e. this va_arg is guaranteed to have undefined behavior).
16381
QualType PromoteType;
16382
if (Context.isPromotableIntegerType(TInfo->getType())) {
16383
PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16384
// [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16385
// and C23 7.16.1.1p2 says, in part:
16386
// If type is not compatible with the type of the actual next argument
16387
// (as promoted according to the default argument promotions), the
16388
// behavior is undefined, except for the following cases:
16389
// - both types are pointers to qualified or unqualified versions of
16390
// compatible types;
16391
// - one type is compatible with a signed integer type, the other
16392
// type is compatible with the corresponding unsigned integer type,
16393
// and the value is representable in both types;
16394
// - one type is pointer to qualified or unqualified void and the
16395
// other is a pointer to a qualified or unqualified character type;
16396
// - or, the type of the next argument is nullptr_t and type is a
16397
// pointer type that has the same representation and alignment
16398
// requirements as a pointer to a character type.
16399
// Given that type compatibility is the primary requirement (ignoring
16400
// qualifications), you would think we could call typesAreCompatible()
16401
// directly to test this. However, in C++, that checks for *same type*,
16402
// which causes false positives when passing an enumeration type to
16403
// va_arg. Instead, get the underlying type of the enumeration and pass
16404
// that.
16405
QualType UnderlyingType = TInfo->getType();
16406
if (const auto *ET = UnderlyingType->getAs<EnumType>())
16407
UnderlyingType = ET->getDecl()->getIntegerType();
16408
if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16409
/*CompareUnqualified*/ true))
16410
PromoteType = QualType();
16411
16412
// If the types are still not compatible, we need to test whether the
16413
// promoted type and the underlying type are the same except for
16414
// signedness. Ask the AST for the correctly corresponding type and see
16415
// if that's compatible.
16416
if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16417
PromoteType->isUnsignedIntegerType() !=
16418
UnderlyingType->isUnsignedIntegerType()) {
16419
UnderlyingType =
16420
UnderlyingType->isUnsignedIntegerType()
16421
? Context.getCorrespondingSignedType(UnderlyingType)
16422
: Context.getCorrespondingUnsignedType(UnderlyingType);
16423
if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16424
/*CompareUnqualified*/ true))
16425
PromoteType = QualType();
16426
}
16427
}
16428
if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16429
PromoteType = Context.DoubleTy;
16430
if (!PromoteType.isNull())
16431
DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16432
PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16433
<< TInfo->getType()
16434
<< PromoteType
16435
<< TInfo->getTypeLoc().getSourceRange());
16436
}
16437
16438
QualType T = TInfo->getType().getNonLValueExprType(Context);
16439
return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16440
}
16441
16442
ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16443
// The type of __null will be int or long, depending on the size of
16444
// pointers on the target.
16445
QualType Ty;
16446
unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
16447
if (pw == Context.getTargetInfo().getIntWidth())
16448
Ty = Context.IntTy;
16449
else if (pw == Context.getTargetInfo().getLongWidth())
16450
Ty = Context.LongTy;
16451
else if (pw == Context.getTargetInfo().getLongLongWidth())
16452
Ty = Context.LongLongTy;
16453
else {
16454
llvm_unreachable("I don't know size of pointer!");
16455
}
16456
16457
return new (Context) GNUNullExpr(Ty, TokenLoc);
16458
}
16459
16460
static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16461
CXXRecordDecl *ImplDecl = nullptr;
16462
16463
// Fetch the std::source_location::__impl decl.
16464
if (NamespaceDecl *Std = S.getStdNamespace()) {
16465
LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16466
Loc, Sema::LookupOrdinaryName);
16467
if (S.LookupQualifiedName(ResultSL, Std)) {
16468
if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16469
LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16470
Loc, Sema::LookupOrdinaryName);
16471
if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16472
S.LookupQualifiedName(ResultImpl, SLDecl)) {
16473
ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16474
}
16475
}
16476
}
16477
}
16478
16479
if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16480
S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16481
return nullptr;
16482
}
16483
16484
// Verify that __impl is a trivial struct type, with no base classes, and with
16485
// only the four expected fields.
16486
if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16487
ImplDecl->getNumBases() != 0) {
16488
S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16489
return nullptr;
16490
}
16491
16492
unsigned Count = 0;
16493
for (FieldDecl *F : ImplDecl->fields()) {
16494
StringRef Name = F->getName();
16495
16496
if (Name == "_M_file_name") {
16497
if (F->getType() !=
16498
S.Context.getPointerType(S.Context.CharTy.withConst()))
16499
break;
16500
Count++;
16501
} else if (Name == "_M_function_name") {
16502
if (F->getType() !=
16503
S.Context.getPointerType(S.Context.CharTy.withConst()))
16504
break;
16505
Count++;
16506
} else if (Name == "_M_line") {
16507
if (!F->getType()->isIntegerType())
16508
break;
16509
Count++;
16510
} else if (Name == "_M_column") {
16511
if (!F->getType()->isIntegerType())
16512
break;
16513
Count++;
16514
} else {
16515
Count = 100; // invalid
16516
break;
16517
}
16518
}
16519
if (Count != 4) {
16520
S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16521
return nullptr;
16522
}
16523
16524
return ImplDecl;
16525
}
16526
16527
ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
16528
SourceLocation BuiltinLoc,
16529
SourceLocation RPLoc) {
16530
QualType ResultTy;
16531
switch (Kind) {
16532
case SourceLocIdentKind::File:
16533
case SourceLocIdentKind::FileName:
16534
case SourceLocIdentKind::Function:
16535
case SourceLocIdentKind::FuncSig: {
16536
QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16537
ResultTy =
16538
Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16539
break;
16540
}
16541
case SourceLocIdentKind::Line:
16542
case SourceLocIdentKind::Column:
16543
ResultTy = Context.UnsignedIntTy;
16544
break;
16545
case SourceLocIdentKind::SourceLocStruct:
16546
if (!StdSourceLocationImplDecl) {
16547
StdSourceLocationImplDecl =
16548
LookupStdSourceLocationImpl(*this, BuiltinLoc);
16549
if (!StdSourceLocationImplDecl)
16550
return ExprError();
16551
}
16552
ResultTy = Context.getPointerType(
16553
Context.getRecordType(StdSourceLocationImplDecl).withConst());
16554
break;
16555
}
16556
16557
return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16558
}
16559
16560
ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
16561
SourceLocation BuiltinLoc,
16562
SourceLocation RPLoc,
16563
DeclContext *ParentContext) {
16564
return new (Context)
16565
SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16566
}
16567
16568
ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
16569
StringLiteral *BinaryData) {
16570
EmbedDataStorage *Data = new (Context) EmbedDataStorage;
16571
Data->BinaryData = BinaryData;
16572
return new (Context)
16573
EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
16574
Data->getDataElementCount());
16575
}
16576
16577
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16578
const Expr *SrcExpr) {
16579
if (!DstType->isFunctionPointerType() ||
16580
!SrcExpr->getType()->isFunctionType())
16581
return false;
16582
16583
auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16584
if (!DRE)
16585
return false;
16586
16587
auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16588
if (!FD)
16589
return false;
16590
16591
return !S.checkAddressOfFunctionIsAvailable(FD,
16592
/*Complain=*/true,
16593
SrcExpr->getBeginLoc());
16594
}
16595
16596
bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16597
SourceLocation Loc,
16598
QualType DstType, QualType SrcType,
16599
Expr *SrcExpr, AssignmentAction Action,
16600
bool *Complained) {
16601
if (Complained)
16602
*Complained = false;
16603
16604
// Decode the result (notice that AST's are still created for extensions).
16605
bool CheckInferredResultType = false;
16606
bool isInvalid = false;
16607
unsigned DiagKind = 0;
16608
ConversionFixItGenerator ConvHints;
16609
bool MayHaveConvFixit = false;
16610
bool MayHaveFunctionDiff = false;
16611
const ObjCInterfaceDecl *IFace = nullptr;
16612
const ObjCProtocolDecl *PDecl = nullptr;
16613
16614
switch (ConvTy) {
16615
case Compatible:
16616
DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16617
return false;
16618
16619
case PointerToInt:
16620
if (getLangOpts().CPlusPlus) {
16621
DiagKind = diag::err_typecheck_convert_pointer_int;
16622
isInvalid = true;
16623
} else {
16624
DiagKind = diag::ext_typecheck_convert_pointer_int;
16625
}
16626
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16627
MayHaveConvFixit = true;
16628
break;
16629
case IntToPointer:
16630
if (getLangOpts().CPlusPlus) {
16631
DiagKind = diag::err_typecheck_convert_int_pointer;
16632
isInvalid = true;
16633
} else {
16634
DiagKind = diag::ext_typecheck_convert_int_pointer;
16635
}
16636
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16637
MayHaveConvFixit = true;
16638
break;
16639
case IncompatibleFunctionPointerStrict:
16640
DiagKind =
16641
diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16642
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16643
MayHaveConvFixit = true;
16644
break;
16645
case IncompatibleFunctionPointer:
16646
if (getLangOpts().CPlusPlus) {
16647
DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16648
isInvalid = true;
16649
} else {
16650
DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16651
}
16652
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16653
MayHaveConvFixit = true;
16654
break;
16655
case IncompatiblePointer:
16656
if (Action == AA_Passing_CFAudited) {
16657
DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16658
} else if (getLangOpts().CPlusPlus) {
16659
DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16660
isInvalid = true;
16661
} else {
16662
DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16663
}
16664
CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16665
SrcType->isObjCObjectPointerType();
16666
if (CheckInferredResultType) {
16667
SrcType = SrcType.getUnqualifiedType();
16668
DstType = DstType.getUnqualifiedType();
16669
} else {
16670
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16671
}
16672
MayHaveConvFixit = true;
16673
break;
16674
case IncompatiblePointerSign:
16675
if (getLangOpts().CPlusPlus) {
16676
DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16677
isInvalid = true;
16678
} else {
16679
DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16680
}
16681
break;
16682
case FunctionVoidPointer:
16683
if (getLangOpts().CPlusPlus) {
16684
DiagKind = diag::err_typecheck_convert_pointer_void_func;
16685
isInvalid = true;
16686
} else {
16687
DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16688
}
16689
break;
16690
case IncompatiblePointerDiscardsQualifiers: {
16691
// Perform array-to-pointer decay if necessary.
16692
if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16693
16694
isInvalid = true;
16695
16696
Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16697
Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16698
if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16699
DiagKind = diag::err_typecheck_incompatible_address_space;
16700
break;
16701
} else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16702
DiagKind = diag::err_typecheck_incompatible_ownership;
16703
break;
16704
}
16705
16706
llvm_unreachable("unknown error case for discarding qualifiers!");
16707
// fallthrough
16708
}
16709
case CompatiblePointerDiscardsQualifiers:
16710
// If the qualifiers lost were because we were applying the
16711
// (deprecated) C++ conversion from a string literal to a char*
16712
// (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16713
// Ideally, this check would be performed in
16714
// checkPointerTypesForAssignment. However, that would require a
16715
// bit of refactoring (so that the second argument is an
16716
// expression, rather than a type), which should be done as part
16717
// of a larger effort to fix checkPointerTypesForAssignment for
16718
// C++ semantics.
16719
if (getLangOpts().CPlusPlus &&
16720
IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16721
return false;
16722
if (getLangOpts().CPlusPlus) {
16723
DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16724
isInvalid = true;
16725
} else {
16726
DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16727
}
16728
16729
break;
16730
case IncompatibleNestedPointerQualifiers:
16731
if (getLangOpts().CPlusPlus) {
16732
isInvalid = true;
16733
DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16734
} else {
16735
DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16736
}
16737
break;
16738
case IncompatibleNestedPointerAddressSpaceMismatch:
16739
DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16740
isInvalid = true;
16741
break;
16742
case IntToBlockPointer:
16743
DiagKind = diag::err_int_to_block_pointer;
16744
isInvalid = true;
16745
break;
16746
case IncompatibleBlockPointer:
16747
DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16748
isInvalid = true;
16749
break;
16750
case IncompatibleObjCQualifiedId: {
16751
if (SrcType->isObjCQualifiedIdType()) {
16752
const ObjCObjectPointerType *srcOPT =
16753
SrcType->castAs<ObjCObjectPointerType>();
16754
for (auto *srcProto : srcOPT->quals()) {
16755
PDecl = srcProto;
16756
break;
16757
}
16758
if (const ObjCInterfaceType *IFaceT =
16759
DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16760
IFace = IFaceT->getDecl();
16761
}
16762
else if (DstType->isObjCQualifiedIdType()) {
16763
const ObjCObjectPointerType *dstOPT =
16764
DstType->castAs<ObjCObjectPointerType>();
16765
for (auto *dstProto : dstOPT->quals()) {
16766
PDecl = dstProto;
16767
break;
16768
}
16769
if (const ObjCInterfaceType *IFaceT =
16770
SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16771
IFace = IFaceT->getDecl();
16772
}
16773
if (getLangOpts().CPlusPlus) {
16774
DiagKind = diag::err_incompatible_qualified_id;
16775
isInvalid = true;
16776
} else {
16777
DiagKind = diag::warn_incompatible_qualified_id;
16778
}
16779
break;
16780
}
16781
case IncompatibleVectors:
16782
if (getLangOpts().CPlusPlus) {
16783
DiagKind = diag::err_incompatible_vectors;
16784
isInvalid = true;
16785
} else {
16786
DiagKind = diag::warn_incompatible_vectors;
16787
}
16788
break;
16789
case IncompatibleObjCWeakRef:
16790
DiagKind = diag::err_arc_weak_unavailable_assign;
16791
isInvalid = true;
16792
break;
16793
case Incompatible:
16794
if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16795
if (Complained)
16796
*Complained = true;
16797
return true;
16798
}
16799
16800
DiagKind = diag::err_typecheck_convert_incompatible;
16801
ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16802
MayHaveConvFixit = true;
16803
isInvalid = true;
16804
MayHaveFunctionDiff = true;
16805
break;
16806
}
16807
16808
QualType FirstType, SecondType;
16809
switch (Action) {
16810
case AA_Assigning:
16811
case AA_Initializing:
16812
// The destination type comes first.
16813
FirstType = DstType;
16814
SecondType = SrcType;
16815
break;
16816
16817
case AA_Returning:
16818
case AA_Passing:
16819
case AA_Passing_CFAudited:
16820
case AA_Converting:
16821
case AA_Sending:
16822
case AA_Casting:
16823
// The source type comes first.
16824
FirstType = SrcType;
16825
SecondType = DstType;
16826
break;
16827
}
16828
16829
PartialDiagnostic FDiag = PDiag(DiagKind);
16830
AssignmentAction ActionForDiag = Action;
16831
if (Action == AA_Passing_CFAudited)
16832
ActionForDiag = AA_Passing;
16833
16834
FDiag << FirstType << SecondType << ActionForDiag
16835
<< SrcExpr->getSourceRange();
16836
16837
if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16838
DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16839
auto isPlainChar = [](const clang::Type *Type) {
16840
return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16841
Type->isSpecificBuiltinType(BuiltinType::Char_U);
16842
};
16843
FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16844
isPlainChar(SecondType->getPointeeOrArrayElementType()));
16845
}
16846
16847
// If we can fix the conversion, suggest the FixIts.
16848
if (!ConvHints.isNull()) {
16849
for (FixItHint &H : ConvHints.Hints)
16850
FDiag << H;
16851
}
16852
16853
if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16854
16855
if (MayHaveFunctionDiff)
16856
HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16857
16858
Diag(Loc, FDiag);
16859
if ((DiagKind == diag::warn_incompatible_qualified_id ||
16860
DiagKind == diag::err_incompatible_qualified_id) &&
16861
PDecl && IFace && !IFace->hasDefinition())
16862
Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16863
<< IFace << PDecl;
16864
16865
if (SecondType == Context.OverloadTy)
16866
NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16867
FirstType, /*TakingAddress=*/true);
16868
16869
if (CheckInferredResultType)
16870
ObjC().EmitRelatedResultTypeNote(SrcExpr);
16871
16872
if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16873
ObjC().EmitRelatedResultTypeNoteForReturn(DstType);
16874
16875
if (Complained)
16876
*Complained = true;
16877
return isInvalid;
16878
}
16879
16880
ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16881
llvm::APSInt *Result,
16882
AllowFoldKind CanFold) {
16883
class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16884
public:
16885
SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16886
QualType T) override {
16887
return S.Diag(Loc, diag::err_ice_not_integral)
16888
<< T << S.LangOpts.CPlusPlus;
16889
}
16890
SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16891
return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16892
}
16893
} Diagnoser;
16894
16895
return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16896
}
16897
16898
ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16899
llvm::APSInt *Result,
16900
unsigned DiagID,
16901
AllowFoldKind CanFold) {
16902
class IDDiagnoser : public VerifyICEDiagnoser {
16903
unsigned DiagID;
16904
16905
public:
16906
IDDiagnoser(unsigned DiagID)
16907
: VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16908
16909
SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16910
return S.Diag(Loc, DiagID);
16911
}
16912
} Diagnoser(DiagID);
16913
16914
return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16915
}
16916
16917
Sema::SemaDiagnosticBuilder
16918
Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16919
QualType T) {
16920
return diagnoseNotICE(S, Loc);
16921
}
16922
16923
Sema::SemaDiagnosticBuilder
16924
Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16925
return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16926
}
16927
16928
ExprResult
16929
Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16930
VerifyICEDiagnoser &Diagnoser,
16931
AllowFoldKind CanFold) {
16932
SourceLocation DiagLoc = E->getBeginLoc();
16933
16934
if (getLangOpts().CPlusPlus11) {
16935
// C++11 [expr.const]p5:
16936
// If an expression of literal class type is used in a context where an
16937
// integral constant expression is required, then that class type shall
16938
// have a single non-explicit conversion function to an integral or
16939
// unscoped enumeration type
16940
ExprResult Converted;
16941
class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16942
VerifyICEDiagnoser &BaseDiagnoser;
16943
public:
16944
CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16945
: ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16946
BaseDiagnoser.Suppress, true),
16947
BaseDiagnoser(BaseDiagnoser) {}
16948
16949
SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16950
QualType T) override {
16951
return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16952
}
16953
16954
SemaDiagnosticBuilder diagnoseIncomplete(
16955
Sema &S, SourceLocation Loc, QualType T) override {
16956
return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16957
}
16958
16959
SemaDiagnosticBuilder diagnoseExplicitConv(
16960
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16961
return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16962
}
16963
16964
SemaDiagnosticBuilder noteExplicitConv(
16965
Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16966
return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16967
<< ConvTy->isEnumeralType() << ConvTy;
16968
}
16969
16970
SemaDiagnosticBuilder diagnoseAmbiguous(
16971
Sema &S, SourceLocation Loc, QualType T) override {
16972
return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16973
}
16974
16975
SemaDiagnosticBuilder noteAmbiguous(
16976
Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16977
return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16978
<< ConvTy->isEnumeralType() << ConvTy;
16979
}
16980
16981
SemaDiagnosticBuilder diagnoseConversion(
16982
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16983
llvm_unreachable("conversion functions are permitted");
16984
}
16985
} ConvertDiagnoser(Diagnoser);
16986
16987
Converted = PerformContextualImplicitConversion(DiagLoc, E,
16988
ConvertDiagnoser);
16989
if (Converted.isInvalid())
16990
return Converted;
16991
E = Converted.get();
16992
// The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
16993
// don't try to evaluate it later. We also don't want to return the
16994
// RecoveryExpr here, as it results in this call succeeding, thus callers of
16995
// this function will attempt to use 'Value'.
16996
if (isa<RecoveryExpr>(E))
16997
return ExprError();
16998
if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16999
return ExprError();
17000
} else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17001
// An ICE must be of integral or unscoped enumeration type.
17002
if (!Diagnoser.Suppress)
17003
Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17004
<< E->getSourceRange();
17005
return ExprError();
17006
}
17007
17008
ExprResult RValueExpr = DefaultLvalueConversion(E);
17009
if (RValueExpr.isInvalid())
17010
return ExprError();
17011
17012
E = RValueExpr.get();
17013
17014
// Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17015
// in the non-ICE case.
17016
if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17017
SmallVector<PartialDiagnosticAt, 8> Notes;
17018
if (Result)
17019
*Result = E->EvaluateKnownConstIntCheckOverflow(Context, &Notes);
17020
if (!isa<ConstantExpr>(E))
17021
E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17022
: ConstantExpr::Create(Context, E);
17023
17024
if (Notes.empty())
17025
return E;
17026
17027
// If our only note is the usual "invalid subexpression" note, just point
17028
// the caret at its location rather than producing an essentially
17029
// redundant note.
17030
if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17031
diag::note_invalid_subexpr_in_const_expr) {
17032
DiagLoc = Notes[0].first;
17033
Notes.clear();
17034
}
17035
17036
if (getLangOpts().CPlusPlus) {
17037
if (!Diagnoser.Suppress) {
17038
Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17039
for (const PartialDiagnosticAt &Note : Notes)
17040
Diag(Note.first, Note.second);
17041
}
17042
return ExprError();
17043
}
17044
17045
Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17046
for (const PartialDiagnosticAt &Note : Notes)
17047
Diag(Note.first, Note.second);
17048
17049
return E;
17050
}
17051
17052
Expr::EvalResult EvalResult;
17053
SmallVector<PartialDiagnosticAt, 8> Notes;
17054
EvalResult.Diag = &Notes;
17055
17056
// Try to evaluate the expression, and produce diagnostics explaining why it's
17057
// not a constant expression as a side-effect.
17058
bool Folded =
17059
E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17060
EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17061
(!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17062
17063
if (!isa<ConstantExpr>(E))
17064
E = ConstantExpr::Create(Context, E, EvalResult.Val);
17065
17066
// In C++11, we can rely on diagnostics being produced for any expression
17067
// which is not a constant expression. If no diagnostics were produced, then
17068
// this is a constant expression.
17069
if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17070
if (Result)
17071
*Result = EvalResult.Val.getInt();
17072
return E;
17073
}
17074
17075
// If our only note is the usual "invalid subexpression" note, just point
17076
// the caret at its location rather than producing an essentially
17077
// redundant note.
17078
if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17079
diag::note_invalid_subexpr_in_const_expr) {
17080
DiagLoc = Notes[0].first;
17081
Notes.clear();
17082
}
17083
17084
if (!Folded || !CanFold) {
17085
if (!Diagnoser.Suppress) {
17086
Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17087
for (const PartialDiagnosticAt &Note : Notes)
17088
Diag(Note.first, Note.second);
17089
}
17090
17091
return ExprError();
17092
}
17093
17094
Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17095
for (const PartialDiagnosticAt &Note : Notes)
17096
Diag(Note.first, Note.second);
17097
17098
if (Result)
17099
*Result = EvalResult.Val.getInt();
17100
return E;
17101
}
17102
17103
namespace {
17104
// Handle the case where we conclude a expression which we speculatively
17105
// considered to be unevaluated is actually evaluated.
17106
class TransformToPE : public TreeTransform<TransformToPE> {
17107
typedef TreeTransform<TransformToPE> BaseTransform;
17108
17109
public:
17110
TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17111
17112
// Make sure we redo semantic analysis
17113
bool AlwaysRebuild() { return true; }
17114
bool ReplacingOriginal() { return true; }
17115
17116
// We need to special-case DeclRefExprs referring to FieldDecls which
17117
// are not part of a member pointer formation; normal TreeTransforming
17118
// doesn't catch this case because of the way we represent them in the AST.
17119
// FIXME: This is a bit ugly; is it really the best way to handle this
17120
// case?
17121
//
17122
// Error on DeclRefExprs referring to FieldDecls.
17123
ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17124
if (isa<FieldDecl>(E->getDecl()) &&
17125
!SemaRef.isUnevaluatedContext())
17126
return SemaRef.Diag(E->getLocation(),
17127
diag::err_invalid_non_static_member_use)
17128
<< E->getDecl() << E->getSourceRange();
17129
17130
return BaseTransform::TransformDeclRefExpr(E);
17131
}
17132
17133
// Exception: filter out member pointer formation
17134
ExprResult TransformUnaryOperator(UnaryOperator *E) {
17135
if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17136
return E;
17137
17138
return BaseTransform::TransformUnaryOperator(E);
17139
}
17140
17141
// The body of a lambda-expression is in a separate expression evaluation
17142
// context so never needs to be transformed.
17143
// FIXME: Ideally we wouldn't transform the closure type either, and would
17144
// just recreate the capture expressions and lambda expression.
17145
StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17146
return SkipLambdaBody(E, Body);
17147
}
17148
};
17149
}
17150
17151
ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17152
assert(isUnevaluatedContext() &&
17153
"Should only transform unevaluated expressions");
17154
ExprEvalContexts.back().Context =
17155
ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17156
if (isUnevaluatedContext())
17157
return E;
17158
return TransformToPE(*this).TransformExpr(E);
17159
}
17160
17161
TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17162
assert(isUnevaluatedContext() &&
17163
"Should only transform unevaluated expressions");
17164
ExprEvalContexts.back().Context = parentEvaluationContext().Context;
17165
if (isUnevaluatedContext())
17166
return TInfo;
17167
return TransformToPE(*this).TransformType(TInfo);
17168
}
17169
17170
void
17171
Sema::PushExpressionEvaluationContext(
17172
ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17173
ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17174
ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17175
LambdaContextDecl, ExprContext);
17176
17177
// Discarded statements and immediate contexts nested in other
17178
// discarded statements or immediate context are themselves
17179
// a discarded statement or an immediate context, respectively.
17180
ExprEvalContexts.back().InDiscardedStatement =
17181
parentEvaluationContext().isDiscardedStatementContext();
17182
17183
// C++23 [expr.const]/p15
17184
// An expression or conversion is in an immediate function context if [...]
17185
// it is a subexpression of a manifestly constant-evaluated expression or
17186
// conversion.
17187
const auto &Prev = parentEvaluationContext();
17188
ExprEvalContexts.back().InImmediateFunctionContext =
17189
Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17190
17191
ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17192
Prev.InImmediateEscalatingFunctionContext;
17193
17194
Cleanup.reset();
17195
if (!MaybeODRUseExprs.empty())
17196
std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17197
}
17198
17199
void
17200
Sema::PushExpressionEvaluationContext(
17201
ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17202
ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17203
Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17204
PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17205
}
17206
17207
namespace {
17208
17209
const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17210
PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17211
if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17212
if (E->getOpcode() == UO_Deref)
17213
return CheckPossibleDeref(S, E->getSubExpr());
17214
} else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17215
return CheckPossibleDeref(S, E->getBase());
17216
} else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17217
return CheckPossibleDeref(S, E->getBase());
17218
} else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17219
QualType Inner;
17220
QualType Ty = E->getType();
17221
if (const auto *Ptr = Ty->getAs<PointerType>())
17222
Inner = Ptr->getPointeeType();
17223
else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17224
Inner = Arr->getElementType();
17225
else
17226
return nullptr;
17227
17228
if (Inner->hasAttr(attr::NoDeref))
17229
return E;
17230
}
17231
return nullptr;
17232
}
17233
17234
} // namespace
17235
17236
void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17237
for (const Expr *E : Rec.PossibleDerefs) {
17238
const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17239
if (DeclRef) {
17240
const ValueDecl *Decl = DeclRef->getDecl();
17241
Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17242
<< Decl->getName() << E->getSourceRange();
17243
Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17244
} else {
17245
Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17246
<< E->getSourceRange();
17247
}
17248
}
17249
Rec.PossibleDerefs.clear();
17250
}
17251
17252
void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17253
if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17254
return;
17255
17256
// Note: ignoring parens here is not justified by the standard rules, but
17257
// ignoring parentheses seems like a more reasonable approach, and this only
17258
// drives a deprecation warning so doesn't affect conformance.
17259
if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17260
if (BO->getOpcode() == BO_Assign) {
17261
auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17262
llvm::erase(LHSs, BO->getLHS());
17263
}
17264
}
17265
}
17266
17267
void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
17268
assert(getLangOpts().CPlusPlus20 &&
17269
ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17270
"Cannot mark an immediate escalating expression outside of an "
17271
"immediate escalating context");
17272
if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17273
Call && Call->getCallee()) {
17274
if (auto *DeclRef =
17275
dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17276
DeclRef->setIsImmediateEscalating(true);
17277
} else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17278
Ctr->setIsImmediateEscalating(true);
17279
} else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17280
DeclRef->setIsImmediateEscalating(true);
17281
} else {
17282
assert(false && "expected an immediately escalating expression");
17283
}
17284
if (FunctionScopeInfo *FI = getCurFunction())
17285
FI->FoundImmediateEscalatingExpression = true;
17286
}
17287
17288
ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17289
if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17290
!Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17291
isCheckingDefaultArgumentOrInitializer() ||
17292
RebuildingImmediateInvocation || isImmediateFunctionContext())
17293
return E;
17294
17295
/// Opportunistically remove the callee from ReferencesToConsteval if we can.
17296
/// It's OK if this fails; we'll also remove this in
17297
/// HandleImmediateInvocations, but catching it here allows us to avoid
17298
/// walking the AST looking for it in simple cases.
17299
if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17300
if (auto *DeclRef =
17301
dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17302
ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17303
17304
// C++23 [expr.const]/p16
17305
// An expression or conversion is immediate-escalating if it is not initially
17306
// in an immediate function context and it is [...] an immediate invocation
17307
// that is not a constant expression and is not a subexpression of an
17308
// immediate invocation.
17309
APValue Cached;
17310
auto CheckConstantExpressionAndKeepResult = [&]() {
17311
llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17312
Expr::EvalResult Eval;
17313
Eval.Diag = &Notes;
17314
bool Res = E.get()->EvaluateAsConstantExpr(
17315
Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17316
if (Res && Notes.empty()) {
17317
Cached = std::move(Eval.Val);
17318
return true;
17319
}
17320
return false;
17321
};
17322
17323
if (!E.get()->isValueDependent() &&
17324
ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17325
!CheckConstantExpressionAndKeepResult()) {
17326
MarkExpressionAsImmediateEscalating(E.get());
17327
return E;
17328
}
17329
17330
if (Cleanup.exprNeedsCleanups()) {
17331
// Since an immediate invocation is a full expression itself - it requires
17332
// an additional ExprWithCleanups node, but it can participate to a bigger
17333
// full expression which actually requires cleanups to be run after so
17334
// create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17335
// may discard cleanups for outer expression too early.
17336
17337
// Note that ExprWithCleanups created here must always have empty cleanup
17338
// objects:
17339
// - compound literals do not create cleanup objects in C++ and immediate
17340
// invocations are C++-only.
17341
// - blocks are not allowed inside constant expressions and compiler will
17342
// issue an error if they appear there.
17343
//
17344
// Hence, in correct code any cleanup objects created inside current
17345
// evaluation context must be outside the immediate invocation.
17346
E = ExprWithCleanups::Create(getASTContext(), E.get(),
17347
Cleanup.cleanupsHaveSideEffects(), {});
17348
}
17349
17350
ConstantExpr *Res = ConstantExpr::Create(
17351
getASTContext(), E.get(),
17352
ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17353
getASTContext()),
17354
/*IsImmediateInvocation*/ true);
17355
if (Cached.hasValue())
17356
Res->MoveIntoResult(Cached, getASTContext());
17357
/// Value-dependent constant expressions should not be immediately
17358
/// evaluated until they are instantiated.
17359
if (!Res->isValueDependent())
17360
ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17361
return Res;
17362
}
17363
17364
static void EvaluateAndDiagnoseImmediateInvocation(
17365
Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17366
llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17367
Expr::EvalResult Eval;
17368
Eval.Diag = &Notes;
17369
ConstantExpr *CE = Candidate.getPointer();
17370
bool Result = CE->EvaluateAsConstantExpr(
17371
Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17372
if (!Result || !Notes.empty()) {
17373
SemaRef.FailedImmediateInvocations.insert(CE);
17374
Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17375
if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17376
InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17377
FunctionDecl *FD = nullptr;
17378
if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17379
FD = cast<FunctionDecl>(Call->getCalleeDecl());
17380
else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17381
FD = Call->getConstructor();
17382
else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17383
FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17384
17385
assert(FD && FD->isImmediateFunction() &&
17386
"could not find an immediate function in this expression");
17387
if (FD->isInvalidDecl())
17388
return;
17389
SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17390
<< FD << FD->isConsteval();
17391
if (auto Context =
17392
SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
17393
SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17394
<< Context->Decl;
17395
SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17396
}
17397
if (!FD->isConsteval())
17398
SemaRef.DiagnoseImmediateEscalatingReason(FD);
17399
for (auto &Note : Notes)
17400
SemaRef.Diag(Note.first, Note.second);
17401
return;
17402
}
17403
CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17404
}
17405
17406
static void RemoveNestedImmediateInvocation(
17407
Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17408
SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17409
struct ComplexRemove : TreeTransform<ComplexRemove> {
17410
using Base = TreeTransform<ComplexRemove>;
17411
llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17412
SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17413
SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17414
CurrentII;
17415
ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17416
SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17417
SmallVector<Sema::ImmediateInvocationCandidate,
17418
4>::reverse_iterator Current)
17419
: Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17420
void RemoveImmediateInvocation(ConstantExpr* E) {
17421
auto It = std::find_if(CurrentII, IISet.rend(),
17422
[E](Sema::ImmediateInvocationCandidate Elem) {
17423
return Elem.getPointer() == E;
17424
});
17425
// It is possible that some subexpression of the current immediate
17426
// invocation was handled from another expression evaluation context. Do
17427
// not handle the current immediate invocation if some of its
17428
// subexpressions failed before.
17429
if (It == IISet.rend()) {
17430
if (SemaRef.FailedImmediateInvocations.contains(E))
17431
CurrentII->setInt(1);
17432
} else {
17433
It->setInt(1); // Mark as deleted
17434
}
17435
}
17436
ExprResult TransformConstantExpr(ConstantExpr *E) {
17437
if (!E->isImmediateInvocation())
17438
return Base::TransformConstantExpr(E);
17439
RemoveImmediateInvocation(E);
17440
return Base::TransformExpr(E->getSubExpr());
17441
}
17442
/// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17443
/// we need to remove its DeclRefExpr from the DRSet.
17444
ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17445
DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17446
return Base::TransformCXXOperatorCallExpr(E);
17447
}
17448
/// Base::TransformUserDefinedLiteral doesn't preserve the
17449
/// UserDefinedLiteral node.
17450
ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17451
/// Base::TransformInitializer skips ConstantExpr so we need to visit them
17452
/// here.
17453
ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17454
if (!Init)
17455
return Init;
17456
/// ConstantExpr are the first layer of implicit node to be removed so if
17457
/// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17458
if (auto *CE = dyn_cast<ConstantExpr>(Init))
17459
if (CE->isImmediateInvocation())
17460
RemoveImmediateInvocation(CE);
17461
return Base::TransformInitializer(Init, NotCopyInit);
17462
}
17463
ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17464
DRSet.erase(E);
17465
return E;
17466
}
17467
ExprResult TransformLambdaExpr(LambdaExpr *E) {
17468
// Do not rebuild lambdas to avoid creating a new type.
17469
// Lambdas have already been processed inside their eval context.
17470
return E;
17471
}
17472
bool AlwaysRebuild() { return false; }
17473
bool ReplacingOriginal() { return true; }
17474
bool AllowSkippingCXXConstructExpr() {
17475
bool Res = AllowSkippingFirstCXXConstructExpr;
17476
AllowSkippingFirstCXXConstructExpr = true;
17477
return Res;
17478
}
17479
bool AllowSkippingFirstCXXConstructExpr = true;
17480
} Transformer(SemaRef, Rec.ReferenceToConsteval,
17481
Rec.ImmediateInvocationCandidates, It);
17482
17483
/// CXXConstructExpr with a single argument are getting skipped by
17484
/// TreeTransform in some situtation because they could be implicit. This
17485
/// can only occur for the top-level CXXConstructExpr because it is used
17486
/// nowhere in the expression being transformed therefore will not be rebuilt.
17487
/// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17488
/// skipping the first CXXConstructExpr.
17489
if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17490
Transformer.AllowSkippingFirstCXXConstructExpr = false;
17491
17492
ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17493
// The result may not be usable in case of previous compilation errors.
17494
// In this case evaluation of the expression may result in crash so just
17495
// don't do anything further with the result.
17496
if (Res.isUsable()) {
17497
Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17498
It->getPointer()->setSubExpr(Res.get());
17499
}
17500
}
17501
17502
static void
17503
HandleImmediateInvocations(Sema &SemaRef,
17504
Sema::ExpressionEvaluationContextRecord &Rec) {
17505
if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17506
Rec.ReferenceToConsteval.size() == 0) ||
17507
Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)
17508
return;
17509
17510
/// When we have more than 1 ImmediateInvocationCandidates or previously
17511
/// failed immediate invocations, we need to check for nested
17512
/// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17513
/// Otherwise we only need to remove ReferenceToConsteval in the immediate
17514
/// invocation.
17515
if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17516
!SemaRef.FailedImmediateInvocations.empty()) {
17517
17518
/// Prevent sema calls during the tree transform from adding pointers that
17519
/// are already in the sets.
17520
llvm::SaveAndRestore DisableIITracking(
17521
SemaRef.RebuildingImmediateInvocation, true);
17522
17523
/// Prevent diagnostic during tree transfrom as they are duplicates
17524
Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17525
17526
for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17527
It != Rec.ImmediateInvocationCandidates.rend(); It++)
17528
if (!It->getInt())
17529
RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17530
} else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17531
Rec.ReferenceToConsteval.size()) {
17532
struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17533
llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17534
SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17535
bool VisitDeclRefExpr(DeclRefExpr *E) {
17536
DRSet.erase(E);
17537
return DRSet.size();
17538
}
17539
} Visitor(Rec.ReferenceToConsteval);
17540
Visitor.TraverseStmt(
17541
Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17542
}
17543
for (auto CE : Rec.ImmediateInvocationCandidates)
17544
if (!CE.getInt())
17545
EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17546
for (auto *DR : Rec.ReferenceToConsteval) {
17547
// If the expression is immediate escalating, it is not an error;
17548
// The outer context itself becomes immediate and further errors,
17549
// if any, will be handled by DiagnoseImmediateEscalatingReason.
17550
if (DR->isImmediateEscalating())
17551
continue;
17552
auto *FD = cast<FunctionDecl>(DR->getDecl());
17553
const NamedDecl *ND = FD;
17554
if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17555
MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17556
ND = MD->getParent();
17557
17558
// C++23 [expr.const]/p16
17559
// An expression or conversion is immediate-escalating if it is not
17560
// initially in an immediate function context and it is [...] a
17561
// potentially-evaluated id-expression that denotes an immediate function
17562
// that is not a subexpression of an immediate invocation.
17563
bool ImmediateEscalating = false;
17564
bool IsPotentiallyEvaluated =
17565
Rec.Context ==
17566
Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
17567
Rec.Context ==
17568
Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
17569
if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17570
ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17571
17572
if (!Rec.InImmediateEscalatingFunctionContext ||
17573
(SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17574
SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17575
<< ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17576
SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17577
if (auto Context =
17578
SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
17579
SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17580
<< Context->Decl;
17581
SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17582
}
17583
if (FD->isImmediateEscalating() && !FD->isConsteval())
17584
SemaRef.DiagnoseImmediateEscalatingReason(FD);
17585
17586
} else {
17587
SemaRef.MarkExpressionAsImmediateEscalating(DR);
17588
}
17589
}
17590
}
17591
17592
void Sema::PopExpressionEvaluationContext() {
17593
ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17594
unsigned NumTypos = Rec.NumTypos;
17595
17596
if (!Rec.Lambdas.empty()) {
17597
using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17598
if (!getLangOpts().CPlusPlus20 &&
17599
(Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17600
Rec.isUnevaluated() ||
17601
(Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17602
unsigned D;
17603
if (Rec.isUnevaluated()) {
17604
// C++11 [expr.prim.lambda]p2:
17605
// A lambda-expression shall not appear in an unevaluated operand
17606
// (Clause 5).
17607
D = diag::err_lambda_unevaluated_operand;
17608
} else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17609
// C++1y [expr.const]p2:
17610
// A conditional-expression e is a core constant expression unless the
17611
// evaluation of e, following the rules of the abstract machine, would
17612
// evaluate [...] a lambda-expression.
17613
D = diag::err_lambda_in_constant_expression;
17614
} else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17615
// C++17 [expr.prim.lamda]p2:
17616
// A lambda-expression shall not appear [...] in a template-argument.
17617
D = diag::err_lambda_in_invalid_context;
17618
} else
17619
llvm_unreachable("Couldn't infer lambda error message.");
17620
17621
for (const auto *L : Rec.Lambdas)
17622
Diag(L->getBeginLoc(), D);
17623
}
17624
}
17625
17626
// Append the collected materialized temporaries into previous context before
17627
// exit if the previous also is a lifetime extending context.
17628
auto &PrevRecord = parentEvaluationContext();
17629
if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
17630
PrevRecord.InLifetimeExtendingContext &&
17631
!Rec.ForRangeLifetimeExtendTemps.empty()) {
17632
PrevRecord.ForRangeLifetimeExtendTemps.append(
17633
Rec.ForRangeLifetimeExtendTemps);
17634
}
17635
17636
WarnOnPendingNoDerefs(Rec);
17637
HandleImmediateInvocations(*this, Rec);
17638
17639
// Warn on any volatile-qualified simple-assignments that are not discarded-
17640
// value expressions nor unevaluated operands (those cases get removed from
17641
// this list by CheckUnusedVolatileAssignment).
17642
for (auto *BO : Rec.VolatileAssignmentLHSs)
17643
Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17644
<< BO->getType();
17645
17646
// When are coming out of an unevaluated context, clear out any
17647
// temporaries that we may have created as part of the evaluation of
17648
// the expression in that context: they aren't relevant because they
17649
// will never be constructed.
17650
if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17651
ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17652
ExprCleanupObjects.end());
17653
Cleanup = Rec.ParentCleanup;
17654
CleanupVarDeclMarking();
17655
std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17656
// Otherwise, merge the contexts together.
17657
} else {
17658
Cleanup.mergeFrom(Rec.ParentCleanup);
17659
MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17660
Rec.SavedMaybeODRUseExprs.end());
17661
}
17662
17663
// Pop the current expression evaluation context off the stack.
17664
ExprEvalContexts.pop_back();
17665
17666
// The global expression evaluation context record is never popped.
17667
ExprEvalContexts.back().NumTypos += NumTypos;
17668
}
17669
17670
void Sema::DiscardCleanupsInEvaluationContext() {
17671
ExprCleanupObjects.erase(
17672
ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17673
ExprCleanupObjects.end());
17674
Cleanup.reset();
17675
MaybeODRUseExprs.clear();
17676
}
17677
17678
ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17679
ExprResult Result = CheckPlaceholderExpr(E);
17680
if (Result.isInvalid())
17681
return ExprError();
17682
E = Result.get();
17683
if (!E->getType()->isVariablyModifiedType())
17684
return E;
17685
return TransformToPotentiallyEvaluated(E);
17686
}
17687
17688
/// Are we in a context that is potentially constant evaluated per C++20
17689
/// [expr.const]p12?
17690
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17691
/// C++2a [expr.const]p12:
17692
// An expression or conversion is potentially constant evaluated if it is
17693
switch (SemaRef.ExprEvalContexts.back().Context) {
17694
case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17695
case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17696
17697
// -- a manifestly constant-evaluated expression,
17698
case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17699
case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17700
case Sema::ExpressionEvaluationContext::DiscardedStatement:
17701
// -- a potentially-evaluated expression,
17702
case Sema::ExpressionEvaluationContext::UnevaluatedList:
17703
// -- an immediate subexpression of a braced-init-list,
17704
17705
// -- [FIXME] an expression of the form & cast-expression that occurs
17706
// within a templated entity
17707
// -- a subexpression of one of the above that is not a subexpression of
17708
// a nested unevaluated operand.
17709
return true;
17710
17711
case Sema::ExpressionEvaluationContext::Unevaluated:
17712
case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17713
// Expressions in this context are never evaluated.
17714
return false;
17715
}
17716
llvm_unreachable("Invalid context");
17717
}
17718
17719
/// Return true if this function has a calling convention that requires mangling
17720
/// in the size of the parameter pack.
17721
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17722
// These manglings don't do anything on non-Windows or non-x86 platforms, so
17723
// we don't need parameter type sizes.
17724
const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17725
if (!TT.isOSWindows() || !TT.isX86())
17726
return false;
17727
17728
// If this is C++ and this isn't an extern "C" function, parameters do not
17729
// need to be complete. In this case, C++ mangling will apply, which doesn't
17730
// use the size of the parameters.
17731
if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17732
return false;
17733
17734
// Stdcall, fastcall, and vectorcall need this special treatment.
17735
CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17736
switch (CC) {
17737
case CC_X86StdCall:
17738
case CC_X86FastCall:
17739
case CC_X86VectorCall:
17740
return true;
17741
default:
17742
break;
17743
}
17744
return false;
17745
}
17746
17747
/// Require that all of the parameter types of function be complete. Normally,
17748
/// parameter types are only required to be complete when a function is called
17749
/// or defined, but to mangle functions with certain calling conventions, the
17750
/// mangler needs to know the size of the parameter list. In this situation,
17751
/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17752
/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17753
/// result in a linker error. Clang doesn't implement this behavior, and instead
17754
/// attempts to error at compile time.
17755
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17756
SourceLocation Loc) {
17757
class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17758
FunctionDecl *FD;
17759
ParmVarDecl *Param;
17760
17761
public:
17762
ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17763
: FD(FD), Param(Param) {}
17764
17765
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17766
CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17767
StringRef CCName;
17768
switch (CC) {
17769
case CC_X86StdCall:
17770
CCName = "stdcall";
17771
break;
17772
case CC_X86FastCall:
17773
CCName = "fastcall";
17774
break;
17775
case CC_X86VectorCall:
17776
CCName = "vectorcall";
17777
break;
17778
default:
17779
llvm_unreachable("CC does not need mangling");
17780
}
17781
17782
S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17783
<< Param->getDeclName() << FD->getDeclName() << CCName;
17784
}
17785
};
17786
17787
for (ParmVarDecl *Param : FD->parameters()) {
17788
ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17789
S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17790
}
17791
}
17792
17793
namespace {
17794
enum class OdrUseContext {
17795
/// Declarations in this context are not odr-used.
17796
None,
17797
/// Declarations in this context are formally odr-used, but this is a
17798
/// dependent context.
17799
Dependent,
17800
/// Declarations in this context are odr-used but not actually used (yet).
17801
FormallyOdrUsed,
17802
/// Declarations in this context are used.
17803
Used
17804
};
17805
}
17806
17807
/// Are we within a context in which references to resolved functions or to
17808
/// variables result in odr-use?
17809
static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17810
OdrUseContext Result;
17811
17812
switch (SemaRef.ExprEvalContexts.back().Context) {
17813
case Sema::ExpressionEvaluationContext::Unevaluated:
17814
case Sema::ExpressionEvaluationContext::UnevaluatedList:
17815
case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17816
return OdrUseContext::None;
17817
17818
case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17819
case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17820
case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17821
Result = OdrUseContext::Used;
17822
break;
17823
17824
case Sema::ExpressionEvaluationContext::DiscardedStatement:
17825
Result = OdrUseContext::FormallyOdrUsed;
17826
break;
17827
17828
case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17829
// A default argument formally results in odr-use, but doesn't actually
17830
// result in a use in any real sense until it itself is used.
17831
Result = OdrUseContext::FormallyOdrUsed;
17832
break;
17833
}
17834
17835
if (SemaRef.CurContext->isDependentContext())
17836
return OdrUseContext::Dependent;
17837
17838
return Result;
17839
}
17840
17841
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17842
if (!Func->isConstexpr())
17843
return false;
17844
17845
if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17846
return true;
17847
auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17848
return CCD && CCD->getInheritedConstructor();
17849
}
17850
17851
void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17852
bool MightBeOdrUse) {
17853
assert(Func && "No function?");
17854
17855
Func->setReferenced();
17856
17857
// Recursive functions aren't really used until they're used from some other
17858
// context.
17859
bool IsRecursiveCall = CurContext == Func;
17860
17861
// C++11 [basic.def.odr]p3:
17862
// A function whose name appears as a potentially-evaluated expression is
17863
// odr-used if it is the unique lookup result or the selected member of a
17864
// set of overloaded functions [...].
17865
//
17866
// We (incorrectly) mark overload resolution as an unevaluated context, so we
17867
// can just check that here.
17868
OdrUseContext OdrUse =
17869
MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17870
if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17871
OdrUse = OdrUseContext::FormallyOdrUsed;
17872
17873
// Trivial default constructors and destructors are never actually used.
17874
// FIXME: What about other special members?
17875
if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17876
OdrUse == OdrUseContext::Used) {
17877
if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17878
if (Constructor->isDefaultConstructor())
17879
OdrUse = OdrUseContext::FormallyOdrUsed;
17880
if (isa<CXXDestructorDecl>(Func))
17881
OdrUse = OdrUseContext::FormallyOdrUsed;
17882
}
17883
17884
// C++20 [expr.const]p12:
17885
// A function [...] is needed for constant evaluation if it is [...] a
17886
// constexpr function that is named by an expression that is potentially
17887
// constant evaluated
17888
bool NeededForConstantEvaluation =
17889
isPotentiallyConstantEvaluatedContext(*this) &&
17890
isImplicitlyDefinableConstexprFunction(Func);
17891
17892
// Determine whether we require a function definition to exist, per
17893
// C++11 [temp.inst]p3:
17894
// Unless a function template specialization has been explicitly
17895
// instantiated or explicitly specialized, the function template
17896
// specialization is implicitly instantiated when the specialization is
17897
// referenced in a context that requires a function definition to exist.
17898
// C++20 [temp.inst]p7:
17899
// The existence of a definition of a [...] function is considered to
17900
// affect the semantics of the program if the [...] function is needed for
17901
// constant evaluation by an expression
17902
// C++20 [basic.def.odr]p10:
17903
// Every program shall contain exactly one definition of every non-inline
17904
// function or variable that is odr-used in that program outside of a
17905
// discarded statement
17906
// C++20 [special]p1:
17907
// The implementation will implicitly define [defaulted special members]
17908
// if they are odr-used or needed for constant evaluation.
17909
//
17910
// Note that we skip the implicit instantiation of templates that are only
17911
// used in unused default arguments or by recursive calls to themselves.
17912
// This is formally non-conforming, but seems reasonable in practice.
17913
bool NeedDefinition =
17914
!IsRecursiveCall &&
17915
(OdrUse == OdrUseContext::Used ||
17916
(NeededForConstantEvaluation && !Func->isPureVirtual()));
17917
17918
// C++14 [temp.expl.spec]p6:
17919
// If a template [...] is explicitly specialized then that specialization
17920
// shall be declared before the first use of that specialization that would
17921
// cause an implicit instantiation to take place, in every translation unit
17922
// in which such a use occurs
17923
if (NeedDefinition &&
17924
(Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17925
Func->getMemberSpecializationInfo()))
17926
checkSpecializationReachability(Loc, Func);
17927
17928
if (getLangOpts().CUDA)
17929
CUDA().CheckCall(Loc, Func);
17930
17931
// If we need a definition, try to create one.
17932
if (NeedDefinition && !Func->getBody()) {
17933
runWithSufficientStackSpace(Loc, [&] {
17934
if (CXXConstructorDecl *Constructor =
17935
dyn_cast<CXXConstructorDecl>(Func)) {
17936
Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17937
if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17938
if (Constructor->isDefaultConstructor()) {
17939
if (Constructor->isTrivial() &&
17940
!Constructor->hasAttr<DLLExportAttr>())
17941
return;
17942
DefineImplicitDefaultConstructor(Loc, Constructor);
17943
} else if (Constructor->isCopyConstructor()) {
17944
DefineImplicitCopyConstructor(Loc, Constructor);
17945
} else if (Constructor->isMoveConstructor()) {
17946
DefineImplicitMoveConstructor(Loc, Constructor);
17947
}
17948
} else if (Constructor->getInheritedConstructor()) {
17949
DefineInheritingConstructor(Loc, Constructor);
17950
}
17951
} else if (CXXDestructorDecl *Destructor =
17952
dyn_cast<CXXDestructorDecl>(Func)) {
17953
Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17954
if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17955
if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17956
return;
17957
DefineImplicitDestructor(Loc, Destructor);
17958
}
17959
if (Destructor->isVirtual() && getLangOpts().AppleKext)
17960
MarkVTableUsed(Loc, Destructor->getParent());
17961
} else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17962
if (MethodDecl->isOverloadedOperator() &&
17963
MethodDecl->getOverloadedOperator() == OO_Equal) {
17964
MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17965
if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17966
if (MethodDecl->isCopyAssignmentOperator())
17967
DefineImplicitCopyAssignment(Loc, MethodDecl);
17968
else if (MethodDecl->isMoveAssignmentOperator())
17969
DefineImplicitMoveAssignment(Loc, MethodDecl);
17970
}
17971
} else if (isa<CXXConversionDecl>(MethodDecl) &&
17972
MethodDecl->getParent()->isLambda()) {
17973
CXXConversionDecl *Conversion =
17974
cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17975
if (Conversion->isLambdaToBlockPointerConversion())
17976
DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17977
else
17978
DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17979
} else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17980
MarkVTableUsed(Loc, MethodDecl->getParent());
17981
}
17982
17983
if (Func->isDefaulted() && !Func->isDeleted()) {
17984
DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17985
if (DCK != DefaultedComparisonKind::None)
17986
DefineDefaultedComparison(Loc, Func, DCK);
17987
}
17988
17989
// Implicit instantiation of function templates and member functions of
17990
// class templates.
17991
if (Func->isImplicitlyInstantiable()) {
17992
TemplateSpecializationKind TSK =
17993
Func->getTemplateSpecializationKindForInstantiation();
17994
SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17995
bool FirstInstantiation = PointOfInstantiation.isInvalid();
17996
if (FirstInstantiation) {
17997
PointOfInstantiation = Loc;
17998
if (auto *MSI = Func->getMemberSpecializationInfo())
17999
MSI->setPointOfInstantiation(Loc);
18000
// FIXME: Notify listener.
18001
else
18002
Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18003
} else if (TSK != TSK_ImplicitInstantiation) {
18004
// Use the point of use as the point of instantiation, instead of the
18005
// point of explicit instantiation (which we track as the actual point
18006
// of instantiation). This gives better backtraces in diagnostics.
18007
PointOfInstantiation = Loc;
18008
}
18009
18010
if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18011
Func->isConstexpr()) {
18012
if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18013
cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18014
CodeSynthesisContexts.size())
18015
PendingLocalImplicitInstantiations.push_back(
18016
std::make_pair(Func, PointOfInstantiation));
18017
else if (Func->isConstexpr())
18018
// Do not defer instantiations of constexpr functions, to avoid the
18019
// expression evaluator needing to call back into Sema if it sees a
18020
// call to such a function.
18021
InstantiateFunctionDefinition(PointOfInstantiation, Func);
18022
else {
18023
Func->setInstantiationIsPending(true);
18024
PendingInstantiations.push_back(
18025
std::make_pair(Func, PointOfInstantiation));
18026
// Notify the consumer that a function was implicitly instantiated.
18027
Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18028
}
18029
}
18030
} else {
18031
// Walk redefinitions, as some of them may be instantiable.
18032
for (auto *i : Func->redecls()) {
18033
if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18034
MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18035
}
18036
}
18037
});
18038
}
18039
18040
// If a constructor was defined in the context of a default parameter
18041
// or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18042
// context), its initializers may not be referenced yet.
18043
if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18044
EnterExpressionEvaluationContext EvalContext(
18045
*this,
18046
Constructor->isImmediateFunction()
18047
? ExpressionEvaluationContext::ImmediateFunctionContext
18048
: ExpressionEvaluationContext::PotentiallyEvaluated,
18049
Constructor);
18050
for (CXXCtorInitializer *Init : Constructor->inits()) {
18051
if (Init->isInClassMemberInitializer())
18052
runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18053
MarkDeclarationsReferencedInExpr(Init->getInit());
18054
});
18055
}
18056
}
18057
18058
// C++14 [except.spec]p17:
18059
// An exception-specification is considered to be needed when:
18060
// - the function is odr-used or, if it appears in an unevaluated operand,
18061
// would be odr-used if the expression were potentially-evaluated;
18062
//
18063
// Note, we do this even if MightBeOdrUse is false. That indicates that the
18064
// function is a pure virtual function we're calling, and in that case the
18065
// function was selected by overload resolution and we need to resolve its
18066
// exception specification for a different reason.
18067
const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18068
if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18069
ResolveExceptionSpec(Loc, FPT);
18070
18071
// A callee could be called by a host function then by a device function.
18072
// If we only try recording once, we will miss recording the use on device
18073
// side. Therefore keep trying until it is recorded.
18074
if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18075
!getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
18076
CUDA().RecordImplicitHostDeviceFuncUsedByDevice(Func);
18077
18078
// If this is the first "real" use, act on that.
18079
if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18080
// Keep track of used but undefined functions.
18081
if (!Func->isDefined()) {
18082
if (mightHaveNonExternalLinkage(Func))
18083
UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18084
else if (Func->getMostRecentDecl()->isInlined() &&
18085
!LangOpts.GNUInline &&
18086
!Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18087
UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18088
else if (isExternalWithNoLinkageType(Func))
18089
UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18090
}
18091
18092
// Some x86 Windows calling conventions mangle the size of the parameter
18093
// pack into the name. Computing the size of the parameters requires the
18094
// parameter types to be complete. Check that now.
18095
if (funcHasParameterSizeMangling(*this, Func))
18096
CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18097
18098
// In the MS C++ ABI, the compiler emits destructor variants where they are
18099
// used. If the destructor is used here but defined elsewhere, mark the
18100
// virtual base destructors referenced. If those virtual base destructors
18101
// are inline, this will ensure they are defined when emitting the complete
18102
// destructor variant. This checking may be redundant if the destructor is
18103
// provided later in this TU.
18104
if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18105
if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18106
CXXRecordDecl *Parent = Dtor->getParent();
18107
if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18108
CheckCompleteDestructorVariant(Loc, Dtor);
18109
}
18110
}
18111
18112
Func->markUsed(Context);
18113
}
18114
}
18115
18116
/// Directly mark a variable odr-used. Given a choice, prefer to use
18117
/// MarkVariableReferenced since it does additional checks and then
18118
/// calls MarkVarDeclODRUsed.
18119
/// If the variable must be captured:
18120
/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18121
/// - else capture it in the DeclContext that maps to the
18122
/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18123
static void
18124
MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
18125
const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18126
// Keep track of used but undefined variables.
18127
// FIXME: We shouldn't suppress this warning for static data members.
18128
VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18129
assert(Var && "expected a capturable variable");
18130
18131
if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18132
(!Var->isExternallyVisible() || Var->isInline() ||
18133
SemaRef.isExternalWithNoLinkageType(Var)) &&
18134
!(Var->isStaticDataMember() && Var->hasInit())) {
18135
SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18136
if (old.isInvalid())
18137
old = Loc;
18138
}
18139
QualType CaptureType, DeclRefType;
18140
if (SemaRef.LangOpts.OpenMP)
18141
SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
18142
SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,
18143
/*EllipsisLoc*/ SourceLocation(),
18144
/*BuildAndDiagnose*/ true, CaptureType,
18145
DeclRefType, FunctionScopeIndexToStopAt);
18146
18147
if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18148
auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18149
auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18150
auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18151
if (VarTarget == SemaCUDA::CVT_Host &&
18152
(UserTarget == CUDAFunctionTarget::Device ||
18153
UserTarget == CUDAFunctionTarget::HostDevice ||
18154
UserTarget == CUDAFunctionTarget::Global)) {
18155
// Diagnose ODR-use of host global variables in device functions.
18156
// Reference of device global variables in host functions is allowed
18157
// through shadow variables therefore it is not diagnosed.
18158
if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18159
SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18160
<< /*host*/ 2 << /*variable*/ 1 << Var
18161
<< llvm::to_underlying(UserTarget);
18162
SemaRef.targetDiag(Var->getLocation(),
18163
Var->getType().isConstQualified()
18164
? diag::note_cuda_const_var_unpromoted
18165
: diag::note_cuda_host_var);
18166
}
18167
} else if (VarTarget == SemaCUDA::CVT_Device &&
18168
!Var->hasAttr<CUDASharedAttr>() &&
18169
(UserTarget == CUDAFunctionTarget::Host ||
18170
UserTarget == CUDAFunctionTarget::HostDevice)) {
18171
// Record a CUDA/HIP device side variable if it is ODR-used
18172
// by host code. This is done conservatively, when the variable is
18173
// referenced in any of the following contexts:
18174
// - a non-function context
18175
// - a host function
18176
// - a host device function
18177
// This makes the ODR-use of the device side variable by host code to
18178
// be visible in the device compilation for the compiler to be able to
18179
// emit template variables instantiated by host code only and to
18180
// externalize the static device side variable ODR-used by host code.
18181
if (!Var->hasExternalStorage())
18182
SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18183
else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18184
(!FD || (!FD->getDescribedFunctionTemplate() &&
18185
SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
18186
GVA_StrongExternal)))
18187
SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18188
}
18189
}
18190
18191
V->markUsed(SemaRef.Context);
18192
}
18193
18194
void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
18195
SourceLocation Loc,
18196
unsigned CapturingScopeIndex) {
18197
MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18198
}
18199
18200
void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
18201
ValueDecl *var) {
18202
DeclContext *VarDC = var->getDeclContext();
18203
18204
// If the parameter still belongs to the translation unit, then
18205
// we're actually just using one parameter in the declaration of
18206
// the next.
18207
if (isa<ParmVarDecl>(var) &&
18208
isa<TranslationUnitDecl>(VarDC))
18209
return;
18210
18211
// For C code, don't diagnose about capture if we're not actually in code
18212
// right now; it's impossible to write a non-constant expression outside of
18213
// function context, so we'll get other (more useful) diagnostics later.
18214
//
18215
// For C++, things get a bit more nasty... it would be nice to suppress this
18216
// diagnostic for certain cases like using a local variable in an array bound
18217
// for a member of a local class, but the correct predicate is not obvious.
18218
if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18219
return;
18220
18221
unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18222
unsigned ContextKind = 3; // unknown
18223
if (isa<CXXMethodDecl>(VarDC) &&
18224
cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18225
ContextKind = 2;
18226
} else if (isa<FunctionDecl>(VarDC)) {
18227
ContextKind = 0;
18228
} else if (isa<BlockDecl>(VarDC)) {
18229
ContextKind = 1;
18230
}
18231
18232
S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18233
<< var << ValueKind << ContextKind << VarDC;
18234
S.Diag(var->getLocation(), diag::note_entity_declared_at)
18235
<< var;
18236
18237
// FIXME: Add additional diagnostic info about class etc. which prevents
18238
// capture.
18239
}
18240
18241
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
18242
ValueDecl *Var,
18243
bool &SubCapturesAreNested,
18244
QualType &CaptureType,
18245
QualType &DeclRefType) {
18246
// Check whether we've already captured it.
18247
if (CSI->CaptureMap.count(Var)) {
18248
// If we found a capture, any subcaptures are nested.
18249
SubCapturesAreNested = true;
18250
18251
// Retrieve the capture type for this variable.
18252
CaptureType = CSI->getCapture(Var).getCaptureType();
18253
18254
// Compute the type of an expression that refers to this variable.
18255
DeclRefType = CaptureType.getNonReferenceType();
18256
18257
// Similarly to mutable captures in lambda, all the OpenMP captures by copy
18258
// are mutable in the sense that user can change their value - they are
18259
// private instances of the captured declarations.
18260
const Capture &Cap = CSI->getCapture(Var);
18261
if (Cap.isCopyCapture() &&
18262
!(isa<LambdaScopeInfo>(CSI) &&
18263
!cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18264
!(isa<CapturedRegionScopeInfo>(CSI) &&
18265
cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18266
DeclRefType.addConst();
18267
return true;
18268
}
18269
return false;
18270
}
18271
18272
// Only block literals, captured statements, and lambda expressions can
18273
// capture; other scopes don't work.
18274
static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
18275
ValueDecl *Var,
18276
SourceLocation Loc,
18277
const bool Diagnose,
18278
Sema &S) {
18279
if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18280
return getLambdaAwareParentOfDeclContext(DC);
18281
18282
VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18283
if (Underlying) {
18284
if (Underlying->hasLocalStorage() && Diagnose)
18285
diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18286
}
18287
return nullptr;
18288
}
18289
18290
// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18291
// certain types of variables (unnamed, variably modified types etc.)
18292
// so check for eligibility.
18293
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
18294
SourceLocation Loc, const bool Diagnose,
18295
Sema &S) {
18296
18297
assert((isa<VarDecl, BindingDecl>(Var)) &&
18298
"Only variables and structured bindings can be captured");
18299
18300
bool IsBlock = isa<BlockScopeInfo>(CSI);
18301
bool IsLambda = isa<LambdaScopeInfo>(CSI);
18302
18303
// Lambdas are not allowed to capture unnamed variables
18304
// (e.g. anonymous unions).
18305
// FIXME: The C++11 rule don't actually state this explicitly, but I'm
18306
// assuming that's the intent.
18307
if (IsLambda && !Var->getDeclName()) {
18308
if (Diagnose) {
18309
S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18310
S.Diag(Var->getLocation(), diag::note_declared_at);
18311
}
18312
return false;
18313
}
18314
18315
// Prohibit variably-modified types in blocks; they're difficult to deal with.
18316
if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18317
if (Diagnose) {
18318
S.Diag(Loc, diag::err_ref_vm_type);
18319
S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18320
}
18321
return false;
18322
}
18323
// Prohibit structs with flexible array members too.
18324
// We cannot capture what is in the tail end of the struct.
18325
if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18326
if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18327
if (Diagnose) {
18328
if (IsBlock)
18329
S.Diag(Loc, diag::err_ref_flexarray_type);
18330
else
18331
S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18332
S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18333
}
18334
return false;
18335
}
18336
}
18337
const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18338
// Lambdas and captured statements are not allowed to capture __block
18339
// variables; they don't support the expected semantics.
18340
if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18341
if (Diagnose) {
18342
S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18343
S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18344
}
18345
return false;
18346
}
18347
// OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18348
if (S.getLangOpts().OpenCL && IsBlock &&
18349
Var->getType()->isBlockPointerType()) {
18350
if (Diagnose)
18351
S.Diag(Loc, diag::err_opencl_block_ref_block);
18352
return false;
18353
}
18354
18355
if (isa<BindingDecl>(Var)) {
18356
if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18357
if (Diagnose)
18358
diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18359
return false;
18360
} else if (Diagnose && S.getLangOpts().CPlusPlus) {
18361
S.Diag(Loc, S.LangOpts.CPlusPlus20
18362
? diag::warn_cxx17_compat_capture_binding
18363
: diag::ext_capture_binding)
18364
<< Var;
18365
S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18366
}
18367
}
18368
18369
return true;
18370
}
18371
18372
// Returns true if the capture by block was successful.
18373
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
18374
SourceLocation Loc, const bool BuildAndDiagnose,
18375
QualType &CaptureType, QualType &DeclRefType,
18376
const bool Nested, Sema &S, bool Invalid) {
18377
bool ByRef = false;
18378
18379
// Blocks are not allowed to capture arrays, excepting OpenCL.
18380
// OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18381
// (decayed to pointers).
18382
if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18383
if (BuildAndDiagnose) {
18384
S.Diag(Loc, diag::err_ref_array_type);
18385
S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18386
Invalid = true;
18387
} else {
18388
return false;
18389
}
18390
}
18391
18392
// Forbid the block-capture of autoreleasing variables.
18393
if (!Invalid &&
18394
CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18395
if (BuildAndDiagnose) {
18396
S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18397
<< /*block*/ 0;
18398
S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18399
Invalid = true;
18400
} else {
18401
return false;
18402
}
18403
}
18404
18405
// Warn about implicitly autoreleasing indirect parameters captured by blocks.
18406
if (const auto *PT = CaptureType->getAs<PointerType>()) {
18407
QualType PointeeTy = PT->getPointeeType();
18408
18409
if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18410
PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18411
!S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18412
if (BuildAndDiagnose) {
18413
SourceLocation VarLoc = Var->getLocation();
18414
S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18415
S.Diag(VarLoc, diag::note_declare_parameter_strong);
18416
}
18417
}
18418
}
18419
18420
const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18421
if (HasBlocksAttr || CaptureType->isReferenceType() ||
18422
(S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18423
// Block capture by reference does not change the capture or
18424
// declaration reference types.
18425
ByRef = true;
18426
} else {
18427
// Block capture by copy introduces 'const'.
18428
CaptureType = CaptureType.getNonReferenceType().withConst();
18429
DeclRefType = CaptureType;
18430
}
18431
18432
// Actually capture the variable.
18433
if (BuildAndDiagnose)
18434
BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18435
CaptureType, Invalid);
18436
18437
return !Invalid;
18438
}
18439
18440
/// Capture the given variable in the captured region.
18441
static bool captureInCapturedRegion(
18442
CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
18443
const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18444
const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18445
bool IsTopScope, Sema &S, bool Invalid) {
18446
// By default, capture variables by reference.
18447
bool ByRef = true;
18448
if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18449
ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18450
} else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18451
// Using an LValue reference type is consistent with Lambdas (see below).
18452
if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18453
bool HasConst = DeclRefType.isConstQualified();
18454
DeclRefType = DeclRefType.getUnqualifiedType();
18455
// Don't lose diagnostics about assignments to const.
18456
if (HasConst)
18457
DeclRefType.addConst();
18458
}
18459
// Do not capture firstprivates in tasks.
18460
if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18461
RSI->OpenMPCaptureLevel) != OMPC_unknown)
18462
return true;
18463
ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18464
RSI->OpenMPCaptureLevel);
18465
}
18466
18467
if (ByRef)
18468
CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18469
else
18470
CaptureType = DeclRefType;
18471
18472
// Actually capture the variable.
18473
if (BuildAndDiagnose)
18474
RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18475
Loc, SourceLocation(), CaptureType, Invalid);
18476
18477
return !Invalid;
18478
}
18479
18480
/// Capture the given variable in the lambda.
18481
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
18482
SourceLocation Loc, const bool BuildAndDiagnose,
18483
QualType &CaptureType, QualType &DeclRefType,
18484
const bool RefersToCapturedVariable,
18485
const Sema::TryCaptureKind Kind,
18486
SourceLocation EllipsisLoc, const bool IsTopScope,
18487
Sema &S, bool Invalid) {
18488
// Determine whether we are capturing by reference or by value.
18489
bool ByRef = false;
18490
if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18491
ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18492
} else {
18493
ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18494
}
18495
18496
if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18497
CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
18498
S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18499
Invalid = true;
18500
}
18501
18502
// Compute the type of the field that will capture this variable.
18503
if (ByRef) {
18504
// C++11 [expr.prim.lambda]p15:
18505
// An entity is captured by reference if it is implicitly or
18506
// explicitly captured but not captured by copy. It is
18507
// unspecified whether additional unnamed non-static data
18508
// members are declared in the closure type for entities
18509
// captured by reference.
18510
//
18511
// FIXME: It is not clear whether we want to build an lvalue reference
18512
// to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18513
// to do the former, while EDG does the latter. Core issue 1249 will
18514
// clarify, but for now we follow GCC because it's a more permissive and
18515
// easily defensible position.
18516
CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18517
} else {
18518
// C++11 [expr.prim.lambda]p14:
18519
// For each entity captured by copy, an unnamed non-static
18520
// data member is declared in the closure type. The
18521
// declaration order of these members is unspecified. The type
18522
// of such a data member is the type of the corresponding
18523
// captured entity if the entity is not a reference to an
18524
// object, or the referenced type otherwise. [Note: If the
18525
// captured entity is a reference to a function, the
18526
// corresponding data member is also a reference to a
18527
// function. - end note ]
18528
if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18529
if (!RefType->getPointeeType()->isFunctionType())
18530
CaptureType = RefType->getPointeeType();
18531
}
18532
18533
// Forbid the lambda copy-capture of autoreleasing variables.
18534
if (!Invalid &&
18535
CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18536
if (BuildAndDiagnose) {
18537
S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18538
S.Diag(Var->getLocation(), diag::note_previous_decl)
18539
<< Var->getDeclName();
18540
Invalid = true;
18541
} else {
18542
return false;
18543
}
18544
}
18545
18546
// Make sure that by-copy captures are of a complete and non-abstract type.
18547
if (!Invalid && BuildAndDiagnose) {
18548
if (!CaptureType->isDependentType() &&
18549
S.RequireCompleteSizedType(
18550
Loc, CaptureType,
18551
diag::err_capture_of_incomplete_or_sizeless_type,
18552
Var->getDeclName()))
18553
Invalid = true;
18554
else if (S.RequireNonAbstractType(Loc, CaptureType,
18555
diag::err_capture_of_abstract_type))
18556
Invalid = true;
18557
}
18558
}
18559
18560
// Compute the type of a reference to this captured variable.
18561
if (ByRef)
18562
DeclRefType = CaptureType.getNonReferenceType();
18563
else {
18564
// C++ [expr.prim.lambda]p5:
18565
// The closure type for a lambda-expression has a public inline
18566
// function call operator [...]. This function call operator is
18567
// declared const (9.3.1) if and only if the lambda-expression's
18568
// parameter-declaration-clause is not followed by mutable.
18569
DeclRefType = CaptureType.getNonReferenceType();
18570
bool Const = LSI->lambdaCaptureShouldBeConst();
18571
if (Const && !CaptureType->isReferenceType())
18572
DeclRefType.addConst();
18573
}
18574
18575
// Add the capture.
18576
if (BuildAndDiagnose)
18577
LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18578
Loc, EllipsisLoc, CaptureType, Invalid);
18579
18580
return !Invalid;
18581
}
18582
18583
static bool canCaptureVariableByCopy(ValueDecl *Var,
18584
const ASTContext &Context) {
18585
// Offer a Copy fix even if the type is dependent.
18586
if (Var->getType()->isDependentType())
18587
return true;
18588
QualType T = Var->getType().getNonReferenceType();
18589
if (T.isTriviallyCopyableType(Context))
18590
return true;
18591
if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18592
18593
if (!(RD = RD->getDefinition()))
18594
return false;
18595
if (RD->hasSimpleCopyConstructor())
18596
return true;
18597
if (RD->hasUserDeclaredCopyConstructor())
18598
for (CXXConstructorDecl *Ctor : RD->ctors())
18599
if (Ctor->isCopyConstructor())
18600
return !Ctor->isDeleted();
18601
}
18602
return false;
18603
}
18604
18605
/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18606
/// default capture. Fixes may be omitted if they aren't allowed by the
18607
/// standard, for example we can't emit a default copy capture fix-it if we
18608
/// already explicitly copy capture capture another variable.
18609
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18610
ValueDecl *Var) {
18611
assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
18612
// Don't offer Capture by copy of default capture by copy fixes if Var is
18613
// known not to be copy constructible.
18614
bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18615
18616
SmallString<32> FixBuffer;
18617
StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18618
if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18619
SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18620
if (ShouldOfferCopyFix) {
18621
// Offer fixes to insert an explicit capture for the variable.
18622
// [] -> [VarName]
18623
// [OtherCapture] -> [OtherCapture, VarName]
18624
FixBuffer.assign({Separator, Var->getName()});
18625
Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18626
<< Var << /*value*/ 0
18627
<< FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18628
}
18629
// As above but capture by reference.
18630
FixBuffer.assign({Separator, "&", Var->getName()});
18631
Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18632
<< Var << /*reference*/ 1
18633
<< FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18634
}
18635
18636
// Only try to offer default capture if there are no captures excluding this
18637
// and init captures.
18638
// [this]: OK.
18639
// [X = Y]: OK.
18640
// [&A, &B]: Don't offer.
18641
// [A, B]: Don't offer.
18642
if (llvm::any_of(LSI->Captures, [](Capture &C) {
18643
return !C.isThisCapture() && !C.isInitCapture();
18644
}))
18645
return;
18646
18647
// The default capture specifiers, '=' or '&', must appear first in the
18648
// capture body.
18649
SourceLocation DefaultInsertLoc =
18650
LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18651
18652
if (ShouldOfferCopyFix) {
18653
bool CanDefaultCopyCapture = true;
18654
// [=, *this] OK since c++17
18655
// [=, this] OK since c++20
18656
if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18657
CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18658
? LSI->getCXXThisCapture().isCopyCapture()
18659
: false;
18660
// We can't use default capture by copy if any captures already specified
18661
// capture by copy.
18662
if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18663
return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18664
})) {
18665
FixBuffer.assign({"=", Separator});
18666
Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18667
<< /*value*/ 0
18668
<< FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18669
}
18670
}
18671
18672
// We can't use default capture by reference if any captures already specified
18673
// capture by reference.
18674
if (llvm::none_of(LSI->Captures, [](Capture &C) {
18675
return !C.isInitCapture() && C.isReferenceCapture() &&
18676
!C.isThisCapture();
18677
})) {
18678
FixBuffer.assign({"&", Separator});
18679
Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18680
<< /*reference*/ 1
18681
<< FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18682
}
18683
}
18684
18685
bool Sema::tryCaptureVariable(
18686
ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18687
SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18688
QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18689
// An init-capture is notionally from the context surrounding its
18690
// declaration, but its parent DC is the lambda class.
18691
DeclContext *VarDC = Var->getDeclContext();
18692
DeclContext *DC = CurContext;
18693
18694
// Skip past RequiresExprBodys because they don't constitute function scopes.
18695
while (DC->isRequiresExprBody())
18696
DC = DC->getParent();
18697
18698
// tryCaptureVariable is called every time a DeclRef is formed,
18699
// it can therefore have non-negigible impact on performances.
18700
// For local variables and when there is no capturing scope,
18701
// we can bailout early.
18702
if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18703
return true;
18704
18705
// Exception: Function parameters are not tied to the function's DeclContext
18706
// until we enter the function definition. Capturing them anyway would result
18707
// in an out-of-bounds error while traversing DC and its parents.
18708
if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
18709
return true;
18710
18711
const auto *VD = dyn_cast<VarDecl>(Var);
18712
if (VD) {
18713
if (VD->isInitCapture())
18714
VarDC = VarDC->getParent();
18715
} else {
18716
VD = Var->getPotentiallyDecomposedVarDecl();
18717
}
18718
assert(VD && "Cannot capture a null variable");
18719
18720
const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18721
? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18722
// We need to sync up the Declaration Context with the
18723
// FunctionScopeIndexToStopAt
18724
if (FunctionScopeIndexToStopAt) {
18725
unsigned FSIndex = FunctionScopes.size() - 1;
18726
while (FSIndex != MaxFunctionScopesIndex) {
18727
DC = getLambdaAwareParentOfDeclContext(DC);
18728
--FSIndex;
18729
}
18730
}
18731
18732
// Capture global variables if it is required to use private copy of this
18733
// variable.
18734
bool IsGlobal = !VD->hasLocalStorage();
18735
if (IsGlobal && !(LangOpts.OpenMP &&
18736
OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18737
MaxFunctionScopesIndex)))
18738
return true;
18739
18740
if (isa<VarDecl>(Var))
18741
Var = cast<VarDecl>(Var->getCanonicalDecl());
18742
18743
// Walk up the stack to determine whether we can capture the variable,
18744
// performing the "simple" checks that don't depend on type. We stop when
18745
// we've either hit the declared scope of the variable or find an existing
18746
// capture of that variable. We start from the innermost capturing-entity
18747
// (the DC) and ensure that all intervening capturing-entities
18748
// (blocks/lambdas etc.) between the innermost capturer and the variable`s
18749
// declcontext can either capture the variable or have already captured
18750
// the variable.
18751
CaptureType = Var->getType();
18752
DeclRefType = CaptureType.getNonReferenceType();
18753
bool Nested = false;
18754
bool Explicit = (Kind != TryCapture_Implicit);
18755
unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18756
do {
18757
18758
LambdaScopeInfo *LSI = nullptr;
18759
if (!FunctionScopes.empty())
18760
LSI = dyn_cast_or_null<LambdaScopeInfo>(
18761
FunctionScopes[FunctionScopesIndex]);
18762
18763
bool IsInScopeDeclarationContext =
18764
!LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
18765
18766
if (LSI && !LSI->AfterParameterList) {
18767
// This allows capturing parameters from a default value which does not
18768
// seems correct
18769
if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
18770
return true;
18771
}
18772
// If the variable is declared in the current context, there is no need to
18773
// capture it.
18774
if (IsInScopeDeclarationContext &&
18775
FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
18776
return true;
18777
18778
// Only block literals, captured statements, and lambda expressions can
18779
// capture; other scopes don't work.
18780
DeclContext *ParentDC =
18781
!IsInScopeDeclarationContext
18782
? DC->getParent()
18783
: getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
18784
BuildAndDiagnose, *this);
18785
// We need to check for the parent *first* because, if we *have*
18786
// private-captured a global variable, we need to recursively capture it in
18787
// intermediate blocks, lambdas, etc.
18788
if (!ParentDC) {
18789
if (IsGlobal) {
18790
FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18791
break;
18792
}
18793
return true;
18794
}
18795
18796
FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18797
CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18798
18799
// Check whether we've already captured it.
18800
if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18801
DeclRefType)) {
18802
CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18803
break;
18804
}
18805
18806
// When evaluating some attributes (like enable_if) we might refer to a
18807
// function parameter appertaining to the same declaration as that
18808
// attribute.
18809
if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
18810
Parm && Parm->getDeclContext() == DC)
18811
return true;
18812
18813
// If we are instantiating a generic lambda call operator body,
18814
// we do not want to capture new variables. What was captured
18815
// during either a lambdas transformation or initial parsing
18816
// should be used.
18817
if (isGenericLambdaCallOperatorSpecialization(DC)) {
18818
if (BuildAndDiagnose) {
18819
LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18820
if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18821
Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18822
Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18823
Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18824
buildLambdaCaptureFixit(*this, LSI, Var);
18825
} else
18826
diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
18827
}
18828
return true;
18829
}
18830
18831
// Try to capture variable-length arrays types.
18832
if (Var->getType()->isVariablyModifiedType()) {
18833
// We're going to walk down into the type and look for VLA
18834
// expressions.
18835
QualType QTy = Var->getType();
18836
if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18837
QTy = PVD->getOriginalType();
18838
captureVariablyModifiedType(Context, QTy, CSI);
18839
}
18840
18841
if (getLangOpts().OpenMP) {
18842
if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18843
// OpenMP private variables should not be captured in outer scope, so
18844
// just break here. Similarly, global variables that are captured in a
18845
// target region should not be captured outside the scope of the region.
18846
if (RSI->CapRegionKind == CR_OpenMP) {
18847
// FIXME: We should support capturing structured bindings in OpenMP.
18848
if (isa<BindingDecl>(Var)) {
18849
if (BuildAndDiagnose) {
18850
Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
18851
Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18852
}
18853
return true;
18854
}
18855
OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
18856
Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18857
// If the variable is private (i.e. not captured) and has variably
18858
// modified type, we still need to capture the type for correct
18859
// codegen in all regions, associated with the construct. Currently,
18860
// it is captured in the innermost captured region only.
18861
if (IsOpenMPPrivateDecl != OMPC_unknown &&
18862
Var->getType()->isVariablyModifiedType()) {
18863
QualType QTy = Var->getType();
18864
if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18865
QTy = PVD->getOriginalType();
18866
for (int I = 1,
18867
E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
18868
I < E; ++I) {
18869
auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18870
FunctionScopes[FunctionScopesIndex - I]);
18871
assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18872
"Wrong number of captured regions associated with the "
18873
"OpenMP construct.");
18874
captureVariablyModifiedType(Context, QTy, OuterRSI);
18875
}
18876
}
18877
bool IsTargetCap =
18878
IsOpenMPPrivateDecl != OMPC_private &&
18879
OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18880
RSI->OpenMPCaptureLevel);
18881
// Do not capture global if it is not privatized in outer regions.
18882
bool IsGlobalCap =
18883
IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
18884
Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18885
18886
// When we detect target captures we are looking from inside the
18887
// target region, therefore we need to propagate the capture from the
18888
// enclosing region. Therefore, the capture is not initially nested.
18889
if (IsTargetCap)
18890
OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
18891
RSI->OpenMPLevel);
18892
18893
if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18894
(IsGlobal && !IsGlobalCap)) {
18895
Nested = !IsTargetCap;
18896
bool HasConst = DeclRefType.isConstQualified();
18897
DeclRefType = DeclRefType.getUnqualifiedType();
18898
// Don't lose diagnostics about assignments to const.
18899
if (HasConst)
18900
DeclRefType.addConst();
18901
CaptureType = Context.getLValueReferenceType(DeclRefType);
18902
break;
18903
}
18904
}
18905
}
18906
}
18907
if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18908
// No capture-default, and this is not an explicit capture
18909
// so cannot capture this variable.
18910
if (BuildAndDiagnose) {
18911
Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18912
Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18913
auto *LSI = cast<LambdaScopeInfo>(CSI);
18914
if (LSI->Lambda) {
18915
Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18916
buildLambdaCaptureFixit(*this, LSI, Var);
18917
}
18918
// FIXME: If we error out because an outer lambda can not implicitly
18919
// capture a variable that an inner lambda explicitly captures, we
18920
// should have the inner lambda do the explicit capture - because
18921
// it makes for cleaner diagnostics later. This would purely be done
18922
// so that the diagnostic does not misleadingly claim that a variable
18923
// can not be captured by a lambda implicitly even though it is captured
18924
// explicitly. Suggestion:
18925
// - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18926
// at the function head
18927
// - cache the StartingDeclContext - this must be a lambda
18928
// - captureInLambda in the innermost lambda the variable.
18929
}
18930
return true;
18931
}
18932
Explicit = false;
18933
FunctionScopesIndex--;
18934
if (IsInScopeDeclarationContext)
18935
DC = ParentDC;
18936
} while (!VarDC->Equals(DC));
18937
18938
// Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18939
// computing the type of the capture at each step, checking type-specific
18940
// requirements, and adding captures if requested.
18941
// If the variable had already been captured previously, we start capturing
18942
// at the lambda nested within that one.
18943
bool Invalid = false;
18944
for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18945
++I) {
18946
CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18947
18948
// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18949
// certain types of variables (unnamed, variably modified types etc.)
18950
// so check for eligibility.
18951
if (!Invalid)
18952
Invalid =
18953
!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18954
18955
// After encountering an error, if we're actually supposed to capture, keep
18956
// capturing in nested contexts to suppress any follow-on diagnostics.
18957
if (Invalid && !BuildAndDiagnose)
18958
return true;
18959
18960
if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18961
Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18962
DeclRefType, Nested, *this, Invalid);
18963
Nested = true;
18964
} else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18965
Invalid = !captureInCapturedRegion(
18966
RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18967
Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18968
Nested = true;
18969
} else {
18970
LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18971
Invalid =
18972
!captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18973
DeclRefType, Nested, Kind, EllipsisLoc,
18974
/*IsTopScope*/ I == N - 1, *this, Invalid);
18975
Nested = true;
18976
}
18977
18978
if (Invalid && !BuildAndDiagnose)
18979
return true;
18980
}
18981
return Invalid;
18982
}
18983
18984
bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
18985
TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18986
QualType CaptureType;
18987
QualType DeclRefType;
18988
return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18989
/*BuildAndDiagnose=*/true, CaptureType,
18990
DeclRefType, nullptr);
18991
}
18992
18993
bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
18994
QualType CaptureType;
18995
QualType DeclRefType;
18996
return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18997
/*BuildAndDiagnose=*/false, CaptureType,
18998
DeclRefType, nullptr);
18999
}
19000
19001
QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19002
QualType CaptureType;
19003
QualType DeclRefType;
19004
19005
// Determine whether we can capture this variable.
19006
if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19007
/*BuildAndDiagnose=*/false, CaptureType,
19008
DeclRefType, nullptr))
19009
return QualType();
19010
19011
return DeclRefType;
19012
}
19013
19014
namespace {
19015
// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19016
// The produced TemplateArgumentListInfo* points to data stored within this
19017
// object, so should only be used in contexts where the pointer will not be
19018
// used after the CopiedTemplateArgs object is destroyed.
19019
class CopiedTemplateArgs {
19020
bool HasArgs;
19021
TemplateArgumentListInfo TemplateArgStorage;
19022
public:
19023
template<typename RefExpr>
19024
CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19025
if (HasArgs)
19026
E->copyTemplateArgumentsInto(TemplateArgStorage);
19027
}
19028
operator TemplateArgumentListInfo*()
19029
#ifdef __has_cpp_attribute
19030
#if __has_cpp_attribute(clang::lifetimebound)
19031
[[clang::lifetimebound]]
19032
#endif
19033
#endif
19034
{
19035
return HasArgs ? &TemplateArgStorage : nullptr;
19036
}
19037
};
19038
}
19039
19040
/// Walk the set of potential results of an expression and mark them all as
19041
/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19042
///
19043
/// \return A new expression if we found any potential results, ExprEmpty() if
19044
/// not, and ExprError() if we diagnosed an error.
19045
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
19046
NonOdrUseReason NOUR) {
19047
// Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19048
// an object that satisfies the requirements for appearing in a
19049
// constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19050
// is immediately applied." This function handles the lvalue-to-rvalue
19051
// conversion part.
19052
//
19053
// If we encounter a node that claims to be an odr-use but shouldn't be, we
19054
// transform it into the relevant kind of non-odr-use node and rebuild the
19055
// tree of nodes leading to it.
19056
//
19057
// This is a mini-TreeTransform that only transforms a restricted subset of
19058
// nodes (and only certain operands of them).
19059
19060
// Rebuild a subexpression.
19061
auto Rebuild = [&](Expr *Sub) {
19062
return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19063
};
19064
19065
// Check whether a potential result satisfies the requirements of NOUR.
19066
auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19067
// Any entity other than a VarDecl is always odr-used whenever it's named
19068
// in a potentially-evaluated expression.
19069
auto *VD = dyn_cast<VarDecl>(D);
19070
if (!VD)
19071
return true;
19072
19073
// C++2a [basic.def.odr]p4:
19074
// A variable x whose name appears as a potentially-evalauted expression
19075
// e is odr-used by e unless
19076
// -- x is a reference that is usable in constant expressions, or
19077
// -- x is a variable of non-reference type that is usable in constant
19078
// expressions and has no mutable subobjects, and e is an element of
19079
// the set of potential results of an expression of
19080
// non-volatile-qualified non-class type to which the lvalue-to-rvalue
19081
// conversion is applied, or
19082
// -- x is a variable of non-reference type, and e is an element of the
19083
// set of potential results of a discarded-value expression to which
19084
// the lvalue-to-rvalue conversion is not applied
19085
//
19086
// We check the first bullet and the "potentially-evaluated" condition in
19087
// BuildDeclRefExpr. We check the type requirements in the second bullet
19088
// in CheckLValueToRValueConversionOperand below.
19089
switch (NOUR) {
19090
case NOUR_None:
19091
case NOUR_Unevaluated:
19092
llvm_unreachable("unexpected non-odr-use-reason");
19093
19094
case NOUR_Constant:
19095
// Constant references were handled when they were built.
19096
if (VD->getType()->isReferenceType())
19097
return true;
19098
if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19099
if (RD->hasMutableFields())
19100
return true;
19101
if (!VD->isUsableInConstantExpressions(S.Context))
19102
return true;
19103
break;
19104
19105
case NOUR_Discarded:
19106
if (VD->getType()->isReferenceType())
19107
return true;
19108
break;
19109
}
19110
return false;
19111
};
19112
19113
// Mark that this expression does not constitute an odr-use.
19114
auto MarkNotOdrUsed = [&] {
19115
S.MaybeODRUseExprs.remove(E);
19116
if (LambdaScopeInfo *LSI = S.getCurLambda())
19117
LSI->markVariableExprAsNonODRUsed(E);
19118
};
19119
19120
// C++2a [basic.def.odr]p2:
19121
// The set of potential results of an expression e is defined as follows:
19122
switch (E->getStmtClass()) {
19123
// -- If e is an id-expression, ...
19124
case Expr::DeclRefExprClass: {
19125
auto *DRE = cast<DeclRefExpr>(E);
19126
if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19127
break;
19128
19129
// Rebuild as a non-odr-use DeclRefExpr.
19130
MarkNotOdrUsed();
19131
return DeclRefExpr::Create(
19132
S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19133
DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19134
DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19135
DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19136
}
19137
19138
case Expr::FunctionParmPackExprClass: {
19139
auto *FPPE = cast<FunctionParmPackExpr>(E);
19140
// If any of the declarations in the pack is odr-used, then the expression
19141
// as a whole constitutes an odr-use.
19142
for (VarDecl *D : *FPPE)
19143
if (IsPotentialResultOdrUsed(D))
19144
return ExprEmpty();
19145
19146
// FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19147
// nothing cares about whether we marked this as an odr-use, but it might
19148
// be useful for non-compiler tools.
19149
MarkNotOdrUsed();
19150
break;
19151
}
19152
19153
// -- If e is a subscripting operation with an array operand...
19154
case Expr::ArraySubscriptExprClass: {
19155
auto *ASE = cast<ArraySubscriptExpr>(E);
19156
Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19157
if (!OldBase->getType()->isArrayType())
19158
break;
19159
ExprResult Base = Rebuild(OldBase);
19160
if (!Base.isUsable())
19161
return Base;
19162
Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19163
Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19164
SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19165
return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19166
ASE->getRBracketLoc());
19167
}
19168
19169
case Expr::MemberExprClass: {
19170
auto *ME = cast<MemberExpr>(E);
19171
// -- If e is a class member access expression [...] naming a non-static
19172
// data member...
19173
if (isa<FieldDecl>(ME->getMemberDecl())) {
19174
ExprResult Base = Rebuild(ME->getBase());
19175
if (!Base.isUsable())
19176
return Base;
19177
return MemberExpr::Create(
19178
S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19179
ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19180
ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19181
CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19182
ME->getObjectKind(), ME->isNonOdrUse());
19183
}
19184
19185
if (ME->getMemberDecl()->isCXXInstanceMember())
19186
break;
19187
19188
// -- If e is a class member access expression naming a static data member,
19189
// ...
19190
if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19191
break;
19192
19193
// Rebuild as a non-odr-use MemberExpr.
19194
MarkNotOdrUsed();
19195
return MemberExpr::Create(
19196
S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19197
ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19198
ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19199
ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19200
}
19201
19202
case Expr::BinaryOperatorClass: {
19203
auto *BO = cast<BinaryOperator>(E);
19204
Expr *LHS = BO->getLHS();
19205
Expr *RHS = BO->getRHS();
19206
// -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19207
if (BO->getOpcode() == BO_PtrMemD) {
19208
ExprResult Sub = Rebuild(LHS);
19209
if (!Sub.isUsable())
19210
return Sub;
19211
BO->setLHS(Sub.get());
19212
// -- If e is a comma expression, ...
19213
} else if (BO->getOpcode() == BO_Comma) {
19214
ExprResult Sub = Rebuild(RHS);
19215
if (!Sub.isUsable())
19216
return Sub;
19217
BO->setRHS(Sub.get());
19218
} else {
19219
break;
19220
}
19221
return ExprResult(BO);
19222
}
19223
19224
// -- If e has the form (e1)...
19225
case Expr::ParenExprClass: {
19226
auto *PE = cast<ParenExpr>(E);
19227
ExprResult Sub = Rebuild(PE->getSubExpr());
19228
if (!Sub.isUsable())
19229
return Sub;
19230
return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19231
}
19232
19233
// -- If e is a glvalue conditional expression, ...
19234
// We don't apply this to a binary conditional operator. FIXME: Should we?
19235
case Expr::ConditionalOperatorClass: {
19236
auto *CO = cast<ConditionalOperator>(E);
19237
ExprResult LHS = Rebuild(CO->getLHS());
19238
if (LHS.isInvalid())
19239
return ExprError();
19240
ExprResult RHS = Rebuild(CO->getRHS());
19241
if (RHS.isInvalid())
19242
return ExprError();
19243
if (!LHS.isUsable() && !RHS.isUsable())
19244
return ExprEmpty();
19245
if (!LHS.isUsable())
19246
LHS = CO->getLHS();
19247
if (!RHS.isUsable())
19248
RHS = CO->getRHS();
19249
return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19250
CO->getCond(), LHS.get(), RHS.get());
19251
}
19252
19253
// [Clang extension]
19254
// -- If e has the form __extension__ e1...
19255
case Expr::UnaryOperatorClass: {
19256
auto *UO = cast<UnaryOperator>(E);
19257
if (UO->getOpcode() != UO_Extension)
19258
break;
19259
ExprResult Sub = Rebuild(UO->getSubExpr());
19260
if (!Sub.isUsable())
19261
return Sub;
19262
return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19263
Sub.get());
19264
}
19265
19266
// [Clang extension]
19267
// -- If e has the form _Generic(...), the set of potential results is the
19268
// union of the sets of potential results of the associated expressions.
19269
case Expr::GenericSelectionExprClass: {
19270
auto *GSE = cast<GenericSelectionExpr>(E);
19271
19272
SmallVector<Expr *, 4> AssocExprs;
19273
bool AnyChanged = false;
19274
for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19275
ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19276
if (AssocExpr.isInvalid())
19277
return ExprError();
19278
if (AssocExpr.isUsable()) {
19279
AssocExprs.push_back(AssocExpr.get());
19280
AnyChanged = true;
19281
} else {
19282
AssocExprs.push_back(OrigAssocExpr);
19283
}
19284
}
19285
19286
void *ExOrTy = nullptr;
19287
bool IsExpr = GSE->isExprPredicate();
19288
if (IsExpr)
19289
ExOrTy = GSE->getControllingExpr();
19290
else
19291
ExOrTy = GSE->getControllingType();
19292
return AnyChanged ? S.CreateGenericSelectionExpr(
19293
GSE->getGenericLoc(), GSE->getDefaultLoc(),
19294
GSE->getRParenLoc(), IsExpr, ExOrTy,
19295
GSE->getAssocTypeSourceInfos(), AssocExprs)
19296
: ExprEmpty();
19297
}
19298
19299
// [Clang extension]
19300
// -- If e has the form __builtin_choose_expr(...), the set of potential
19301
// results is the union of the sets of potential results of the
19302
// second and third subexpressions.
19303
case Expr::ChooseExprClass: {
19304
auto *CE = cast<ChooseExpr>(E);
19305
19306
ExprResult LHS = Rebuild(CE->getLHS());
19307
if (LHS.isInvalid())
19308
return ExprError();
19309
19310
ExprResult RHS = Rebuild(CE->getLHS());
19311
if (RHS.isInvalid())
19312
return ExprError();
19313
19314
if (!LHS.get() && !RHS.get())
19315
return ExprEmpty();
19316
if (!LHS.isUsable())
19317
LHS = CE->getLHS();
19318
if (!RHS.isUsable())
19319
RHS = CE->getRHS();
19320
19321
return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19322
RHS.get(), CE->getRParenLoc());
19323
}
19324
19325
// Step through non-syntactic nodes.
19326
case Expr::ConstantExprClass: {
19327
auto *CE = cast<ConstantExpr>(E);
19328
ExprResult Sub = Rebuild(CE->getSubExpr());
19329
if (!Sub.isUsable())
19330
return Sub;
19331
return ConstantExpr::Create(S.Context, Sub.get());
19332
}
19333
19334
// We could mostly rely on the recursive rebuilding to rebuild implicit
19335
// casts, but not at the top level, so rebuild them here.
19336
case Expr::ImplicitCastExprClass: {
19337
auto *ICE = cast<ImplicitCastExpr>(E);
19338
// Only step through the narrow set of cast kinds we expect to encounter.
19339
// Anything else suggests we've left the region in which potential results
19340
// can be found.
19341
switch (ICE->getCastKind()) {
19342
case CK_NoOp:
19343
case CK_DerivedToBase:
19344
case CK_UncheckedDerivedToBase: {
19345
ExprResult Sub = Rebuild(ICE->getSubExpr());
19346
if (!Sub.isUsable())
19347
return Sub;
19348
CXXCastPath Path(ICE->path());
19349
return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19350
ICE->getValueKind(), &Path);
19351
}
19352
19353
default:
19354
break;
19355
}
19356
break;
19357
}
19358
19359
default:
19360
break;
19361
}
19362
19363
// Can't traverse through this node. Nothing to do.
19364
return ExprEmpty();
19365
}
19366
19367
ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19368
// Check whether the operand is or contains an object of non-trivial C union
19369
// type.
19370
if (E->getType().isVolatileQualified() &&
19371
(E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19372
E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19373
checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19374
Sema::NTCUC_LValueToRValueVolatile,
19375
NTCUK_Destruct|NTCUK_Copy);
19376
19377
// C++2a [basic.def.odr]p4:
19378
// [...] an expression of non-volatile-qualified non-class type to which
19379
// the lvalue-to-rvalue conversion is applied [...]
19380
if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19381
return E;
19382
19383
ExprResult Result =
19384
rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19385
if (Result.isInvalid())
19386
return ExprError();
19387
return Result.get() ? Result : E;
19388
}
19389
19390
ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19391
Res = CorrectDelayedTyposInExpr(Res);
19392
19393
if (!Res.isUsable())
19394
return Res;
19395
19396
// If a constant-expression is a reference to a variable where we delay
19397
// deciding whether it is an odr-use, just assume we will apply the
19398
// lvalue-to-rvalue conversion. In the one case where this doesn't happen
19399
// (a non-type template argument), we have special handling anyway.
19400
return CheckLValueToRValueConversionOperand(Res.get());
19401
}
19402
19403
void Sema::CleanupVarDeclMarking() {
19404
// Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19405
// call.
19406
MaybeODRUseExprSet LocalMaybeODRUseExprs;
19407
std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19408
19409
for (Expr *E : LocalMaybeODRUseExprs) {
19410
if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19411
MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19412
DRE->getLocation(), *this);
19413
} else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19414
MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19415
*this);
19416
} else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19417
for (VarDecl *VD : *FP)
19418
MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19419
} else {
19420
llvm_unreachable("Unexpected expression");
19421
}
19422
}
19423
19424
assert(MaybeODRUseExprs.empty() &&
19425
"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19426
}
19427
19428
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
19429
ValueDecl *Var, Expr *E) {
19430
VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
19431
if (!VD)
19432
return;
19433
19434
const bool RefersToEnclosingScope =
19435
(SemaRef.CurContext != VD->getDeclContext() &&
19436
VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
19437
if (RefersToEnclosingScope) {
19438
LambdaScopeInfo *const LSI =
19439
SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19440
if (LSI && (!LSI->CallOperator ||
19441
!LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19442
// If a variable could potentially be odr-used, defer marking it so
19443
// until we finish analyzing the full expression for any
19444
// lvalue-to-rvalue
19445
// or discarded value conversions that would obviate odr-use.
19446
// Add it to the list of potential captures that will be analyzed
19447
// later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19448
// unless the variable is a reference that was initialized by a constant
19449
// expression (this will never need to be captured or odr-used).
19450
//
19451
// FIXME: We can simplify this a lot after implementing P0588R1.
19452
assert(E && "Capture variable should be used in an expression.");
19453
if (!Var->getType()->isReferenceType() ||
19454
!VD->isUsableInConstantExpressions(SemaRef.Context))
19455
LSI->addPotentialCapture(E->IgnoreParens());
19456
}
19457
}
19458
}
19459
19460
static void DoMarkVarDeclReferenced(
19461
Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19462
llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19463
assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19464
isa<FunctionParmPackExpr>(E)) &&
19465
"Invalid Expr argument to DoMarkVarDeclReferenced");
19466
Var->setReferenced();
19467
19468
if (Var->isInvalidDecl())
19469
return;
19470
19471
auto *MSI = Var->getMemberSpecializationInfo();
19472
TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19473
: Var->getTemplateSpecializationKind();
19474
19475
OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19476
bool UsableInConstantExpr =
19477
Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19478
19479
if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19480
RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19481
}
19482
19483
// C++20 [expr.const]p12:
19484
// A variable [...] is needed for constant evaluation if it is [...] a
19485
// variable whose name appears as a potentially constant evaluated
19486
// expression that is either a contexpr variable or is of non-volatile
19487
// const-qualified integral type or of reference type
19488
bool NeededForConstantEvaluation =
19489
isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19490
19491
bool NeedDefinition =
19492
OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19493
19494
assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19495
"Can't instantiate a partial template specialization.");
19496
19497
// If this might be a member specialization of a static data member, check
19498
// the specialization is visible. We already did the checks for variable
19499
// template specializations when we created them.
19500
if (NeedDefinition && TSK != TSK_Undeclared &&
19501
!isa<VarTemplateSpecializationDecl>(Var))
19502
SemaRef.checkSpecializationVisibility(Loc, Var);
19503
19504
// Perform implicit instantiation of static data members, static data member
19505
// templates of class templates, and variable template specializations. Delay
19506
// instantiations of variable templates, except for those that could be used
19507
// in a constant expression.
19508
if (NeedDefinition && isTemplateInstantiation(TSK)) {
19509
// Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19510
// instantiation declaration if a variable is usable in a constant
19511
// expression (among other cases).
19512
bool TryInstantiating =
19513
TSK == TSK_ImplicitInstantiation ||
19514
(TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19515
19516
if (TryInstantiating) {
19517
SourceLocation PointOfInstantiation =
19518
MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19519
bool FirstInstantiation = PointOfInstantiation.isInvalid();
19520
if (FirstInstantiation) {
19521
PointOfInstantiation = Loc;
19522
if (MSI)
19523
MSI->setPointOfInstantiation(PointOfInstantiation);
19524
// FIXME: Notify listener.
19525
else
19526
Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19527
}
19528
19529
if (UsableInConstantExpr) {
19530
// Do not defer instantiations of variables that could be used in a
19531
// constant expression.
19532
SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19533
SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19534
});
19535
19536
// Re-set the member to trigger a recomputation of the dependence bits
19537
// for the expression.
19538
if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19539
DRE->setDecl(DRE->getDecl());
19540
else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19541
ME->setMemberDecl(ME->getMemberDecl());
19542
} else if (FirstInstantiation) {
19543
SemaRef.PendingInstantiations
19544
.push_back(std::make_pair(Var, PointOfInstantiation));
19545
} else {
19546
bool Inserted = false;
19547
for (auto &I : SemaRef.SavedPendingInstantiations) {
19548
auto Iter = llvm::find_if(
19549
I, [Var](const Sema::PendingImplicitInstantiation &P) {
19550
return P.first == Var;
19551
});
19552
if (Iter != I.end()) {
19553
SemaRef.PendingInstantiations.push_back(*Iter);
19554
I.erase(Iter);
19555
Inserted = true;
19556
break;
19557
}
19558
}
19559
19560
// FIXME: For a specialization of a variable template, we don't
19561
// distinguish between "declaration and type implicitly instantiated"
19562
// and "implicit instantiation of definition requested", so we have
19563
// no direct way to avoid enqueueing the pending instantiation
19564
// multiple times.
19565
if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19566
SemaRef.PendingInstantiations
19567
.push_back(std::make_pair(Var, PointOfInstantiation));
19568
}
19569
}
19570
}
19571
19572
// C++2a [basic.def.odr]p4:
19573
// A variable x whose name appears as a potentially-evaluated expression e
19574
// is odr-used by e unless
19575
// -- x is a reference that is usable in constant expressions
19576
// -- x is a variable of non-reference type that is usable in constant
19577
// expressions and has no mutable subobjects [FIXME], and e is an
19578
// element of the set of potential results of an expression of
19579
// non-volatile-qualified non-class type to which the lvalue-to-rvalue
19580
// conversion is applied
19581
// -- x is a variable of non-reference type, and e is an element of the set
19582
// of potential results of a discarded-value expression to which the
19583
// lvalue-to-rvalue conversion is not applied [FIXME]
19584
//
19585
// We check the first part of the second bullet here, and
19586
// Sema::CheckLValueToRValueConversionOperand deals with the second part.
19587
// FIXME: To get the third bullet right, we need to delay this even for
19588
// variables that are not usable in constant expressions.
19589
19590
// If we already know this isn't an odr-use, there's nothing more to do.
19591
if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19592
if (DRE->isNonOdrUse())
19593
return;
19594
if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19595
if (ME->isNonOdrUse())
19596
return;
19597
19598
switch (OdrUse) {
19599
case OdrUseContext::None:
19600
// In some cases, a variable may not have been marked unevaluated, if it
19601
// appears in a defaukt initializer.
19602
assert((!E || isa<FunctionParmPackExpr>(E) ||
19603
SemaRef.isUnevaluatedContext()) &&
19604
"missing non-odr-use marking for unevaluated decl ref");
19605
break;
19606
19607
case OdrUseContext::FormallyOdrUsed:
19608
// FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19609
// behavior.
19610
break;
19611
19612
case OdrUseContext::Used:
19613
// If we might later find that this expression isn't actually an odr-use,
19614
// delay the marking.
19615
if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19616
SemaRef.MaybeODRUseExprs.insert(E);
19617
else
19618
MarkVarDeclODRUsed(Var, Loc, SemaRef);
19619
break;
19620
19621
case OdrUseContext::Dependent:
19622
// If this is a dependent context, we don't need to mark variables as
19623
// odr-used, but we may still need to track them for lambda capture.
19624
// FIXME: Do we also need to do this inside dependent typeid expressions
19625
// (which are modeled as unevaluated at this point)?
19626
DoMarkPotentialCapture(SemaRef, Loc, Var, E);
19627
break;
19628
}
19629
}
19630
19631
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
19632
BindingDecl *BD, Expr *E) {
19633
BD->setReferenced();
19634
19635
if (BD->isInvalidDecl())
19636
return;
19637
19638
OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19639
if (OdrUse == OdrUseContext::Used) {
19640
QualType CaptureType, DeclRefType;
19641
SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
19642
/*EllipsisLoc*/ SourceLocation(),
19643
/*BuildAndDiagnose*/ true, CaptureType,
19644
DeclRefType,
19645
/*FunctionScopeIndexToStopAt*/ nullptr);
19646
} else if (OdrUse == OdrUseContext::Dependent) {
19647
DoMarkPotentialCapture(SemaRef, Loc, BD, E);
19648
}
19649
}
19650
19651
void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19652
DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19653
}
19654
19655
// C++ [temp.dep.expr]p3:
19656
// An id-expression is type-dependent if it contains:
19657
// - an identifier associated by name lookup with an entity captured by copy
19658
// in a lambda-expression that has an explicit object parameter whose type
19659
// is dependent ([dcl.fct]),
19660
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
19661
Sema &SemaRef, ValueDecl *D, Expr *E) {
19662
auto *ID = dyn_cast<DeclRefExpr>(E);
19663
if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19664
return;
19665
19666
// If any enclosing lambda with a dependent explicit object parameter either
19667
// explicitly captures the variable by value, or has a capture default of '='
19668
// and does not capture the variable by reference, then the type of the DRE
19669
// is dependent on the type of that lambda's explicit object parameter.
19670
auto IsDependent = [&]() {
19671
for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19672
auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19673
if (!LSI)
19674
continue;
19675
19676
if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19677
LSI->AfterParameterList)
19678
return false;
19679
19680
const auto *MD = LSI->CallOperator;
19681
if (MD->getType().isNull())
19682
continue;
19683
19684
const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19685
if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19686
!Ty->getParamType(0)->isDependentType())
19687
continue;
19688
19689
if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19690
if (C->isCopyCapture())
19691
return true;
19692
continue;
19693
}
19694
19695
if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19696
return true;
19697
}
19698
return false;
19699
}();
19700
19701
ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19702
IsDependent, SemaRef.getASTContext());
19703
}
19704
19705
static void
19706
MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19707
bool MightBeOdrUse,
19708
llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19709
if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
19710
SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
19711
19712
if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19713
DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19714
if (SemaRef.getLangOpts().CPlusPlus)
19715
FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
19716
Var, E);
19717
return;
19718
}
19719
19720
if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19721
DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
19722
if (SemaRef.getLangOpts().CPlusPlus)
19723
FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
19724
Decl, E);
19725
return;
19726
}
19727
SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19728
19729
// If this is a call to a method via a cast, also mark the method in the
19730
// derived class used in case codegen can devirtualize the call.
19731
const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19732
if (!ME)
19733
return;
19734
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19735
if (!MD)
19736
return;
19737
// Only attempt to devirtualize if this is truly a virtual call.
19738
bool IsVirtualCall = MD->isVirtual() &&
19739
ME->performsVirtualDispatch(SemaRef.getLangOpts());
19740
if (!IsVirtualCall)
19741
return;
19742
19743
// If it's possible to devirtualize the call, mark the called function
19744
// referenced.
19745
CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19746
ME->getBase(), SemaRef.getLangOpts().AppleKext);
19747
if (DM)
19748
SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19749
}
19750
19751
void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19752
// TODO: update this with DR# once a defect report is filed.
19753
// C++11 defect. The address of a pure member should not be an ODR use, even
19754
// if it's a qualified reference.
19755
bool OdrUse = true;
19756
if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19757
if (Method->isVirtual() &&
19758
!Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19759
OdrUse = false;
19760
19761
if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
19762
if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
19763
!isImmediateFunctionContext() &&
19764
!isCheckingDefaultArgumentOrInitializer() &&
19765
FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
19766
!FD->isDependentContext())
19767
ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19768
}
19769
MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19770
RefsMinusAssignments);
19771
}
19772
19773
void Sema::MarkMemberReferenced(MemberExpr *E) {
19774
// C++11 [basic.def.odr]p2:
19775
// A non-overloaded function whose name appears as a potentially-evaluated
19776
// expression or a member of a set of candidate functions, if selected by
19777
// overload resolution when referred to from a potentially-evaluated
19778
// expression, is odr-used, unless it is a pure virtual function and its
19779
// name is not explicitly qualified.
19780
bool MightBeOdrUse = true;
19781
if (E->performsVirtualDispatch(getLangOpts())) {
19782
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19783
if (Method->isPureVirtual())
19784
MightBeOdrUse = false;
19785
}
19786
SourceLocation Loc =
19787
E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19788
MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19789
RefsMinusAssignments);
19790
}
19791
19792
void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19793
for (VarDecl *VD : *E)
19794
MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19795
RefsMinusAssignments);
19796
}
19797
19798
/// Perform marking for a reference to an arbitrary declaration. It
19799
/// marks the declaration referenced, and performs odr-use checking for
19800
/// functions and variables. This method should not be used when building a
19801
/// normal expression which refers to a variable.
19802
void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19803
bool MightBeOdrUse) {
19804
if (MightBeOdrUse) {
19805
if (auto *VD = dyn_cast<VarDecl>(D)) {
19806
MarkVariableReferenced(Loc, VD);
19807
return;
19808
}
19809
}
19810
if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19811
MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19812
return;
19813
}
19814
D->setReferenced();
19815
}
19816
19817
namespace {
19818
// Mark all of the declarations used by a type as referenced.
19819
// FIXME: Not fully implemented yet! We need to have a better understanding
19820
// of when we're entering a context we should not recurse into.
19821
// FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19822
// TreeTransforms rebuilding the type in a new context. Rather than
19823
// duplicating the TreeTransform logic, we should consider reusing it here.
19824
// Currently that causes problems when rebuilding LambdaExprs.
19825
class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19826
Sema &S;
19827
SourceLocation Loc;
19828
19829
public:
19830
typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19831
19832
MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19833
19834
bool TraverseTemplateArgument(const TemplateArgument &Arg);
19835
};
19836
}
19837
19838
bool MarkReferencedDecls::TraverseTemplateArgument(
19839
const TemplateArgument &Arg) {
19840
{
19841
// A non-type template argument is a constant-evaluated context.
19842
EnterExpressionEvaluationContext Evaluated(
19843
S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19844
if (Arg.getKind() == TemplateArgument::Declaration) {
19845
if (Decl *D = Arg.getAsDecl())
19846
S.MarkAnyDeclReferenced(Loc, D, true);
19847
} else if (Arg.getKind() == TemplateArgument::Expression) {
19848
S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19849
}
19850
}
19851
19852
return Inherited::TraverseTemplateArgument(Arg);
19853
}
19854
19855
void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19856
MarkReferencedDecls Marker(*this, Loc);
19857
Marker.TraverseType(T);
19858
}
19859
19860
namespace {
19861
/// Helper class that marks all of the declarations referenced by
19862
/// potentially-evaluated subexpressions as "referenced".
19863
class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19864
public:
19865
typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19866
bool SkipLocalVariables;
19867
ArrayRef<const Expr *> StopAt;
19868
19869
EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19870
ArrayRef<const Expr *> StopAt)
19871
: Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19872
19873
void visitUsedDecl(SourceLocation Loc, Decl *D) {
19874
S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19875
}
19876
19877
void Visit(Expr *E) {
19878
if (llvm::is_contained(StopAt, E))
19879
return;
19880
Inherited::Visit(E);
19881
}
19882
19883
void VisitConstantExpr(ConstantExpr *E) {
19884
// Don't mark declarations within a ConstantExpression, as this expression
19885
// will be evaluated and folded to a value.
19886
}
19887
19888
void VisitDeclRefExpr(DeclRefExpr *E) {
19889
// If we were asked not to visit local variables, don't.
19890
if (SkipLocalVariables) {
19891
if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19892
if (VD->hasLocalStorage())
19893
return;
19894
}
19895
19896
// FIXME: This can trigger the instantiation of the initializer of a
19897
// variable, which can cause the expression to become value-dependent
19898
// or error-dependent. Do we need to propagate the new dependence bits?
19899
S.MarkDeclRefReferenced(E);
19900
}
19901
19902
void VisitMemberExpr(MemberExpr *E) {
19903
S.MarkMemberReferenced(E);
19904
Visit(E->getBase());
19905
}
19906
};
19907
} // namespace
19908
19909
void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19910
bool SkipLocalVariables,
19911
ArrayRef<const Expr*> StopAt) {
19912
EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19913
}
19914
19915
/// Emit a diagnostic when statements are reachable.
19916
/// FIXME: check for reachability even in expressions for which we don't build a
19917
/// CFG (eg, in the initializer of a global or in a constant expression).
19918
/// For example,
19919
/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19920
bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19921
const PartialDiagnostic &PD) {
19922
if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19923
if (!FunctionScopes.empty())
19924
FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19925
sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19926
return true;
19927
}
19928
19929
// The initializer of a constexpr variable or of the first declaration of a
19930
// static data member is not syntactically a constant evaluated constant,
19931
// but nonetheless is always required to be a constant expression, so we
19932
// can skip diagnosing.
19933
// FIXME: Using the mangling context here is a hack.
19934
if (auto *VD = dyn_cast_or_null<VarDecl>(
19935
ExprEvalContexts.back().ManglingContextDecl)) {
19936
if (VD->isConstexpr() ||
19937
(VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19938
return false;
19939
// FIXME: For any other kind of variable, we should build a CFG for its
19940
// initializer and check whether the context in question is reachable.
19941
}
19942
19943
Diag(Loc, PD);
19944
return true;
19945
}
19946
19947
/// Emit a diagnostic that describes an effect on the run-time behavior
19948
/// of the program being compiled.
19949
///
19950
/// This routine emits the given diagnostic when the code currently being
19951
/// type-checked is "potentially evaluated", meaning that there is a
19952
/// possibility that the code will actually be executable. Code in sizeof()
19953
/// expressions, code used only during overload resolution, etc., are not
19954
/// potentially evaluated. This routine will suppress such diagnostics or,
19955
/// in the absolutely nutty case of potentially potentially evaluated
19956
/// expressions (C++ typeid), queue the diagnostic to potentially emit it
19957
/// later.
19958
///
19959
/// This routine should be used for all diagnostics that describe the run-time
19960
/// behavior of a program, such as passing a non-POD value through an ellipsis.
19961
/// Failure to do so will likely result in spurious diagnostics or failures
19962
/// during overload resolution or within sizeof/alignof/typeof/typeid.
19963
bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19964
const PartialDiagnostic &PD) {
19965
19966
if (ExprEvalContexts.back().isDiscardedStatementContext())
19967
return false;
19968
19969
switch (ExprEvalContexts.back().Context) {
19970
case ExpressionEvaluationContext::Unevaluated:
19971
case ExpressionEvaluationContext::UnevaluatedList:
19972
case ExpressionEvaluationContext::UnevaluatedAbstract:
19973
case ExpressionEvaluationContext::DiscardedStatement:
19974
// The argument will never be evaluated, so don't complain.
19975
break;
19976
19977
case ExpressionEvaluationContext::ConstantEvaluated:
19978
case ExpressionEvaluationContext::ImmediateFunctionContext:
19979
// Relevant diagnostics should be produced by constant evaluation.
19980
break;
19981
19982
case ExpressionEvaluationContext::PotentiallyEvaluated:
19983
case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19984
return DiagIfReachable(Loc, Stmts, PD);
19985
}
19986
19987
return false;
19988
}
19989
19990
bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19991
const PartialDiagnostic &PD) {
19992
return DiagRuntimeBehavior(
19993
Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
19994
}
19995
19996
bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19997
CallExpr *CE, FunctionDecl *FD) {
19998
if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19999
return false;
20000
20001
// If we're inside a decltype's expression, don't check for a valid return
20002
// type or construct temporaries until we know whether this is the last call.
20003
if (ExprEvalContexts.back().ExprContext ==
20004
ExpressionEvaluationContextRecord::EK_Decltype) {
20005
ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20006
return false;
20007
}
20008
20009
class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20010
FunctionDecl *FD;
20011
CallExpr *CE;
20012
20013
public:
20014
CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20015
: FD(FD), CE(CE) { }
20016
20017
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20018
if (!FD) {
20019
S.Diag(Loc, diag::err_call_incomplete_return)
20020
<< T << CE->getSourceRange();
20021
return;
20022
}
20023
20024
S.Diag(Loc, diag::err_call_function_incomplete_return)
20025
<< CE->getSourceRange() << FD << T;
20026
S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20027
<< FD->getDeclName();
20028
}
20029
} Diagnoser(FD, CE);
20030
20031
if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20032
return true;
20033
20034
return false;
20035
}
20036
20037
// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20038
// will prevent this condition from triggering, which is what we want.
20039
void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
20040
SourceLocation Loc;
20041
20042
unsigned diagnostic = diag::warn_condition_is_assignment;
20043
bool IsOrAssign = false;
20044
20045
if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20046
if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20047
return;
20048
20049
IsOrAssign = Op->getOpcode() == BO_OrAssign;
20050
20051
// Greylist some idioms by putting them into a warning subcategory.
20052
if (ObjCMessageExpr *ME
20053
= dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20054
Selector Sel = ME->getSelector();
20055
20056
// self = [<foo> init...]
20057
if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20058
diagnostic = diag::warn_condition_is_idiomatic_assignment;
20059
20060
// <foo> = [<bar> nextObject]
20061
else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20062
diagnostic = diag::warn_condition_is_idiomatic_assignment;
20063
}
20064
20065
Loc = Op->getOperatorLoc();
20066
} else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20067
if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20068
return;
20069
20070
IsOrAssign = Op->getOperator() == OO_PipeEqual;
20071
Loc = Op->getOperatorLoc();
20072
} else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20073
return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20074
else {
20075
// Not an assignment.
20076
return;
20077
}
20078
20079
Diag(Loc, diagnostic) << E->getSourceRange();
20080
20081
SourceLocation Open = E->getBeginLoc();
20082
SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
20083
Diag(Loc, diag::note_condition_assign_silence)
20084
<< FixItHint::CreateInsertion(Open, "(")
20085
<< FixItHint::CreateInsertion(Close, ")");
20086
20087
if (IsOrAssign)
20088
Diag(Loc, diag::note_condition_or_assign_to_comparison)
20089
<< FixItHint::CreateReplacement(Loc, "!=");
20090
else
20091
Diag(Loc, diag::note_condition_assign_to_comparison)
20092
<< FixItHint::CreateReplacement(Loc, "==");
20093
}
20094
20095
void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
20096
// Don't warn if the parens came from a macro.
20097
SourceLocation parenLoc = ParenE->getBeginLoc();
20098
if (parenLoc.isInvalid() || parenLoc.isMacroID())
20099
return;
20100
// Don't warn for dependent expressions.
20101
if (ParenE->isTypeDependent())
20102
return;
20103
20104
Expr *E = ParenE->IgnoreParens();
20105
20106
if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20107
if (opE->getOpcode() == BO_EQ &&
20108
opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20109
== Expr::MLV_Valid) {
20110
SourceLocation Loc = opE->getOperatorLoc();
20111
20112
Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20113
SourceRange ParenERange = ParenE->getSourceRange();
20114
Diag(Loc, diag::note_equality_comparison_silence)
20115
<< FixItHint::CreateRemoval(ParenERange.getBegin())
20116
<< FixItHint::CreateRemoval(ParenERange.getEnd());
20117
Diag(Loc, diag::note_equality_comparison_to_assign)
20118
<< FixItHint::CreateReplacement(Loc, "=");
20119
}
20120
}
20121
20122
ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
20123
bool IsConstexpr) {
20124
DiagnoseAssignmentAsCondition(E);
20125
if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20126
DiagnoseEqualityWithExtraParens(parenE);
20127
20128
ExprResult result = CheckPlaceholderExpr(E);
20129
if (result.isInvalid()) return ExprError();
20130
E = result.get();
20131
20132
if (!E->isTypeDependent()) {
20133
if (getLangOpts().CPlusPlus)
20134
return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20135
20136
ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
20137
if (ERes.isInvalid())
20138
return ExprError();
20139
E = ERes.get();
20140
20141
QualType T = E->getType();
20142
if (!T->isScalarType()) { // C99 6.8.4.1p1
20143
Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20144
<< T << E->getSourceRange();
20145
return ExprError();
20146
}
20147
CheckBoolLikeConversion(E, Loc);
20148
}
20149
20150
return E;
20151
}
20152
20153
Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
20154
Expr *SubExpr, ConditionKind CK,
20155
bool MissingOK) {
20156
// MissingOK indicates whether having no condition expression is valid
20157
// (for loop) or invalid (e.g. while loop).
20158
if (!SubExpr)
20159
return MissingOK ? ConditionResult() : ConditionError();
20160
20161
ExprResult Cond;
20162
switch (CK) {
20163
case ConditionKind::Boolean:
20164
Cond = CheckBooleanCondition(Loc, SubExpr);
20165
break;
20166
20167
case ConditionKind::ConstexprIf:
20168
Cond = CheckBooleanCondition(Loc, SubExpr, true);
20169
break;
20170
20171
case ConditionKind::Switch:
20172
Cond = CheckSwitchCondition(Loc, SubExpr);
20173
break;
20174
}
20175
if (Cond.isInvalid()) {
20176
Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20177
{SubExpr}, PreferredConditionType(CK));
20178
if (!Cond.get())
20179
return ConditionError();
20180
}
20181
// FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20182
FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20183
if (!FullExpr.get())
20184
return ConditionError();
20185
20186
return ConditionResult(*this, nullptr, FullExpr,
20187
CK == ConditionKind::ConstexprIf);
20188
}
20189
20190
namespace {
20191
/// A visitor for rebuilding a call to an __unknown_any expression
20192
/// to have an appropriate type.
20193
struct RebuildUnknownAnyFunction
20194
: StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20195
20196
Sema &S;
20197
20198
RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20199
20200
ExprResult VisitStmt(Stmt *S) {
20201
llvm_unreachable("unexpected statement!");
20202
}
20203
20204
ExprResult VisitExpr(Expr *E) {
20205
S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20206
<< E->getSourceRange();
20207
return ExprError();
20208
}
20209
20210
/// Rebuild an expression which simply semantically wraps another
20211
/// expression which it shares the type and value kind of.
20212
template <class T> ExprResult rebuildSugarExpr(T *E) {
20213
ExprResult SubResult = Visit(E->getSubExpr());
20214
if (SubResult.isInvalid()) return ExprError();
20215
20216
Expr *SubExpr = SubResult.get();
20217
E->setSubExpr(SubExpr);
20218
E->setType(SubExpr->getType());
20219
E->setValueKind(SubExpr->getValueKind());
20220
assert(E->getObjectKind() == OK_Ordinary);
20221
return E;
20222
}
20223
20224
ExprResult VisitParenExpr(ParenExpr *E) {
20225
return rebuildSugarExpr(E);
20226
}
20227
20228
ExprResult VisitUnaryExtension(UnaryOperator *E) {
20229
return rebuildSugarExpr(E);
20230
}
20231
20232
ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20233
ExprResult SubResult = Visit(E->getSubExpr());
20234
if (SubResult.isInvalid()) return ExprError();
20235
20236
Expr *SubExpr = SubResult.get();
20237
E->setSubExpr(SubExpr);
20238
E->setType(S.Context.getPointerType(SubExpr->getType()));
20239
assert(E->isPRValue());
20240
assert(E->getObjectKind() == OK_Ordinary);
20241
return E;
20242
}
20243
20244
ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20245
if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20246
20247
E->setType(VD->getType());
20248
20249
assert(E->isPRValue());
20250
if (S.getLangOpts().CPlusPlus &&
20251
!(isa<CXXMethodDecl>(VD) &&
20252
cast<CXXMethodDecl>(VD)->isInstance()))
20253
E->setValueKind(VK_LValue);
20254
20255
return E;
20256
}
20257
20258
ExprResult VisitMemberExpr(MemberExpr *E) {
20259
return resolveDecl(E, E->getMemberDecl());
20260
}
20261
20262
ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20263
return resolveDecl(E, E->getDecl());
20264
}
20265
};
20266
}
20267
20268
/// Given a function expression of unknown-any type, try to rebuild it
20269
/// to have a function type.
20270
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20271
ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20272
if (Result.isInvalid()) return ExprError();
20273
return S.DefaultFunctionArrayConversion(Result.get());
20274
}
20275
20276
namespace {
20277
/// A visitor for rebuilding an expression of type __unknown_anytype
20278
/// into one which resolves the type directly on the referring
20279
/// expression. Strict preservation of the original source
20280
/// structure is not a goal.
20281
struct RebuildUnknownAnyExpr
20282
: StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20283
20284
Sema &S;
20285
20286
/// The current destination type.
20287
QualType DestType;
20288
20289
RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20290
: S(S), DestType(CastType) {}
20291
20292
ExprResult VisitStmt(Stmt *S) {
20293
llvm_unreachable("unexpected statement!");
20294
}
20295
20296
ExprResult VisitExpr(Expr *E) {
20297
S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20298
<< E->getSourceRange();
20299
return ExprError();
20300
}
20301
20302
ExprResult VisitCallExpr(CallExpr *E);
20303
ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20304
20305
/// Rebuild an expression which simply semantically wraps another
20306
/// expression which it shares the type and value kind of.
20307
template <class T> ExprResult rebuildSugarExpr(T *E) {
20308
ExprResult SubResult = Visit(E->getSubExpr());
20309
if (SubResult.isInvalid()) return ExprError();
20310
Expr *SubExpr = SubResult.get();
20311
E->setSubExpr(SubExpr);
20312
E->setType(SubExpr->getType());
20313
E->setValueKind(SubExpr->getValueKind());
20314
assert(E->getObjectKind() == OK_Ordinary);
20315
return E;
20316
}
20317
20318
ExprResult VisitParenExpr(ParenExpr *E) {
20319
return rebuildSugarExpr(E);
20320
}
20321
20322
ExprResult VisitUnaryExtension(UnaryOperator *E) {
20323
return rebuildSugarExpr(E);
20324
}
20325
20326
ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20327
const PointerType *Ptr = DestType->getAs<PointerType>();
20328
if (!Ptr) {
20329
S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20330
<< E->getSourceRange();
20331
return ExprError();
20332
}
20333
20334
if (isa<CallExpr>(E->getSubExpr())) {
20335
S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20336
<< E->getSourceRange();
20337
return ExprError();
20338
}
20339
20340
assert(E->isPRValue());
20341
assert(E->getObjectKind() == OK_Ordinary);
20342
E->setType(DestType);
20343
20344
// Build the sub-expression as if it were an object of the pointee type.
20345
DestType = Ptr->getPointeeType();
20346
ExprResult SubResult = Visit(E->getSubExpr());
20347
if (SubResult.isInvalid()) return ExprError();
20348
E->setSubExpr(SubResult.get());
20349
return E;
20350
}
20351
20352
ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20353
20354
ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20355
20356
ExprResult VisitMemberExpr(MemberExpr *E) {
20357
return resolveDecl(E, E->getMemberDecl());
20358
}
20359
20360
ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20361
return resolveDecl(E, E->getDecl());
20362
}
20363
};
20364
}
20365
20366
/// Rebuilds a call expression which yielded __unknown_anytype.
20367
ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20368
Expr *CalleeExpr = E->getCallee();
20369
20370
enum FnKind {
20371
FK_MemberFunction,
20372
FK_FunctionPointer,
20373
FK_BlockPointer
20374
};
20375
20376
FnKind Kind;
20377
QualType CalleeType = CalleeExpr->getType();
20378
if (CalleeType == S.Context.BoundMemberTy) {
20379
assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20380
Kind = FK_MemberFunction;
20381
CalleeType = Expr::findBoundMemberType(CalleeExpr);
20382
} else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20383
CalleeType = Ptr->getPointeeType();
20384
Kind = FK_FunctionPointer;
20385
} else {
20386
CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20387
Kind = FK_BlockPointer;
20388
}
20389
const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20390
20391
// Verify that this is a legal result type of a function.
20392
if (DestType->isArrayType() || DestType->isFunctionType()) {
20393
unsigned diagID = diag::err_func_returning_array_function;
20394
if (Kind == FK_BlockPointer)
20395
diagID = diag::err_block_returning_array_function;
20396
20397
S.Diag(E->getExprLoc(), diagID)
20398
<< DestType->isFunctionType() << DestType;
20399
return ExprError();
20400
}
20401
20402
// Otherwise, go ahead and set DestType as the call's result.
20403
E->setType(DestType.getNonLValueExprType(S.Context));
20404
E->setValueKind(Expr::getValueKindForType(DestType));
20405
assert(E->getObjectKind() == OK_Ordinary);
20406
20407
// Rebuild the function type, replacing the result type with DestType.
20408
const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20409
if (Proto) {
20410
// __unknown_anytype(...) is a special case used by the debugger when
20411
// it has no idea what a function's signature is.
20412
//
20413
// We want to build this call essentially under the K&R
20414
// unprototyped rules, but making a FunctionNoProtoType in C++
20415
// would foul up all sorts of assumptions. However, we cannot
20416
// simply pass all arguments as variadic arguments, nor can we
20417
// portably just call the function under a non-variadic type; see
20418
// the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20419
// However, it turns out that in practice it is generally safe to
20420
// call a function declared as "A foo(B,C,D);" under the prototype
20421
// "A foo(B,C,D,...);". The only known exception is with the
20422
// Windows ABI, where any variadic function is implicitly cdecl
20423
// regardless of its normal CC. Therefore we change the parameter
20424
// types to match the types of the arguments.
20425
//
20426
// This is a hack, but it is far superior to moving the
20427
// corresponding target-specific code from IR-gen to Sema/AST.
20428
20429
ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20430
SmallVector<QualType, 8> ArgTypes;
20431
if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20432
ArgTypes.reserve(E->getNumArgs());
20433
for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20434
ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20435
}
20436
ParamTypes = ArgTypes;
20437
}
20438
DestType = S.Context.getFunctionType(DestType, ParamTypes,
20439
Proto->getExtProtoInfo());
20440
} else {
20441
DestType = S.Context.getFunctionNoProtoType(DestType,
20442
FnType->getExtInfo());
20443
}
20444
20445
// Rebuild the appropriate pointer-to-function type.
20446
switch (Kind) {
20447
case FK_MemberFunction:
20448
// Nothing to do.
20449
break;
20450
20451
case FK_FunctionPointer:
20452
DestType = S.Context.getPointerType(DestType);
20453
break;
20454
20455
case FK_BlockPointer:
20456
DestType = S.Context.getBlockPointerType(DestType);
20457
break;
20458
}
20459
20460
// Finally, we can recurse.
20461
ExprResult CalleeResult = Visit(CalleeExpr);
20462
if (!CalleeResult.isUsable()) return ExprError();
20463
E->setCallee(CalleeResult.get());
20464
20465
// Bind a temporary if necessary.
20466
return S.MaybeBindToTemporary(E);
20467
}
20468
20469
ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20470
// Verify that this is a legal result type of a call.
20471
if (DestType->isArrayType() || DestType->isFunctionType()) {
20472
S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20473
<< DestType->isFunctionType() << DestType;
20474
return ExprError();
20475
}
20476
20477
// Rewrite the method result type if available.
20478
if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20479
assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20480
Method->setReturnType(DestType);
20481
}
20482
20483
// Change the type of the message.
20484
E->setType(DestType.getNonReferenceType());
20485
E->setValueKind(Expr::getValueKindForType(DestType));
20486
20487
return S.MaybeBindToTemporary(E);
20488
}
20489
20490
ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20491
// The only case we should ever see here is a function-to-pointer decay.
20492
if (E->getCastKind() == CK_FunctionToPointerDecay) {
20493
assert(E->isPRValue());
20494
assert(E->getObjectKind() == OK_Ordinary);
20495
20496
E->setType(DestType);
20497
20498
// Rebuild the sub-expression as the pointee (function) type.
20499
DestType = DestType->castAs<PointerType>()->getPointeeType();
20500
20501
ExprResult Result = Visit(E->getSubExpr());
20502
if (!Result.isUsable()) return ExprError();
20503
20504
E->setSubExpr(Result.get());
20505
return E;
20506
} else if (E->getCastKind() == CK_LValueToRValue) {
20507
assert(E->isPRValue());
20508
assert(E->getObjectKind() == OK_Ordinary);
20509
20510
assert(isa<BlockPointerType>(E->getType()));
20511
20512
E->setType(DestType);
20513
20514
// The sub-expression has to be a lvalue reference, so rebuild it as such.
20515
DestType = S.Context.getLValueReferenceType(DestType);
20516
20517
ExprResult Result = Visit(E->getSubExpr());
20518
if (!Result.isUsable()) return ExprError();
20519
20520
E->setSubExpr(Result.get());
20521
return E;
20522
} else {
20523
llvm_unreachable("Unhandled cast type!");
20524
}
20525
}
20526
20527
ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20528
ExprValueKind ValueKind = VK_LValue;
20529
QualType Type = DestType;
20530
20531
// We know how to make this work for certain kinds of decls:
20532
20533
// - functions
20534
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20535
if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20536
DestType = Ptr->getPointeeType();
20537
ExprResult Result = resolveDecl(E, VD);
20538
if (Result.isInvalid()) return ExprError();
20539
return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20540
VK_PRValue);
20541
}
20542
20543
if (!Type->isFunctionType()) {
20544
S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20545
<< VD << E->getSourceRange();
20546
return ExprError();
20547
}
20548
if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20549
// We must match the FunctionDecl's type to the hack introduced in
20550
// RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20551
// type. See the lengthy commentary in that routine.
20552
QualType FDT = FD->getType();
20553
const FunctionType *FnType = FDT->castAs<FunctionType>();
20554
const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20555
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20556
if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20557
SourceLocation Loc = FD->getLocation();
20558
FunctionDecl *NewFD = FunctionDecl::Create(
20559
S.Context, FD->getDeclContext(), Loc, Loc,
20560
FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20561
SC_None, S.getCurFPFeatures().isFPConstrained(),
20562
false /*isInlineSpecified*/, FD->hasPrototype(),
20563
/*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20564
20565
if (FD->getQualifier())
20566
NewFD->setQualifierInfo(FD->getQualifierLoc());
20567
20568
SmallVector<ParmVarDecl*, 16> Params;
20569
for (const auto &AI : FT->param_types()) {
20570
ParmVarDecl *Param =
20571
S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20572
Param->setScopeInfo(0, Params.size());
20573
Params.push_back(Param);
20574
}
20575
NewFD->setParams(Params);
20576
DRE->setDecl(NewFD);
20577
VD = DRE->getDecl();
20578
}
20579
}
20580
20581
if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20582
if (MD->isInstance()) {
20583
ValueKind = VK_PRValue;
20584
Type = S.Context.BoundMemberTy;
20585
}
20586
20587
// Function references aren't l-values in C.
20588
if (!S.getLangOpts().CPlusPlus)
20589
ValueKind = VK_PRValue;
20590
20591
// - variables
20592
} else if (isa<VarDecl>(VD)) {
20593
if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20594
Type = RefTy->getPointeeType();
20595
} else if (Type->isFunctionType()) {
20596
S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20597
<< VD << E->getSourceRange();
20598
return ExprError();
20599
}
20600
20601
// - nothing else
20602
} else {
20603
S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20604
<< VD << E->getSourceRange();
20605
return ExprError();
20606
}
20607
20608
// Modifying the declaration like this is friendly to IR-gen but
20609
// also really dangerous.
20610
VD->setType(DestType);
20611
E->setType(Type);
20612
E->setValueKind(ValueKind);
20613
return E;
20614
}
20615
20616
ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20617
Expr *CastExpr, CastKind &CastKind,
20618
ExprValueKind &VK, CXXCastPath &Path) {
20619
// The type we're casting to must be either void or complete.
20620
if (!CastType->isVoidType() &&
20621
RequireCompleteType(TypeRange.getBegin(), CastType,
20622
diag::err_typecheck_cast_to_incomplete))
20623
return ExprError();
20624
20625
// Rewrite the casted expression from scratch.
20626
ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20627
if (!result.isUsable()) return ExprError();
20628
20629
CastExpr = result.get();
20630
VK = CastExpr->getValueKind();
20631
CastKind = CK_NoOp;
20632
20633
return CastExpr;
20634
}
20635
20636
ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20637
return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20638
}
20639
20640
ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20641
Expr *arg, QualType &paramType) {
20642
// If the syntactic form of the argument is not an explicit cast of
20643
// any sort, just do default argument promotion.
20644
ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20645
if (!castArg) {
20646
ExprResult result = DefaultArgumentPromotion(arg);
20647
if (result.isInvalid()) return ExprError();
20648
paramType = result.get()->getType();
20649
return result;
20650
}
20651
20652
// Otherwise, use the type that was written in the explicit cast.
20653
assert(!arg->hasPlaceholderType());
20654
paramType = castArg->getTypeAsWritten();
20655
20656
// Copy-initialize a parameter of that type.
20657
InitializedEntity entity =
20658
InitializedEntity::InitializeParameter(Context, paramType,
20659
/*consumed*/ false);
20660
return PerformCopyInitialization(entity, callLoc, arg);
20661
}
20662
20663
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20664
Expr *orig = E;
20665
unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20666
while (true) {
20667
E = E->IgnoreParenImpCasts();
20668
if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20669
E = call->getCallee();
20670
diagID = diag::err_uncasted_call_of_unknown_any;
20671
} else {
20672
break;
20673
}
20674
}
20675
20676
SourceLocation loc;
20677
NamedDecl *d;
20678
if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20679
loc = ref->getLocation();
20680
d = ref->getDecl();
20681
} else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20682
loc = mem->getMemberLoc();
20683
d = mem->getMemberDecl();
20684
} else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20685
diagID = diag::err_uncasted_call_of_unknown_any;
20686
loc = msg->getSelectorStartLoc();
20687
d = msg->getMethodDecl();
20688
if (!d) {
20689
S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20690
<< static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20691
<< orig->getSourceRange();
20692
return ExprError();
20693
}
20694
} else {
20695
S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20696
<< E->getSourceRange();
20697
return ExprError();
20698
}
20699
20700
S.Diag(loc, diagID) << d << orig->getSourceRange();
20701
20702
// Never recoverable.
20703
return ExprError();
20704
}
20705
20706
ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20707
if (!Context.isDependenceAllowed()) {
20708
// C cannot handle TypoExpr nodes on either side of a binop because it
20709
// doesn't handle dependent types properly, so make sure any TypoExprs have
20710
// been dealt with before checking the operands.
20711
ExprResult Result = CorrectDelayedTyposInExpr(E);
20712
if (!Result.isUsable()) return ExprError();
20713
E = Result.get();
20714
}
20715
20716
const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20717
if (!placeholderType) return E;
20718
20719
switch (placeholderType->getKind()) {
20720
case BuiltinType::UnresolvedTemplate: {
20721
auto *ULE = cast<UnresolvedLookupExpr>(E);
20722
const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
20723
// There's only one FoundDecl for UnresolvedTemplate type. See
20724
// BuildTemplateIdExpr.
20725
NamedDecl *Temp = *ULE->decls_begin();
20726
const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
20727
20728
if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
20729
Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20730
<< Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
20731
<< Loc.getSourceRange() << IsTypeAliasTemplateDecl;
20732
else
20733
Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20734
<< "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
20735
<< IsTypeAliasTemplateDecl;
20736
Diag(Temp->getLocation(), diag::note_referenced_type_template)
20737
<< IsTypeAliasTemplateDecl;
20738
20739
return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
20740
}
20741
20742
// Overloaded expressions.
20743
case BuiltinType::Overload: {
20744
// Try to resolve a single function template specialization.
20745
// This is obligatory.
20746
ExprResult Result = E;
20747
if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20748
return Result;
20749
20750
// No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20751
// leaves Result unchanged on failure.
20752
Result = E;
20753
if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20754
return Result;
20755
20756
// If that failed, try to recover with a call.
20757
tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20758
/*complain*/ true);
20759
return Result;
20760
}
20761
20762
// Bound member functions.
20763
case BuiltinType::BoundMember: {
20764
ExprResult result = E;
20765
const Expr *BME = E->IgnoreParens();
20766
PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20767
// Try to give a nicer diagnostic if it is a bound member that we recognize.
20768
if (isa<CXXPseudoDestructorExpr>(BME)) {
20769
PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20770
} else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20771
if (ME->getMemberNameInfo().getName().getNameKind() ==
20772
DeclarationName::CXXDestructorName)
20773
PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20774
}
20775
tryToRecoverWithCall(result, PD,
20776
/*complain*/ true);
20777
return result;
20778
}
20779
20780
// ARC unbridged casts.
20781
case BuiltinType::ARCUnbridgedCast: {
20782
Expr *realCast = ObjC().stripARCUnbridgedCast(E);
20783
ObjC().diagnoseARCUnbridgedCast(realCast);
20784
return realCast;
20785
}
20786
20787
// Expressions of unknown type.
20788
case BuiltinType::UnknownAny:
20789
return diagnoseUnknownAnyExpr(*this, E);
20790
20791
// Pseudo-objects.
20792
case BuiltinType::PseudoObject:
20793
return PseudoObject().checkRValue(E);
20794
20795
case BuiltinType::BuiltinFn: {
20796
// Accept __noop without parens by implicitly converting it to a call expr.
20797
auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20798
if (DRE) {
20799
auto *FD = cast<FunctionDecl>(DRE->getDecl());
20800
unsigned BuiltinID = FD->getBuiltinID();
20801
if (BuiltinID == Builtin::BI__noop) {
20802
E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20803
CK_BuiltinFnToFnPtr)
20804
.get();
20805
return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20806
VK_PRValue, SourceLocation(),
20807
FPOptionsOverride());
20808
}
20809
20810
if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20811
// Any use of these other than a direct call is ill-formed as of C++20,
20812
// because they are not addressable functions. In earlier language
20813
// modes, warn and force an instantiation of the real body.
20814
Diag(E->getBeginLoc(),
20815
getLangOpts().CPlusPlus20
20816
? diag::err_use_of_unaddressable_function
20817
: diag::warn_cxx20_compat_use_of_unaddressable_function);
20818
if (FD->isImplicitlyInstantiable()) {
20819
// Require a definition here because a normal attempt at
20820
// instantiation for a builtin will be ignored, and we won't try
20821
// again later. We assume that the definition of the template
20822
// precedes this use.
20823
InstantiateFunctionDefinition(E->getBeginLoc(), FD,
20824
/*Recursive=*/false,
20825
/*DefinitionRequired=*/true,
20826
/*AtEndOfTU=*/false);
20827
}
20828
// Produce a properly-typed reference to the function.
20829
CXXScopeSpec SS;
20830
SS.Adopt(DRE->getQualifierLoc());
20831
TemplateArgumentListInfo TemplateArgs;
20832
DRE->copyTemplateArgumentsInto(TemplateArgs);
20833
return BuildDeclRefExpr(
20834
FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20835
DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20836
DRE->getTemplateKeywordLoc(),
20837
DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20838
}
20839
}
20840
20841
Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20842
return ExprError();
20843
}
20844
20845
case BuiltinType::IncompleteMatrixIdx:
20846
Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20847
->getRowIdx()
20848
->getBeginLoc(),
20849
diag::err_matrix_incomplete_index);
20850
return ExprError();
20851
20852
// Expressions of unknown type.
20853
case BuiltinType::ArraySection:
20854
Diag(E->getBeginLoc(), diag::err_array_section_use)
20855
<< cast<ArraySectionExpr>(E)->isOMPArraySection();
20856
return ExprError();
20857
20858
// Expressions of unknown type.
20859
case BuiltinType::OMPArrayShaping:
20860
return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20861
20862
case BuiltinType::OMPIterator:
20863
return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20864
20865
// Everything else should be impossible.
20866
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20867
case BuiltinType::Id:
20868
#include "clang/Basic/OpenCLImageTypes.def"
20869
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20870
case BuiltinType::Id:
20871
#include "clang/Basic/OpenCLExtensionTypes.def"
20872
#define SVE_TYPE(Name, Id, SingletonId) \
20873
case BuiltinType::Id:
20874
#include "clang/Basic/AArch64SVEACLETypes.def"
20875
#define PPC_VECTOR_TYPE(Name, Id, Size) \
20876
case BuiltinType::Id:
20877
#include "clang/Basic/PPCTypes.def"
20878
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20879
#include "clang/Basic/RISCVVTypes.def"
20880
#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20881
#include "clang/Basic/WebAssemblyReferenceTypes.def"
20882
#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20883
#include "clang/Basic/AMDGPUTypes.def"
20884
#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20885
#define PLACEHOLDER_TYPE(Id, SingletonId)
20886
#include "clang/AST/BuiltinTypes.def"
20887
break;
20888
}
20889
20890
llvm_unreachable("invalid placeholder type!");
20891
}
20892
20893
bool Sema::CheckCaseExpression(Expr *E) {
20894
if (E->isTypeDependent())
20895
return true;
20896
if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20897
return E->getType()->isIntegralOrEnumerationType();
20898
return false;
20899
}
20900
20901
ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20902
ArrayRef<Expr *> SubExprs, QualType T) {
20903
if (!Context.getLangOpts().RecoveryAST)
20904
return ExprError();
20905
20906
if (isSFINAEContext())
20907
return ExprError();
20908
20909
if (T.isNull() || T->isUndeducedType() ||
20910
!Context.getLangOpts().RecoveryASTType)
20911
// We don't know the concrete type, fallback to dependent type.
20912
T = Context.DependentTy;
20913
20914
return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20915
}
20916
20917